text:
Q: Flutter FCM crashes when onBackgroundMessage I am trying to integrate FCM for my flutter app and I was able to successfully do that when onMessage and onResume but when the app is terminated I get a crash error and the notification won't show, my code is as below:
Future<void> firebaseMessagingBackgroundHandler(Map<String, dynamic> message) async {
  print("Handling a background message");
}

     onResume: (Map<String, dynamic> message) async {

             print(message['data']);
        }
     onMessage: (Map<String, dynamic> message) async {

             print(message['data']);
        }
onBackgroundMessage: (Map<String, dynamic> message) async {

             print(message['data']);
        }

Can anyone help out? Tho I tried to use flutterLocalNotification but I don't know how to parse the data I receive from FCM into it, below is my flutterLocalNotification code:

 FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;

  showNotification() async {
    var android = AndroidNotificationDetails(
        'channel id', 'channel name', 'channel description');
    var iOS = IOSNotificationDetails();
    var platform = NotificationDetails(android: android, iOS: iOS);

  }


text:
Q: Magento 2 - change database in etc/env.php My environment:

*

*Magento 2.0.7

*Production mode

*Cache enabled

I cloned current Database that my store has been normaly working with:

original_db

and named it:

original_db_dev

All DB details that changed are: database name, and user name. The rest (host, password) remained the same.
I change details in etc/env.php file by simply replacing appriopriate data. Then flush the cache. However, although the DB is cloned (= is exactly the same as the original one) the store it's not working. I'm getting error:

There has been an error processing your request Exception printing is
  disabled by default for security reasons. Error log record number:
  455082819174

Questions

*

*How can I found out more about the error? Nothing is generated in var/log

*How can I fix the problem?

Thanks

redpajama_set_name: RedPajamaStackExchange


text:
Q: Difference between MODWT (Maximum Overlap Discrete Wavelet Transform) and WAVEDEC/DFT (Discrete Wavelet Trasnform) in MATLAB I need to perform the Discrete Wavelet Transform of a discrete signal in MATLAB.
What is the difference between the commands MODWT and WAVEDEC?
I see that MODWT operates the Maximum Overlapped Discrete Wavelet Transform (MODWT), whereas  Wavedec performs the classical Discrete Wavelet Transform, though the function DWT.
What are the main differences between these algorithms and what is the best one in order to perform a 1-Dsignal MRA decomposition and a successive de-noising?
Thanks for your help, I tried to find information online, but I have not found a clear explanation from an engineering point of view.
Thanks.
E.

A: The main difference is that the standard DWT downsamples the signals with a factor 2 between two decomposition levels. The downside is that if you want to do that 8 times, it's only possible on a signal with length C*256 (i.e. multiples of 2^8).
The MODWT modifies the filter not the signal, between levels, which means it can handle signals of any length and suffers less from thinks like boundary effects. The downside here is that it's highly redundant: with an 8-level decomposition you have 1 approximation and 8 detail signals the same length as the original.
Both have been used for denoising, DWT is more efficient, MODWT is more robust w.r.t boundary effects.


text:
Q: Service Fabric application's root directory In my code I fail at
if (!File.Exists(_configurationFileName)) {...}

In the immediate window I made a call to Directory.GetCurrentDirectory() and it pointed me to the "work" folder rather than the "code" folder which I would have expected.
Directory.GetCurrentDirectory()
"C:\\SfDevCluster\\Data\\_App\\_Node_0\\My.Application.Type_App2\\work"

So my configuration file which is sitting right next to the executable is of course not being found.
Now I wonder what the solution is.
Since I also want to  keep running the console application I don't want to implement any "if service fabric hosting, then change current directory, ..." workaround.
Any recommendations? What about my .exe.config files (if I had any, how would they be found)?
What's the reason for Service Fabric settings the current directory to "work"? Is this some kind of security mechanism?

A: This is how i just did it change the service manifest to point at the code
<EntryPoint>
  <ExeHost>
    <Program>configui.exe</Program>
    <WorkingFolder>CodePackage</WorkingFolder>
  </ExeHost>
</EntryPoint>

A: You could do some simple reflection and get the folder the executing assembly is in, then reference that file in that location. I did this successfully for an ancillary file I needed that is deployed to the same folder as my executable.
string exePath = System.Reflection.Assembly.GetExecutingAssembly().Location;
string filePath = Path.Combine(Path.GetDirectoryName(exePath), "myfilename.txt");

A: You can select build action as 'content' and select 'copy if newer' in the properties so that it gets copied to the output folder.

A: Setting "Application Debug Mode" to "Keep Application" resolved a similar issue I was having where my files were not getting copied to the final deploy area on my local service fabric.
It had been set to "Refresh Application" which is in preview as I type this. But that mode wasn't copying my wwwroot folder over, so my view engine (Nancy in this case) was not finding my views.
Right click your service fabric project > properties > Application > Application Debug Mode > Keep Application


text:
Q: Running xunit.console.runner on OSX Have xunit tests for a Portable Class Library (which is for a xamarin forms project). I run the xunit tests in visual studio and using the xunit.runner.console on windows, and they work.
I try the same under OSX and I get this:
mono xunit.runner.console.2.2.0/tools/xunit.console.exe bin/Debug/AppTests.dll -nunit reports/xunit_reports.xml
xUnit.net Console Runner (32-bit .NET 4.0.30319.42000)
System.IO.FileNotFoundException: Could not load file or assembly 'AppTests' or one of its dependencies

Now bin/DebugAppTests.dll exists.
Can I somehow find out which dependencies the runner cannot find? Or is there a different way to run the xunit tests on osx from the command line?

A: instead xunit runner use dotnet
https://xunit.github.io/docs/getting-started/netcore/cmdline
dotnet test PATH_TO_TEST_PROJECT.csproj

I checked it with dotnet 2.1.301


text:
Q: React/React Native useState Hook not updating state from within a function - possible scope issues? I am having trouble with useState in React Native. Trying to set an image's local uri to then upload to firebase, but the setImageURI function isn't being called. I have tried console logging and other ways of determining if the block is being reached, and it is.
Code:
const [ imageURI, setImageURI ] = useState('');

    const handleImageUpload = () => {

        ImagePicker.launchImageLibrary(imagePickerOptions, response => {

            if (response.didCancel) {
                console.log('image picker canceled')
            } else if (response.error) {
                console.log('response error: ', response.error)
            } else {
                setImageURI('new uri');
                setTimeout(() => {
                    console.log('new uri: ', imageURI)
                }, 3000)
                // storageRef.putFile(response.uri).then(response => {
                //     console.log('upload successful: ', response.metadata.fullPath)
                //     // handleSubmit();
                // }).catch(error => {
                //     console.log('there has been an error: ', error)
                // })

            }
            // console.log('response: ', response)
        })
    };

Versions:
react-native-cli: 2.0.1
react-native: 0.61.5
node: v14.3.0

I threw a setTimeout() in there just to see if that would log it, but it still isn't having any effect on imageURI state object. Am I missing something with scope here? Or misunderstanding what I am doing?


text:
Q: Can't load python NMSLIB index? I'm trying to load an index of about 8.6GB using nmslib by the following commands:
search_index = nmslib.init(method='hnsw', space='cosinesimil')
search_index.loadIndex('./data/search/search_index.nmslib')

But, the following error happens:
Check failed: data_level0_memory_
Traceback (most recent call last):
search_index.loadIndex("./data/search/search_index.nmslib")
RuntimeError: Check failed: it's either a bug or inconsistent data!

My computer has only 8GB as primary memory. So, did this error happen because the index is over 8GB and could not be loaded into memory?
Thank you for any help.


text:
Q: How to get the response code form the following I need to get the ResponseCode and ResponseDescription I am using PHP
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <ProcessPaymentResponse xmlns="https://services.incard.com.au">
      <ProcessPaymentResult>
        <ResponseCode>string</ResponseCode>
        <ResponseDescription>string</ResponseDescription>
      </ProcessPaymentResult>
    </ProcessPaymentResponse>
  </soap:Body>
</soap:Envelope>

A: you need php xml parser.
use simplexml
more info here: http://in2.php.net/manual/en/simplexml.examples.php

A: You might consider using the php SoapClient, assuming they are exposing a SOAP service to
you.
Failing that there are several other things you can do:

*

*Use XPath to grab the values:
http://php.net/manual/en/simplexmlelement.xpath.php

*Use one of php's XML parsing functions to parse the XML and grab the values: http://www.php.net/manual/en/function.xml-parse-into-struct.php

A: Try this:
<?php
$str = '<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <ProcessPaymentResponse xmlns="https://services.incard.com.au">
      <ProcessPaymentResult>
        <ResponseCode>string</ResponseCode>
        <ResponseDescription>string</ResponseDescription>
      </ProcessPaymentResult>
    </ProcessPaymentResponse>
  </soap:Body>
</soap:Envelope>';

$xml = simplexml_load_string( $str );
$xml->registerXPathNamespace( 'soap', 'http://schemas.xmlsoap.org/soap/envelope/' );
$result = $xml->xpath('//soap:Body');

foreach ($result as $body) {
  echo $body->ProcessPaymentResponse->ProcessPaymentResult->ResponseCode . "
";
  echo $body->ProcessPaymentResponse->ProcessPaymentResult->ResponseDescription . "
";
}
?>

Hope this helps.

A: in
new .xml put your xml data then do the code below if you want single field of data
 <?php

$file="new.xml";

function contents($parser, $data){
    echo $data;
}

function startTag($parser, $data){
    echo "";
}

function endTag($parser, $data){
    echo "
";
}

$xml_parser = xml_parser_create();

xml_set_element_handler($xml_parser, "startTag", "endTag");

xml_set_character_data_handler($xml_parser, "contents");

$fp = fopen($file, "r");

$data = fread($fp, 80000);

if(!(xml_parse($xml_parser, $data, feof($fp)))){
    die("Error on line " . xml_get_current_line_number($xml_parser));
}

xml_parser_free($xml_parser);

fclose($fp);

$xml = simplexml_load_string( $data);
$xml->registerXPathNamespace( 'soap', 'http://schemas.xmlsoap.org/soap/envelope/' );
$result = $xml->xpath('//soap:Body');

foreach ($result as $body) {
  echo $body->ProcessPaymentResponse->ProcessPaymentResult->ResponseCode . "
";
  echo $body->ProcessPaymentResponse->ProcessPaymentResult->ResponseDescription . "
";
}
?>

if you want n number of data try this
<?php
$file="new.xml";

function contents($parser, $data){
    echo $data;
}

function startTag($parser, $data){
    echo "";
}

function endTag($parser, $data){
    echo "
";
}

$xml_parser = xml_parser_create();

xml_set_element_handler($xml_parser, "startTag", "endTag");

xml_set_character_data_handler($xml_parser, "contents");

$fp = fopen($file, "r");

$data = fread($fp, 80000);

if(!(xml_parse($xml_parser, $data, feof($fp)))){
    die("Error on line " . xml_get_current_line_number($xml_parser));
}

xml_parser_free($xml_parser);

fclose($fp);
    $xml = simplexml_load_string($data);
    $xml->registerXPathNamespace('soap:Envelope', 'http://schemas.xmlsoap.org/soap/envelope/');
    foreach ($xml->xpath('//soap:Envelope:ResponseCode') as $item) {
        echo (string) $item;
    }
    foreach ($xml->xpath('//soap:Envelope:ResponseDescription') as $item) {
        echo (string) $item;
    }
    ?>


text:
Q: Like operator or using wildcards in LINQ to Entities I'm using LINQ 2 Entities.
Following is the problem:
string str = '%test%.doc%'
.Contains(str) // converts this into LIKE '%~%test~%.doc~%%'

Expected Conversion: LIKE '%test%.doc%'
If it was LINQ 2 SQL, I could have used SqlMethods.Like as somebody answered it in my previous question. But now as I'm using L2E not L2S, I need other solution.

A: Following on from Magnus' correct answer, here is an extension method that can be re-used, as I needed in my project.
public static class LinqExtensions
{
    public static Expression<Func<T, bool>> WildCardWhere<T>(this Expression<Func<T, bool>> source, Expression<Func<T, string>> selector, string terms, char separator)
    {
        if (terms == null || selector == null)
            return source;

        foreach (string term in terms.Split(new[] { separator }, StringSplitOptions.RemoveEmptyEntries))
        {
            string current = term;
            source = source.And(
                Expression.Lambda<Func<T, bool>>(
                    Expression.Call(selector.Body, "Contains", null, Expression.Constant(current)),
                    selector.Parameters[0]
                )
            );
        }

        return source;
    }
}

Usage:
var terms = "%test%.doc%";
Expression<Func<Doc, bool>> whereClause = d => d;
whereClause = whereClause.WildCardWhere(d => d.docName, terms, '%');
whereClause = whereClause.WildCardWhere(d => d.someOtherProperty, "another%string%of%terms", '%');
var result = ListOfDocs.Where(whereClause).ToList();

The extension makes use of the predicate builder at http://petemontgomery.wordpress.com/2011/02/10/a-universal-predicatebuilder/. The resulting sql does a single table scan of the table, no matter how many terms are in there. Jo Vdb has an example you could start from if you wanted an extension of iQueryable instead.

A: You can try use this article, where author describes how to build a LIKE statement with wildcard characters in LINQ to Entities.
EDIT: Since the original link is now dead, here is the original extension class (as per Jon Koeter in the comments) and usage example.
Extension:
public static class LinqHelper
{
    //Support IQueryable (Linq to Entities)
    public static IQueryable<TSource> WhereLike<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, string>> valueSelector, string value, char wildcard)
    {
        return source.Where(BuildLikeExpression(valueSelector, value, wildcard));
    }

    //Support IEnumerable (Linq to objects)
    public static IEnumerable<TSource> WhereLike<TSource>(this IEnumerable<TSource> sequence, Func<TSource, string> expression, string value, char wildcard)
    {
        var regEx = WildcardToRegex(value, wildcard);

        //Prevent multiple enumeration:
        var arraySequence = sequence as TSource[] ?? sequence.ToArray();

        try
        {
            return arraySequence.Where(item => Regex.IsMatch(expression(item), regEx));
        }
        catch (ArgumentNullException)
        {
            return arraySequence;
        }
    }

    //Used for the IEnumerable support
    private static string WildcardToRegex(string value, char wildcard)
    {
        return "(?i:^" + Regex.Escape(value).Replace("\\" + wildcard, "." + wildcard) + "$)";
    }

    //Used for the IQueryable support
    private static Expression<Func<TElement, bool>> BuildLikeExpression<TElement>(Expression<Func<TElement, string>> valueSelector, string value, char wildcard)
    {
        if (valueSelector == null) throw new ArgumentNullException("valueSelector");

        var method = GetLikeMethod(value, wildcard);

        value = value.Trim(wildcard);
        var body = Expression.Call(valueSelector.Body, method, Expression.Constant(value));

        var parameter = valueSelector.Parameters.Single();
        return Expression.Lambda<Func<TElement, bool>>(body, parameter);
    }

    private static MethodInfo GetLikeMethod(string value, char wildcard)
    {
        var methodName = "Equals";

        var textLength = value.Length;
        value = value.TrimEnd(wildcard);
        if (textLength > value.Length)
        {
            methodName = "StartsWith";
            textLength = value.Length;
        }

        value = value.TrimStart(wildcard);
        if (textLength > value.Length)
        {
            methodName = (methodName == "StartsWith") ? "Contains" : "EndsWith";
        }

        var stringType = typeof(string);
        return stringType.GetMethod(methodName, new[] { stringType });
    }
}

Usage Example:
string strEmailToFind = "%@yahoo.com"

IQueryable<User> myUsers = entities.Users.WhereLike(u => u.EmailAddress, strEmailToFind, '%');

or, if you expect your users to be more accustomed to Windows Explorer-styled wildcards:
string strEmailToFind = "*@yahoo.com"

IQueryable<User> myUsers = entities.Users.WhereLike(u => u.EmailAddress, strEmailToFind, '*');

A: Use a regular expression...
The following will print out all of the files in the current directory that match test.doc*  (dos wildcard style - which I believe is what you're asking for)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;

namespace RegexFileTester
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] _files = Directory.GetFiles(".");
            var _fileMatches =  from i in _files
                                where Regex.IsMatch(i, ".*test*.doc.*")
                                //where Regex.IsMatch(i, ".*cs")
                                select i;
            foreach(var _file in _fileMatches)
            {
                Console.WriteLine(_file);
            }
        }
    }
}

A: Split the String
var str =  "%test%.doc%";
var arr = str.Split(new[]{'%'} ,StringSplitOptions.RemoveEmptyEntries);
var q = tblUsers.Select (u => u);
foreach (var item in arr)
{
    var localItem = item;
    q = q.Where (x => x.userName.Contains(localItem));
}

A: The SQL method PATINDEX provides the same functionality as LIKE. Therefore, you can use the SqlFunctions.PatIndex method:
.Where(x => SqlFunctions.PatIndex("%test%.doc%", x.MySearchField) > 0)

A: So I was trying the same thing - trying to pair down a List to return all candidates that matched a SearchTerm. I wanted it so that if a user typed "Arizona" it would return everything regardless of case that had Arizona. Also, if the user typed "Arizona Cha", it would return items like "Arizona License Change". The following worked:
private List<Certification> GetCertListBySearchString()
    {
        string[] searchTerms = SearchString.Split(' ');
        List<Certification> allCerts = _context.Certifications.ToList();

        allCerts = searchTerms.Aggregate(allCerts, (current, thisSearchString) => (from ac in current
                                                                                where ac.Name.ToUpper().Contains(thisSearchString.ToUpper())
                                                                                select ac).ToList());
          return allCerts;
    }


text:
Q: ASP.NET checkbox changes focus? I have a checkbox control, and when it's clicked, the focus of the page changes to the top--the window scrolls to the top of the page.
Nowhere in the code am I specifying a change in focus, either in JavaScript on codebehind.
What could be causing this?

A: Is the checkbox set with Autopostback = true?  This could cause the page to postback and reset the form.


text:
Q: How do I correctly write this if statement? Suppose that I get the values for valid, d ,sn from a function that I introduced in my program. Then I pass it through the following if statement in python to output the result.
I want the program to print the following statements:

*

*print  on if the sn >= 0 and  1<d <90.

*print off-right if the sn<0.

*print off-left if the d>=90

*other than that, for anything that is not valid outputs unknown.

Here is what I wrote, how do I include d when checking the statement?
if valid:
    if sn >= 0 and 1<d <90:
        print(" on ")
    else:
        print("off")
else:
    print("unknown")

A: if valid:
   if sn >= 0 and d > 1 and d < 90:
      print(" on ")
   elif sn < 0:
      print("off-right")
   elif d >= 90:
      print("off-left")
else:
   print("unknown")

A: Not sure what you want. But most probably you want to do this i guess?

if valid:
    if sn >= 0 and (d>1 and d<90):
        print(" on ")

    else:
        if sn<0:
            print("off-right")
        elif d>=90:
            print('off-left')
else:
    print("unknown")

This is a self explanatory answer..
If you get confused by 1<d<90 then you can use what i did above


text:
Q: Random colour within a list of pre-defined colours Here is my actionscript that edited from http://circlecube.com/2009/02/random-movement-brownian-revisited-for-as3/:
//number of balls
var numBalls:uint = 50;
var defaultBallSize:uint = 8;

//init
makeDots();

function makeDots():void {
//create desired number of balls
for (var ballNum:uint=0; ballNum<numBalls; ballNum++){
    var c1:Number = randomColor();
    var c2:Number = randomColor();

    //create ball
    var thisBall:MovieClip = new MovieClip();
    thisBall.graphics.beginFill(c1);
    //thisBall.graphics.lineStyle(defaultBallSize, 0);
    thisBall.graphics.drawCircle(defaultBallSize, defaultBallSize, defaultBallSize);
    thisBall.graphics.endFill();

    addChild(thisBall);

    //coordinates
    thisBall.x = Math.random() * stage.stageWidth;
    thisBall.y = Math.random() * stage.stageHeight;
    //percieved depth
    //thisBall.ballNum = ballNum;
   // thisBall.depth = ballNum/numBalls;
    //thisBall.scaleY = thisBall.scaleX = thisBall.alpha = ballNum/numBalls;
    //velocity
    thisBall.vx = 0;
    thisBall.vy = 0;
    thisBall.vz = 0;

    //ball animation
    thisBall.addEventListener(Event.ENTER_FRAME, animateBall);
}
}

var dampen:Number = 0.95;
var maxScale:Number = 1.3;
var minScale:Number = .3;
var maxAlpha:Number = 1.3;
var minAlpha:Number = .3;
function animateBall(e:Event):void{
var thisBall:Object = e.target;
//apply randomness to velocity
thisBall.vx += Math.random() * 0.2 - 0.1;
thisBall.vy += Math.random() * 0.2 - 0.1;
thisBall.vz += Math.random() * 0.002 - 0.001;

thisBall.x += thisBall.vx;
thisBall.y += thisBall.vy;
//thisBall.scaleX = thisBall.scaleY += thisBall.vz;
//thisBall.alpha += thisBall.vz;
thisBall.vx *= dampen;
thisBall.vy *= dampen;
thisBall.vz *= dampen;

if(thisBall.x > stage.stageWidth) {
    thisBall.x = 0 - thisBall.width;
}
else if(thisBall.x < 0 - thisBall.width) {
    thisBall.x = stage.stageWidth;
}
if(thisBall.y > stage.stageHeight) {
    thisBall.y = 0 - thisBall.height;
}
else if(thisBall.y < 0 - thisBall.height) {
    thisBall.y = stage.stageHeight;
}

if (thisBall.scaleX > maxScale){
    thisBall.scaleX = thisBall.scaleY = maxScale;
}
else if (thisBall.scaleX < minScale){
    thisBall.scaleX = thisBall.scaleY = minScale;
}
if (thisBall.alpha > maxAlpha){
    thisBall.alpha = maxAlpha;
}
else if (thisBall.alpha < minAlpha){
    thisBall.alpha = minAlpha;
}
}

function randomColor():Number{
return Math.floor(Math.random() * 16777215);
}

The colour of the balls are totally random and I was wondering if it was possible to make it so the colours would be random but from a pre-defined list of colours.
Thanks a lot.

A: You can easily accomplish that by using an array of colors:
var colors:Array = [0xFF0000, 0x00FF00, 0x0000FF];

function randomColor():uint
{
    return colors[int(Math.random()*colors.length)];
}

The above code will select randomly from red, green and blue. You can add new colors to the randomization by simply adding their hex code to the array.

A: function randomColor():Number{
    var my_clrs_arr:Array =
        new Array(0xFFCC00,0xFF0000, 0xFFFF00, 0xFFFFFF, 0xCCCC00, 0xFACC00);
    var random_num = Math.floor(Math.random() * my_clrs_arr.lemgth);
    return  my_clrs_arr[random_num];
}


text:
Q: Find top k tag at any point in time, from a stream of tags I need to find the top k tags from a stream of tags, at any point in time during the flow.
I am able to find the top K tags at the end of the flow, by using HashMap and PriorityQueue of size K. But, i am not sure on how to modify this approach to find top tags during the stream of tags, i.e if the tag is already among top ten and just update it's count, instead of adding the same tag again with the new count.

A: There are several ways to do what you're asking. The simplest is to just re-compute the top K tags every time you're asked. That is, you maintain a histogram of some kind, and when somebody asks for the top K, you run through the algorithm that uses a priority queue to figure out the top K items. This has the benefit of simplicity, but it takes time.
You could maintain that list of the top K if you like, and whenever some other item is updated you check to see if its new count is higher than the count for the smallest item in the top K. If it is, then replace that smallest item with the newly updated item. That should be easy enough to do with an auxiliary data structure. The primary drawback here is the memory it takes to keep a copy of the top K items.
Another way to do it would be to keep your hash map with counts, and an additional linked list that orders things by descending count. The data in the hash table contains references to the linked list nodes. Whenever an item is updated, you update its count and then compare its count with the count of the item just before it in the linked list. If the new count is greater than the count of the item's predecessor, move the item up in the list to keep it in order. Of course, you might have to move it multiple times. This is essentially an insertion sort.
The benefit of that approach is that the top K items are always at the front of the list. The drawback is potentially performance. If you have a lot of items and your range of counts is small, each update can cost O(n) time. You can speed that up some by keeping track of the next higher item so that, for example, if there are 100 items with a count of 1, you have a reference to the last item with a count of 2. So when you increase the count of an item with count 1, you don't have to sift it up through all of the items with count 1. This costs you more memory (in the worst case, O(n) memory), but it makes insertion O(1), and keeps the list in order.
There are other possibilities, all of which make tradeoffs between speed and memory usage. Which you choose depends on how much memory you want to spend and how fast you want this thing to be.


text:
Q: I want to get recipient_signing_uri from the Docusign API response but it returns null Here is the code
public function send(Request $request): object
    {

        $apiClient = new ApiClient();
        $apiClient->getOAuth()->setOAuthBasePath(env('DS_AUTH_SERVER'));
        try {
            $accessToken = $this->getToken($apiClient);
        } catch (\Throwable $th) {
            return back()->withError($th->getMessage())->withInput();
        }

        $userInfo = $apiClient->getUserInfo($accessToken);
        $accountInfo = $userInfo[0]->getAccounts();
        $apiClient->getConfig()->setHost($accountInfo[0]->getBaseUri() . env('DS_ESIGN_URI_SUFFIX'));

        $envelopeDefenition = $this->buildEnvelope($request);
        try {
            $envelopeApi = new EnvelopesApi($apiClient);
            $result = $envelopeApi->createEnvelope($accountInfo[0]->getAccountId(), $envelopeDefenition);
            dd($result);
        } catch (\Throwable $th) {
            return back()->withError($th->getMessage())->withInput();
        }
        return view('backend.response')->with('result', $result);
    }

When I print $result variable it returns a response like this
container: array:8 [
    "bulk_envelope_status" => null
    "envelope_id" => "b634f8c5-96c5-4a18-947f-59418d8c4e03"
    "error_details" => null
    "recipient_signing_uri" => null
    "recipient_signing_uri_error" => null
    "status" => "sent"
    "status_date_time" => "2023-02-16T07:24:39.1570000Z"
    "uri" => "/envelopes/b634f8`your text`c5-96c5-4a18-947f-59418d8c4e03"
  ]

I want to get the value of recipient signing uri in response but in my case it returns null
How I can achieve this? Will anyone suggests?

A: createEnvelope creates the envelope. It does not give you an URL for an embedded recipient view (signing ceremony). In order to get that URL, you need to make an additional call to
EnvelopeViews:createRecipient/
See this page for more info.
Also
$apiClient->getConfig()->setHost($accountInfo[0]->getBaseUri() . env('DS_ESIGN_URI_SUFFIX'));

You are using the first entry in the UserInfo returned data's accountInfo array. That's not a good idea. Instead, look for the entry that is the user's default account.
Or if your application is designed to work with a specific eSign account, then make sure the user has access to that account.
It is very common for DocuSign customers to have access to more than one account.


text:
Q: Format currency with minus sign using regex I have simple function that is formatting string as currency - it is adding spaces every 3 characters:
function addSpace(n) {
    var rx = /(\d+)(\d{3})/;
    return String(n).replace(/^\d+/, function (w) {
        while (rx.test(w)) {
            w = w.replace(rx, '$1 $2');
        }
        return w;
    });
}

So when I use it like so:
addSpace("1234567.89")

I get:
"1 234 567.89"

but I can't get same behaviour for negative numbers.
I would like to get -1 234 567.89 for addSpace("-1234567.89")
How should I change my function to get that result? I tried adding -? at beginning of rx but that didn't help.
I know I could search for - in string and if found add it to beginning, but I want to avoid that.

A: Just modify your regex to:
/^-?\d+/

Output:
"-1 234 567.89"

Demo

A: Pass - as optional argument, Use /^-?\d+/ as RegEX
return String(n).replace(/^-?\d+/, function (w) {
    while (rx.test(w)) {
        w = w.replace(rx, '$1 $2');
    }
    return w;
});

DEMO


text:
Q: javascript check image existence I am trying to show either google map or image. So, what i want is that for default i want to show the image, if image does not exist, show google map. To do so, as a default I disable google maps with  #map_canvas {display:none;}. Then, I need something like a boolean conditions that checks existence of image then, returns true or false, if it is false, display maps, by changing display="block";. But, I do not how to do that exactly, Can you please help me ?
By the way, two codes separately work fine.

A: To show #map_canvas if the image does not load into #worldMap use
var img = document.getElementById("worldMap");
img.src = "http://www.freeworldmaps.net/download/maps/political-world-map-big.gif";

img.onerror = function( ) {
    img.style.display = "none";
    document.getElementById("map_canvas").style.display = "block";
}

You obviously have to not specify the src attribute in your img tag but set it as above when the page loads.
Fiddle here


text:
Q: Flutter app does not work on a real iOS device (white screen) Created a test application flutter create hello_world.
flutter run on the ios simulator launches the application perfect - it works!
But when launched on a real iOS device, appears windows the "Local Network" -> press "allow", and after only white screen.
iOS 14.7.1
Xcode 12.5.1
Signing & Capabilities - no error
flutter doctor -v

[✓] Flutter (Channel stable, 2.2.3, on macOS 11.5 20G71 darwin-x64, locale
    ru-RU)
    • Flutter version 2.2.3 at /Users/incognito/Developer/flutter
    • Framework revision f4abaa0735 (4 weeks ago), 2021-07-01 12:46:11 -0700
    • Engine revision 241c87ad80
    • Dart version 2.13.4

[✓] Android toolchain - develop for Android devices (Android SDK version 31.0.0)
    • Android SDK at /Users/incognito/Library/Android/sdk
    • Platform android-31, build-tools 31.0.0
    • Java binary at: /Applications/Android
      Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.8+10-b944.6916264)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 12.5.1, Build version 12E507
    • CocoaPods version 1.10.1

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 4.2)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.8+10-b944.6916264)

[✓] Connected device (2 available)
    • iPhone 12 mini (mobile) • 1CE9DEC7-D645-4C14-A3A5-79C4B1C8AB9F • ios
      • com.apple.CoreSimulator.SimRuntime.iOS-14-5 (simulator)
    • Chrome (web)            • chrome                               •
      web-javascript • Google Chrome 92.0.4515.107
    ! Error: iPhone No Name is busy: Waiting for Device. Xcode will continue
      when iPhone No Name is finished. (code -10)

Xcode console
2021-07-30 01:27:14.959824+0300 Runner[440:12621] Metal API Validation Enabled
2021-07-30 01:27:15.028878+0300 Runner[440:12621] fopen failed for data file: errno = 2 (No such file or directory)
2021-07-30 01:27:15.028922+0300 Runner[440:12621] Errors found! Invalidating cache...
2021-07-30 01:27:15.076411+0300 Runner[440:12621] Warning: Unable to create restoration in progress marker file
2021-07-30 01:27:15.088662+0300 Runner[440:12868] [VERBOSE-2:shell.cc(93)] Dart Error: Can't load Kernel binary: Invalid kernel binary format version.
2021-07-30 01:27:15.088704+0300 Runner[440:12868] [VERBOSE-2:dart_isolate.cc(170)] Could not prepare isolate.
2021-07-30 01:27:15.088835+0300 Runner[440:12868] [VERBOSE-2:runtime_controller.cc(382)] Could not create root isolate.
2021-07-30 01:27:15.088861+0300 Runner[440:12868] [VERBOSE-2:shell.cc(576)] Could not launch engine with configuration.
2021-07-30 01:27:15.115109+0300 Runner[440:12882] flutter: Observatory listening on http://127.0.0.1:50825/Ibq99VrylBU=/

UPDATE
footprint for posterit:
Solution - delete the bin/cache directory in your Flutter installation directory, then run flutter doctor and try again.

A: footprint for posterit: Solution - delete the bin/cache directory in your Flutter installation directory, then run flutter doctor and try again.


text:
Q: Using Google Apps script, how to check if an email has a pdf attached to it, then forward it to another email address? I managed to create a function that converts an email to a pdf and then it forwards it to another email address ( I used this great library made by Mike Greiling  :https://github.com/pixelcog/gmail-to-pdf).
but now I want to create another function that checks if the email already has an attachment, and then forward it right away.
here's my working function:
function saveExpenses() {

    GmailUtils.processStarred( 'label: test', 5, function(message) {

    // create a pdf of the message
    var pdf = GmailUtils.messageToPdf(message);

    // prefix the pdf filename with a date string
    pdf.setName(GmailUtils.formatDate(message, 'yyyy/MM/dd - ') + pdf.getName());

     // send confirmation email to the original sender
     var confirmationEmail = message.getFrom();

     // Get the name of the document to use as an email subject line.
     var subject =  pdf.getName();

     var body = "This is a confirmation that this receipt has been sent";

     // Send a confirmation email to the sender
     GmailApp.sendEmail(confirmationEmail, subject, body,  {attachments: [pdf]});

    return true;

  });
 }
}

A: Ok, I found the solution, actually it was pretty easy.
I guess I didn't think enough, so basically I just get all the attachments from the message with the function getAttachmentswhich returns an array of attachments, I then just check if the length of the array is greater than 0 ( which means there are attachments in the email )
and if the result is 0, it means there are no attachments.
Here is what I did :
var attachment = message.getAttachments();

    if (attachment.length > 0 ) {
          // I add the code to deal with the attachment

    } else if  (attachment.length == 0 ) {
          // I add the code that I posted in the question above
    }


text:
Q: even function representation given any even function $ g(x)=g(-x) $ is it always possible to write it as the product of two functions ? i mean
$ g(x) = f(x)f(-x) $ so $ g(x) $ is always an even function even though $ f(x) $ it isn't
for example given the Riemann Xi function $ \xi(1/2+s)= \xi(1/2-s) $ can we represent it as the product of two functions ? $ \xi(1/2+s)=f(s)f(-s) $
in this case and using the Hadamard product $ f(x)= \prod _{n}(1- \frac{ix}{n}) $

A: Consider $g(x)=-5+x^2$ then $g$ is even and $g(0)=-5<0$. Now if $g(x)=f(x)f(-x)$ for some $f$ then $g(0)=f(0)^2\geq 0$, a contradiction.

A: There are many irreducible even functions over real numbers,which is a whole class of function that contradicts your statement.

A: As already mentioned by @pritam $g(0) < 0$ will lead to a contradiction. If we have $g(0) \ge 0$ the function
$$f(x)=\begin{cases}g(x) &; x > 0 \\ \sqrt{g(0)} &; x=0 \\ 1 &;x < 0 \end{cases}$$
would be a simple function $f(x)$ with $g(x)=f(x)f(-x)$.
If we allow complex values for $f$ then $f=\sqrt{g}$ would be a solution where $\sqrt{\cdot}$ is defined as one steam of the complex square root.


text:
Q: Should I post a question if I know the answer is "it's a bug"? Let's assume that I've found some behaviour in a language/library/client etc. that is definitively, provably, incorrect; for instance a function called 5 times executes 6 times in one context in one client and 5 times everywhere else (don't ask). I realise this sounds arrogant and that the typical answer is that it's a problem with the code rather than anything else but let's assume, for the sake of argument, that I'm correct; I've done my research extremely thoroughly and I'm certain.
I would really like to whether or not this behaviour is expected, because it's entirely possible me and my colleagues are completely unaware of some "feature" that's causing what appears, at first glance, to be a bug. However, I don't ask the question because I'm fairly certain it's a bug.
If it is a bug the question becomes a statement of my investigation followed by the "Is this a bug or is it some feature I'm unaware of?". The answer would either be "It's a bug." or a description of the problem. I might be able to provide the "bug" answer at the same time if I can find a verified bug report.
This doesn't appear to be the sort of question/answer that would fit Stack Overflow particularly well. Do you agree or disagree? Why?
This question (the meta one) has, I think, two answers. I work mostly with two technologies, Python and Oracle. Oracle is so closed source that you can lose your support licence if you post details of a bug report in the wider world (though some Oracle DBAs have still ripped it to pieces and can answer what seem like impossible questions - nothing can be truly closed). Python is so open source that you can view the original source code.
Would your answer to this question be different if the language/library/client etc. in question was open source or closed?
Apologies for the gratuitous bolding but I think the question marks are in the correct places here and I couldn't find a less ostentatious way of making them stand out.

A: Ask under the assumption it isn't a bug. Worst case scenario, it is a bug, but you've still confirmed this, where an answerer has hopefully given a quality answer explaining their findings. Best case scenario, it isn't a bug, but a fault with your implementation, and the answerer has given you a solution.
Another answer could confirm it is a bug, but provide a workaround, again useful to you and the community. So yes, absolutely ask, but try to avoid jumping to conclusions in your question.

A: Rather than asking, "Is this a bug or a feature?"  simply ask, "Why does this produce X?  I expected it to produce Y instead."  The answer to that question may be "it's a bug", or it could be an explanation of how you're improperly observing the results, configuring your application, or whatever.  In any case, it's much more likely to produce a quality answer.  When you ask "why", you can get a quality, detailed explanation of what is wrong.  When you ask, "is it A or B" it's just too tempting to answer with nothing more than "A" or "B", which just isn't as helpful.

A: That depends on several factors. Do you have something useful to say, beyond the existence of the bug?

*

*Is the bug difficult to diagnose? If so, post a question with the symptoms and an answer that pinpoints where the bug is.

*Do you have a non-obvious workaround? If so, post a question describing the situation in which the bug occcurs, and an answer showing this workaround.

If the Q&A pair is just "if the user clicks 5 times then the event is triggered 6 times" → "it's a bug", it doesn't help to have it around. But if you have more information to share that could help other people who encounter the same bug, please do.
Keep in mind that SO is not a place to report bugs — do that with the maintainer of the application of library. If there is a public bug tracker, please link to the bug. If you know what versions are affected by the bug, please mention that.

A: The two things to remember are:

*

*If there's a bug in a platform, there's also a solution the programmer will eventually implement, even if it means working around the platform.

*Asking [x] or [y] questions is less helpful, as it prompts answers like "it's [x/y]."

Everything else I write is simply a deduction from these two points.
As the question asker, it's your responsibility to write helpful questions. This means your questions should be open-ended enough for someone to (potentially) answer "it's not actually a bug," or give a more helpful response as to why it is a bug.
However, as you've noted, you can't really be completely confident, unless you've looked through the source and spotted the line (in which case, why are you asking a question?), that what you've found is a bug in the platform. The better way is to phrase the question so that the answerer can provide any form of solution.
The answerer has two responsibilities in this case. It's simply not good enough to say "this is a bug." Instead, the answerer should be looking to a solution for the problem. You know as well as I that solutions don't necessarily mean fixing the exact code at hand - the answerer should respond with this in mind, providing pointers which should help in either a) working around the problem, or b) creating a new and similar solution entirely (if succinctly possible).

A: Blatantly stating there is a bug in a major framework is usually a bad idea. For the most part this is the route inexperienced users take. It probably turns out that they didn't frobulate the barelator.
If it was truly a bug, then there is nothing anyone but the author of the related code can do to fix it. No answer from a non author will fix the bug.
What can potentially get fixed is the behavior the bug is causing. Stating the behavior that was expected but what actually happened can be beneficial because then answers can either address the bug (if it is will known), provide a workaround, an alternative, or all of these.
If you know the answer is a bug, then post the question anyway, but make sure that the behavior is the centerpiece of the question and give as much information on reproducing the behavior as possible. Others can benefit from those answers. If the answer truly is "this is not possible with the current version" then at least that reference is there as well.


text:
Q: How to scrollTop an anchor in home page by another page (eg.: about) Has anyone had this problem before? I am on an internal page (like about.html) and I want to scrollTop to an anchor in home page (like home.html#sectionID), but I don't know how can I do that with jQuery.. I've already tried some stuffs but it doesn't work.
Here is my actual code that works if I am in the home page..
  $(".anchor-link").click(function(e) {
    e.preventDefault();
    $('html, body').animate({
        scrollTop: $( $(this).attr('href') ).offset().top + (-117)
    }, 1000);
    return false;
  });

A: Instead of using $(this).attr('href'), use any selector in the top of page where you want to scroll.
If you have #home id in top then you need to use:
$('html, body').animate({
    scrollTop: $('#home').offset().top + (-117)
}, 1000);


text:
Q: Conflicting versions of ASP.NET Web Pages detected I'm receiving the following error when I run my ASP.NET web project:
Conflicting versions of ASP.NET Web Pages detected: specified version is "2.0.0.0", but the version in bin is "3.0.0.0". To continue, remove files from the application's bin directory or remove the version specification in web.config.
The answer on this question solves this problem - in my Web.config, switching
<add key="webpages:Version" value="2.0.0.0"/>

to
<add key="webpages:Version" value="3.0.0.0"/>

allows me to successfully run my site.
Unfortunately, a coworker who recently pulled down a clean copy of the repository is receiving the exact opposite error:
Conflicting versions of ASP.NET Web Pages detected: specified version is "3.0.0.0", but the version in bin is "2.0.0.0".
He can solve the problem by changing the webpages:Version value back to "2.0.0.0".
What is the root cause of this error, and how can my coworker and I use the same version in our Web.config?


text:
Q: IPv4 to IPv6 DNS possible? I setup proxy server 3proxy on my VPS which uses NAT IP4 address but offers IPv6 subnet /64 address I success make  3proxy contact outside world using IPv6 ,
But I face other issue many websites didn't have AAAA/IPv6 record at all which was surprise to me , e/g twitter.com can't be resolved .
So is it possible transfer websites IPv4 address to IPv4 so it will be available to the IPv6 proxy users !
Edit I was able to reach IPv4 site temporary by letting the proxy resolve IPv4 if IPv6 not available -64 adding this line 3proxy.cfg.
proxy -64 -n  -p66505 -a  -i0.0.0.0  -e2a04:f2a7:26:a143:3815:0abf:8723:1000
Looks like 3proxy tries to resolve host address with Ipv6 if it fails tray with current server IPv4 and bring back data to the proxy client (whether he is connection via IPv4 or IPv6) .
PS After testing IPv6 only connection looks like only Google/YT/facebook and few other website are supporting IPv6 special that have cloudflare the rest of Internet are dark (reddit/twitter/) with no AAAA host record .

A: Yes, but that's not enough. Even if you put an IPv4 address in an AAAA record, IPv6-only clients still will not be able to contact it. (They can't talk using IPv6 packets because the IPv4-only destination won't understand them, and they can't talk using IPv4 packets because the IPv6-only source won't understand them.) So this needs to be paired with packet translation on the router.
Most commonly, you'll see NAT64 for the packet translation (from v6-only clients to v4-only services), and DNS64 for the generation of fake AAAA records for those clients. A common NAT64 translator is Tayga (although some ISPs have published their own open-source projects), and several DNS resolvers including Bind9 can do DNS64. Google Public DNS also has special servers which perform DNS64.
But, of course, the NAT64 gateway itself must be able to use IPv4. If your current server cannot access the IPv4 Internet, well, that means it cannot.


text:
Q: BufferGeometry transparency In BufferGeometry, we can use material setting {vertexColors: THREE.FaceColors} to set different colors for faces. But there is no way to set transparency.
How do you set transparency for different faces in BufferGeometry?

A: This is something that has been solved in the dev branch.
Take a look at this example:
https://github.com/mrdoob/three.js/blob/dev/examples/webgl_buffergeometry_rawshader.html


text:
Q: Show Interfaces in ArgoUml Sequence diagram I am using ArgoUml to draw sequence diagram. But how can i show interface classes along with the implementation using ArgoUML?

A: A ClassifierRole can have either an Interface or a Class associated with it, since they're both subtypes of Classifier.  Just drag the classes or interfaces that you want to work with onto the Sequence Diagram and start drawing Actions between them.


text:
Q: How to bind the mouse i wish bind the mouse icon in a Visual Brush,i.e i have a Canvas and so i add  A visual Brush to bind whole content of the Canvas but now i wish bind also when the mouse move the Visual Brush can reproduce the movement of the mouse into the Canvas.
Do you have any idea how work out this step/feature?
Thanks so much.
ahh i forget i wish develop this feature in WPF
Cheers
EDIT:
Maybe im not clear to explain my request so i will link a webpage that recreate the same effect Example
here you can understand better infact i wish reproduce the same effect of the mouse binding in a small window and when the mouse move in the main window the shape in the small window will follow its movement.
Sorry my English is not good.
Thanks

A: Mitsu Furuta has a good example of how to do it in this blog post. Just skip the part about Surface and the popfly duck ;)


text:
Q: Skype symbol in cover letter made with moderncv latex I want to include the skype symbol in the cover letter made with modern cv.
I cannot find anything that suites me. I found several cases where the symbol of skype was included after the command \begin{document}. I want to include the skype symbol before.
Here below a working example:
\documentclass[11pt,a4paper,roman]{moderncv}
\usepackage[UKenglish]{babel}
\makeatletter
\definecolor{ashgrey}{rgb}{0.7, 0.75, 0.71}
\moderncvstyle{classic}

\newcommand\subject[1]{\def\@subject{#1}}          % style options are 'casual'
\moderncvcolor{green}                              % color options 'blue' (default), 'orange', the
\usepackage[utf8]{inputenc}                       % if you are not using xelatex ou lualatex, replace

\usepackage[scale=0.75]{geometry}
\name{XXXX}{XXXX}
\address{XXXX
}{XXXX}
\phone[mobile]{XXXX}                   % optional, remove / comment the line if not wanted
\email{XXXX}                           % optional, remove / comment the line if not wanted
\usepackage{ragged2e}
\usepackage{xcolor}
\makeatother

\begin{document}

\justify
\sloppy

\recipient{\mdseries To XXXX}{Phone: XXXX\\ XXXX \\ XXXX \\ XXXX}

\date{\today}

\title{Some fancy title}
\opening{ \textbf{:XXXXX}

\end{document}


text:
Q: In need of a perspective function example with explicit math In order to help me understand perspective functions, can someone provide me with a simple example that uses numbers?
Let's say I have the perspective function $P : \mathbb{R}^{n+1} \to  \mathbb{R}^n$, with domain $P = \mathbb{R}^n \times \mathbb{R}_{++}$, as $P(z,t) = \frac{z}t$. (Here $\mathbb{R}^{++}$ denotes the set of positive numbers: $\mathbb{R}_{++} = \{x \in \mathbb{R} | x > 0\}$.)
Now let's say I have a poyhedron defined in $\mathbb{R}^{3}$ as $\{x \in \mathbb{R}^{3}| -1\leq x\leq1\}$ so it'd be a cube centered at the origin. If I put that set into my prospective function, what comes out? If I go according to the definition of a perspective function, I would imagine the answer would be in $\mathbb{R}^{2}$ with a square at the origin.
But I don't see the math, so how would I describe my cube in order to pass it through a perspective function to get a square?
As you can see, I'm extremely confused, so any help  is appreciated


text:
Q: outOfMemoryError:java heap public class seventhma {

    XSSFSheet m_sheet;
    int m_iNbRows;
    int m_iCurrentRow = 0;
    private static final String JAVA_TOSTRING = "EEE MMM dd HH:mm:ss zzz yyyy";

    public seventhma(XSSFSheet sheet) {
        m_sheet = sheet;
        m_iNbRows = sheet.getPhysicalNumberOfRows();
    }

    /*
     * Returns the contents of an Excel row in the form of a String array.
     *
     * @see com.ibm.ccd.common.parsing.Parser#splitLine()
     */
    public String[] splitLine() throws Exception {
        // if (m_iCurrentRow == m_iNbRows)
        // return null;

        XSSFRow row = m_sheet.getRow(m_iCurrentRow);
        if (row == null) {
            return null;
        } else {
            int cellIndex = 0;
            int noOfCells = row.getPhysicalNumberOfCells();
            String[] values = new String[noOfCells];
            short firstCellNum = row.getFirstCellNum();
            short lastCellNum = row.getLastCellNum();

            if (firstCellNum >= 0 && lastCellNum >= 0) {
                for (short iCurrent = firstCellNum; iCurrent < lastCellNum; iCurrent++) {
                    XSSFCell cell = (XSSFCell) row.getCell(iCurrent);
                    if (cell == null) {
                        values[iCurrent] = "";
                        cellIndex++;
                        continue;
                    } else {
                        switch (cell.getCellType()) {
                            case XSSFCell.CELL_TYPE_NUMERIC:
                                double value = cell.getNumericCellValue();
                                if (DateUtil.isCellDateFormatted(cell))

                                {
                                    if (DateUtil.isValidExcelDate(value)) {
                                        Date date = DateUtil.getJavaDate(value);
                                        SimpleDateFormat dateFormat = new SimpleDateFormat(JAVA_TOSTRING);
                                        values[iCurrent] = dateFormat.format(date);
                                    } else {
                                        // throw new
                                        // Exception("Invalid Date value found at row number "
                                        // +
                                        // row.getRowNum()+" and column number "+cell.getCellNum());
                                    }
                                } else {
                                    values[iCurrent] = value + "";
                                }
                                break;

                            case XSSFCell.CELL_TYPE_STRING:
                                values[iCurrent] = cell.getStringCellValue();
                                break;

                            case XSSFCell.CELL_TYPE_BLANK:
                                values[iCurrent] = null;
                                break;

                            default:
                                values[iCurrent] = null;
                        }
                    }
                }
            }
            m_iCurrentRow++;
            return values;
        }

    }

    public static void main(String args[]) {
        XSSFWorkbook workBook = null;
        File file = new File("E:\\Local\\Local2.xlsx");
        InputStream excelDocumentStream = null;
        try {
            excelDocumentStream = new FileInputStream(file);
            // POIFSFileSystem fsPOI = new POIFSFileSystem(new
            // BufferedInputStream(excelDocumentStream));
            BufferedInputStream bfs = new BufferedInputStream(excelDocumentStream);
            workBook = new XSSFWorkbook(bfs);
            seventhma parser = new seventhma(workBook.getSheetAt(0));
            String[] res = null;
            while ((res = parser.splitLine()) != null) {
                for (int i = 0; i < res.length; i++) {
                    System.out.println("[" + res[i] + "]" + "\t");

                }
                System.out.println(res.length);

            }
            bfs = null;
            excelDocumentStream.close();

        } catch (Exception e) {
            System.out.println(e);
            e.printStackTrace();
        }

    }
}

This program gives java heap out of space and when excel sheet containing 16 columns is uploaded it gives ArrayIndexOutOfBoundException.I had increased memory of eclipse upto -Xmx1600m but that also didnt work.

A: You get the ArrayIndexOutOfBoundException on the values array because you use the row.getPhysicalNumberOfCells() to determine its size. But row.getPhysicalNumberOfCells() will only count the cells that are actually filled in the file.
For example if you create an Excel sheet and only fill columns A, C and F and don't touch the other cells at all row.getPhysicalNumberOfCells() will return 3.
But you are iterating over all the cells by getting row.getFirstCellNum() and row.getLastCellNum(). So values[iCurrent] will sure be out of bounds once you reach cell F.
Regarding the OutOfMemory issue:
XSSF uses a LOT of memory. Try pushing your VM to as much memory as is possible for your machine. Or if you are just reading the files then try to go with the eventmodel API instead of the usermodel (think SAX vs. DOM).

(source: apache.org)


text:
Q: Android Gradle build : renaming the apk How can I adapt my build.gradle to change the final basename of the apk(s) ? (without changing the default suffixes)

A: On Gradle 1.8, project.archivesBaseName does work, but it gives this complaint:

Creating properties on demand (a.k.a. dynamic properties) has been
  deprecated and is scheduled to be removed in Gradle 2.0. Please read
  http://gradle.org/docs/current/dsl/org.gradle.api.plugins.ExtraPropertiesExtension.html
  for information on the replacement for dynamic properties. Deprecated
  dynamic property: "archivesBaseName" on "root project
  'myapp'", value: "AnotherName".

To get rid of the warning (and to avoid your build breaking on Gradle 2.0), use this:
project.ext.set("archivesBaseName", "AnotherName");

...as suggested in the ExtraPropertiesExtension documentation.
Update (Gradle plugin 1.1.0)
Android Gradle plugin version 1.1.0 introduced a bug which broke archivesBaseName, as friederbluemle noted. But fortunately this has since been fixed (in version 1.1.2).

A: I found a very simple solution. The apk base name is the property archivesBaseName defined on the project. So the following line is enough to rename the apks:
project.archivesBaseName = "AnotherName";

A: The below codeworked great for me on v1.3.1 and with APKs only:
android {
    defaultConfig {
        archivesBaseName = "AnotherName"

Again, this works with android plugin 1.3.1 (not 1.3.0) but we were still having trouble renaming both our apps (APK) and libs (AAR).  A big problem since we have a 20+ project setup where we are locking down where deployed binaries come from and not duplicate code in every sub project build.gradle.
The following worked for us:
Define the following method (and plugin) in root build.gradle:
ext.snapshotSuffix = "<sha>-<count>-SNAPSHOT"
ext.nextVersion = "patch"
apply plugin: 'com.cinnober.gradle.semver-git'

def renameArtifact(variant) {
    variant.outputs.each { output ->
        def fullName = output.outputFile.name
        def projectName = fullName.substring(0, fullName.indexOf('-'))
        output.outputFile = new File(
                (String) output.outputFile.parent,
                (String) output.outputFile.name.replace(projectName, "drivecx-${projectName}-${project.version}"))
    }
}

For applications use:
apply plugin: 'com.android.application'
android {
    ...
    // Rename all output artifacts to include version information
    applicationVariants.all { variant ->
        renameArtifact(variant)
    }
}

For libraries use:
apply plugin: 'com.android.library'
android {
    ...
    // Rename all output artifacts to include version information
    libraryVariants.all { variant ->
        renameArtifact(variant)
    }
}

Now you get some really nice files with a common prefix, project name, git-describe-wth-sha1-buildflavor, and extension.
OLD example:
androidauto-debug.apk

NEW example:
drivecx-androidauto-0.2.1-d1436b7-193-SNAPSHOT-debug.apk

A bonus is that it doesn't rename the unaligned apks.

A: Starting with version 1.1.0 of the Android Gradle plugin you have to use
archivesBaseName = "yourOtherName"

instead of project.ext.set("archivesBaseName", "yourOtherName") in your build.gradle to make it work.

A: You can also rename the sub-project (without renaming the directory), by putting the following in the root settings.gradle:
rootProject.children.each {
    it.name = ('app' == it.name ? 'MyAppName' : it.name)
}


text:
Q: ¿Cómo contar registros con Count? tengo el siguiente inconveniente estoy realizando una consulta anidada con 3 tablas para devolver el siguiente resultado

este es mi SQL
SELECT
a.id as id_asesor,
a.nombres,
(SELECT COUNT(*) from REL_ASESOR_LOTE WHERE id_asesor) as total_lotes
FROM REL_ASESOR_LOTE as rel
INNER JOIN ASESORES as a ON id_asesor = rel.id_asesor
INNER JOIN LOTES as l ON l.id = rel.id_lote
GROUP BY rel.id_asesor

y este es el resultado que obtengo

ya que solo existe en la tabla REL_ASESOR_LOTE 2 registros

como se ve en el resultado solo me muestra 1 nombre 2 veces, como puedo arreglar este error ?

A: Si entendí bien tu pregunta, lo que buscas es contar la cantidad de lotes por asesor. Esto podrías resolverlo de la siguiente forma:
SELECT a.id as id_asesor,
       a.nombres,
       COUNT(DISTINCT l.id)
       FROM REL_ASESOR_LOTE as rel
       INNER JOIN ASESORES as a
             ON a.id = rel.id_asesor
       INNER JOIN LOTES as l
             ON l.id = rel.id_lote
       GROUP BY a.id_asesor,
                a.nombres

Comentarios:

*

*El mysql es muy poco consistente con el estándar a la hora de manejar los GROUP BY, y eso es una fuente de problemas. Como buena práctica, toda columna en el select que no esté en una función de agregación debería repetirse en el GROUP BY

*Una vez conseguida la agrupación por asesor, simplemente hay que contar los lotes, lo hacemos con un COUNT(DISTINCT l.id) el  DISTINCT puede ser opcional, pero coo no conozco la relaciones, me asegura la suma de lotes distintos.


text:
Q: How to invoke drag event of a custom view inside SurfaceView? How can i drag a custom view inside the SurfaceView. Touch events are not dispatched to child custom view from SurfaceView or child view's onTouchEvent is not called.

A: Try this code
 public class MoveViewTouchListener implements View.OnTouchListener
{
    private GestureDetector mGestureDetector;
    private View mView;

    public MoveViewTouchListener(View view)
    {
        mGestureDetector = new GestureDetector(view.getContext(), mGestureListener);
        mView = view;
    }

    @Override
    public boolean onTouch(View v, MotionEvent event)
    {
        return mGestureDetector.onTouchEvent(event);
    }

    private GestureDetector.OnGestureListener mGestureListener = new GestureDetector.SimpleOnGestureListener()
    {
        private float mMotionDownX, mMotionDownY;

        @Override
        public boolean onDown(MotionEvent e)
        {
            mMotionDownX = e.getRawX() - mView.getTranslationX();
            mMotionDownY = e.getRawY() - mView.getTranslationY();
            return true;
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY)
        {
            mView.setTranslationX(e2.getRawX() - mMotionDownX);
            mView.setTranslationY(e2.getRawY() - mMotionDownY);
            return true;
        }
        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            if (g) {
                if (groupselecteditems.contains(mView)) {
                    mView.setBackgroundColor(Color.TRANSPARENT);
                    groupselecteditems.remove(mView);
                } else {
                    mView.setBackgroundResource(border);
                    groupselecteditems.add((MyTextView) mView);
                }
            } else {
                toucheditem = mView;
                xcountry = mView.getX();
                ycountry = mView.getY();
            }
            return true;
        }
        @Override
        public void onLongPress(MotionEvent e) {
            if (g) {
                if (groupselecteditems.size() > 0) {
                    editGroup();
                }
            } else {
                changtextfeatures((TextView) mView);
            }
        }
    };
}

Call this class with your view
 view.setOnTouchListener(new MoveViewTouchListener(view));


text:
Q: Android 9(only observed) using Room(for non-images): Row too big to fit into CursorWindow requiredPos=0, totalRows=1 I've only observed this on Android 9 and possibly only on Samsung devices. I'm storing multiple JSON responses to multiple serialized strings into my DB later to be typeConverted using Moshi again into a model.
The query that causes this error is:
@Query("SELECT * FROM tasks")
public abstract Flowable<List<TaskEntity>> getAll();

The last instance had a total of about 392,000 characters TOTAL in the table. These are actually split up into about 5500 character size entries within the table.

*

*Why would the cursor have a problem with ~11k byte sized entries? Does the fact that I'm selecting * mean the cursor is grabbing the whole table into memory and not a single row at a time?

*Why only Android 9?

Thanks.

A:
Does the fact that I'm selecting * mean the cursor is grabbing the whole table into memory and not a single row at a time?

SELECT * means you are retrieving all columns. A SELECT without a WHERE clause (or other types of constraints) means that you are retrieving all rows. So, SELECT * FROM tasks will attempt to retrieve the entire table contents into memory.
You could add @Transaction to this function, as that may help get past this error. Quoting the documentation:

When used on a Query method that has a SELECT statement, the generated code for the Query will be run in a transaction. There are 2 main cases where you may want to do that:

*

*If the result of the query is fairly big, it is better to run it inside a transaction to receive a consistent result. Otherwise, if the query result does not fit into a single CursorWindow, the query result may be corrupted due to changes in the database in between cursor window swaps.

*If the result of the query is a POJO with Relation fields, these fields are queried separately. To receive consistent results between these queries, you also want to run them in a single transaction.

Even better would be to not load the entire table's content's into memory (and then convert the entire table's rows into entity objects). Heap space is limited.

Why only Android 9?

No clue. I wouldn't worry about that — if you focus on retrieving less data, that will have benefits for all your users.


text:
Q: Why my xcode 6 break on crash? I have some error in my app,
It report in console:
exc:*** -[__NSArrayI objectAtIndex:]: index 0 beyond bounds for empty array

but it just crashed and terminated, just didn't break on the crash line of code.
Is it a bug or something wrong on my settings ?
I know what is the problem of my code. I just want to know why xcode not break at the line of the code, not just terminated the app running.
Xcode 6.1   Mac OSX 10.10

A: somewhere in your code, you are trying to access objects within an array but the array is empty. Before accessing elements of array, just check if array is empty or not by using [myArray count].


text:
Q: Put forms next to each other Working on a project where I am going to put forms next to each other. But having the problem that they are not next to eachother. I am going to have 20 rows with input forms and the label name of the forms can be long so very unsure how to handle that.
This is how far I am right now: http://www.bootply.com/129498

A: Your columns are floating properly next to each other, but your second column has a div an id of "dato", which is throwing off the positioning a bit. You have a couple options:
Adding:
#dato {
  overflow: hidden;
}

will cause your second column to flow correctly.


text:
Q: Load dataframe from PySpark I am trying to connect to MS SQL DB from PySpark using spark.read.jdbc
import os
from pyspark.sql import *
from pyspark.sql.functions import *
from pyspark import SparkContext;
from pyspark.sql.session import SparkSession
sc = SparkContext.getOrCreate()
spark = SparkSession(sc)

df = spark.read \
     .format('jdbc') \
     .option('url', 'jdbc:sqlserver://local:1433') \
     .option('user', 'sa') \
     .option('password', '12345') \
     .option('dbtable', '(select COL1, COL2 from tbl1 WHERE COL1 = 2)')

then I do df.load() and returns an error :
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\spark\spark\python\pyspark\sql\readwriter.py", line 172, in load
    return self._df(self._jreader.load())
  File "C:\spark\spark\python\lib\py4j-0.10.7-src.zip\py4j\java_gateway.py", line 1256, in __call__
  File "C:\spark\spark\python\pyspark\sql\utils.py", line 63, in deco
    return f(*a, **kw)
  File "C:\spark\spark\python\lib\py4j-0.10.7-src.zip\py4j\protocol.py", line 326, in get_return_value
py4j.protocol.Py4JJavaError: An error occurred while calling o42.load.
: java.sql.SQLException: No suitable driver
        at java.sql.DriverManager.getDriver(Unknown Source)
        at org.apache.spark.sql.execution.datasources.jdbc.JDBCOptions$$anonfun$6.apply(JDBCOptions.scala:105)
        at org.apache.spark.sql.execution.datasources.jdbc.JDBCOptions$$anonfun$6.apply(JDBCOptions.scala:105)
        at scala.Option.getOrElse(Option.scala:121)
        at org.apache.spark.sql.execution.datasources.jdbc.JDBCOptions.<init>(JDBCOptions.scala:104)
        at org.apache.spark.sql.execution.datasources.jdbc.JDBCOptions.<init>(JDBCOptions.scala:35)
        at org.apache.spark.sql.execution.datasources.jdbc.JdbcRelationProvider.createRelation(JdbcRelationProvider.scala:32)

What's wrong?

A: You need to download the JDBC driver and put it into your spark/jars folder.
For SQL SERVER JDBC driver, you can download it from https://learn.microsoft.com/en-us/sql/connect/jdbc/download-microsoft-jdbc-driver-for-sql-server?view=sql-server-ver15


text:
Q: How to check if MVC bundle exists Is there a way to test if a bundle exists before trying to render it?
I want to do something like this:
@{
    var bundleName = GetBundleName();
}

@if (Scripts.BundleExists(bundleName))
{
    @Scripts.Render(bundleName)
}

Obviously, Scripts.BundleExists() isn't real, but it there something build in that does this?  Or do I have to implement this myself?

A: You can get the bundles in the View by:  var bl = System.Web.Optimization.BundleTable.Bundles;  Then you can search the collection for a specific bundle by path as registered in BundleConfig. After that check if the path or any of the included paths exist.

A: I'm not aware of any way (nor was I able to find a way) for you to do this that is built into the framework. If you really have to do this, I would point you to a solution by Herman.
Asp.Net MVC Bundling, best way to detect missing file
Are your bundles dynamic? If not, I would suggest that this may not be something you need. Once you have them setup correctly the first time, they shouldn't fail.


text:
Q: Is there a way to cast a function I think it would greatly simplify function overloading if I could just write the case that takes the most parameters and then simply stuff each case having less parameters with dummy params.  For example..
// Add two integers
Func<int, int, int> addInts = (x, y) => { return x + y; };

// Add one to  an integer
Func<int, int> addOne = (x) => { return x++; };

// In this case Func takes 2 args and has 1 return
public int IntCalc(Func<int,int,int> operation, int param1, int param2)
{
    return operation(param1, param2);
}

// In this case Func takes 1 arg and has 1 return
public int IntCalc(Func<int, int> operation, int param1, int param2)
{
    // This cast would allow me to do the overload
    Func<int, int, int> castedOperation = (Func<int, int, int>)addOne;
    return IntCalc(castedOperation, param1, 0);
}

So is there a way to do this?  Is this a horrible practice?

A: You can only cast if the parameter signatures are compatible. In your case you'd need to define a lamda since converting a function with one parameter to a function with two parameters makes no sense in general.
  Func<int, int, int> castedOperation = (i1,i2)=>addOne(i1);

If it's good practice depends on the contract of how the delegate will be used. If your functions with less parameters can fulfill that contract then this lamda based conversion is perfectly fine.
As a sidenode your addOne function is really ugly. While the increment of x has no effect because the parameter gets copied and thus only the copy is incremented and discared, implementing it as return x+1; would be much nicer than return x++; since you don't actually want to modify x.

A: Apart from the accepted answer you should also change the addOne to operation. So complete function would be
// In this case Func takes 1 arg and has 1 return
public int IntCalc(Func<int, int> operation, int param1, int param2)
{
    // This cast would allow me to do the overload
    Func<int, int, int> castedOperation = (i1,i2)=>operation(i1);
    return IntCalc(castedOperation, param1, 0);
}

A: If your all parameters are the same type you can use params
adder(bool sample, params int[] a)
{
  ....
}

adder(2,3,4);

also you can use Named Parameter in C# 4.0.
Your approach is useful in constructors (you can do this with them).


text:
Q: Equivalence of Forms of Baire Category Theorem I am trying to show the equivalence of two forms of the Baire Category Theorem. These are the two statements:

*

*Let $(X,d)$ be a complete metric space. Let $U_n$ be a dense, open set for each $n \in \Bbb N$. Then $\bigcap_{n=1}^\infty U_n$ is dense (in $X$).

*Let $(X,d)$ be a complete, non-empty metric space. If $X = \bigcup_{n=1}^\infty A_n$, then there exists $N \in \Bbb N$ such that $\text{Int} \bar{A_N} \neq \emptyset$.

I can show that $1.$ implies $2.$, and for the case that $X = \emptyset$ that $2.$ implies $1.$. My issue is showing that, for non-empt $X$, $2.$ implies $1.$. I've been trying various different manipulations of the closure of $\bigcap_{n=1}^\infty U_n$, eg using de Morgan's law, but I can't get anywhere.
Any advice would be most gratefully received! Thanks! :)

UPDATE: I now have a solution - see answer, if you are interested.

A: I now have a solution to this - credit to my lecturer, the excellent Dr Zsak.
Observe that $\bigcap_{n=1}^\infty U_n \neq \emptyset$. Indeed, if $\bigcap_{n=1}^\infty U_n = \emptyset$, then we have
$$X = \emptyset^c = \left( \bigcap_{n=1}^\infty U_n \right)^c = \bigcup_{n=1}^\infty U_n^c,$$
but $\text{Int}(U_n^c) = \emptyset$ for all $n \in \Bbb N$, contradicting our assumption.
Now let $Y = \overline {B(x,r)}$ for some $x \in X$ and $r > 0$. Observe that $Y \cap U_n$ is open and dense in $Y$ (not $X$). By above,
$$Y \cap \bigcap_{n=1}^\infty U_n = \bigcap_{n=1}^\infty (Y \cap U_n) \neq \emptyset.$$
Thus $\bigcap_{n=1}^\infty U_n$ meets every closed ball, and hence every open ball; hence it is dense.


text:
Q: How can I reinstall Windows 7 without an optical drive?
Possible Duplicate:
Install Windows 7 from USB flash drive

My wife has a Neo netbook with a manufacturer installed Windows 7 OS.
Is it possible to reinstall the OS without an optical drive, perhaps with a USB memory and the license code on the Windows sticker?

A: Use the .iso file sold from the Windows website. If you take this route, it may cost a few bucks, but you can use WUDT to create a bootable USB drive, and then you are solid if you ever need to do it again.
Just be careful to modify your boot order in BIOS.


text:
Q: Spinning wheel function does not always exit I have a function that loops a spinning wheel gif to show a running process. When the process finishes the function is called again with a different value (on/off) and the Label changes to a ✓. If I only have a couple threads from threadspawner() kick off then they finish just fine and change the label to a  ✓. if I start alot of threads (like 12) at the same time then the threads finish just fine but the spinning wheel for one or two labels is sometimes not changed to a ✓.
Note that in the example below I couldn't get the loader to stop and change to a ✓. Maybe this is part of where im messing up but in my code it switches just fine.
Should I be representing the load wheel differently or calling the loader('off') differently?
I tried using a global variable for each thread and setting that to True when the thread starts and then off when the thread ends. This only works if I update the variable in the loader loop to get the new value and that means I have to create a different loader function for each thread which is alot of extra code. I tried using a while loop instead of if but it changed nothing.
I want to use the same loader function for the spinning wheel that runs for each thread. If that is not the best way to do it please point me in the right direction.
from tkinter import *
import time
import threading
main = Tk()

def threadspawner():
    global var1
    global var2
    print(var1)
    if var1.get() == 2:

        thread1 = threading.Thread(target=lambda: loader(lbl1, 'on')) #<-- starts the spinning wheel to show that something is happening
        thread1.start()
        time.sleep(1)  #start doing stuff here
        loader(lbl1, 'off') #<-- Turns off the spinning wheel
        thread1.join()
    if var2.get() == 2:
        thread2 = threading.Thread(target=lambda: loader(lbl1, 'on')) #<-- starts the spinning wheel to show that something is happening
        thread2.start()
        time.sleep(2)
        loader(lbl2, 'off')#<-- Turns off the spinning wheel
        thread2.join()

var1 = IntVar()
chk1 = Checkbutton(main, text='process1', onvalue=2, offvalue=0, variable=var1)
chk1.grid(row=1)
lbl1 = Label(main, text='')
lbl1.grid(row=1, column=1)

var2 = IntVar()
chk2 = Checkbutton(main, text='process2', variable=var2)
chk2.grid(row=2)
lbl2 = Label(main, text='')
lbl2.grid(row=2, column=1)

strt = Button(main, text='Start', command=lambda: threading.Thread(target=lambda: threadspawner()).start())
strt.grid(columnspan=2)

def loader(label, switch):
    global lbl1
    global lbl2

    #im using images for my program but you do not have them so I use keyboard entries below to represent

    #img = PhotoImage(file='icons\\wheel.gif', format="gif -index 0")
    #img1 = PhotoImage(file='icons\\wheel.gif', format="gif -index 1")
    #img2 = PhotoImage(file='icons\\wheel.gif', format="gif -index 2")
    if switch == 'off':
        label['text'] = '✓'
        return
    if switch == 'on':
        print('starting loop')
        if switch == 'on':
            label['text'] = '/'
        time.sleep(.1)
        if switch == 'on':
            label['text'] = '-'
        time.sleep(.1)
        if switch == 'on':
            label['text'] = '\\'
        time.sleep(.1)
        if switch == 'on':
            loader(label, 'on')
main.mainloop()

A: The problem with what you were doing is that switch is a local variable, so when the loader function is started, the spinner is started, but when it is stopped, the switch parameter being passed to the endless chain of loader functions is still 'on', so even though the label is set to the '✓', the text is immediately reset to continue the loading animation; When the loader function is called with parameter 'off', the switch variable only has the value 'off' in the local scope of that function call.
A quick and dirty fix is to create a new global variable, which can be used to stop the loader functions calling itself forever. This has many problems, such as only one spinner being allowed at once.
global_switch = 'off'

def loader(label, switch):
    global lbl1, lbl2, global_switch

    if not switch==None:
        global_switch = switch

    if global_switch == 'off':
        ....
    if global_switch == 'on':
        ....
            loader(label, None)
main.mainloop()

However, I would recommend a much neater approach using classes. (There are some untested commented-out suggestions on converting it to using the images instead of text). Also, you can't safely make tkinter calls outside the main thread, so although this wasn't the original problem you asked about, I've used the root's after method in place of threads and time.sleep()s.
Here is the solution I would recommend:
from tkinter import *
import time
import threading
main = Tk()

def threadspawner():
    global var1
    global var2
    print(var1.get(),var2.get())
    if var1.get() != 0:
        lbl1.start() #<-- starts the spinning wheel to show that something is happening
        time.sleep(1)  #start doing stuff here
        lbl1.stop() #<-- Turns off the spinning wheel
    if var2.get() != 0:
        lbl2.start() #<-- starts the spinning wheel to show that something is happening
        time.sleep(2)
        lbl2.stop() #<-- Turns off the spinning wheel

class Loader(Label):
    positions_text = '/-\\'
    #positions_imgs = [PhotoImage(file='icons\\wheel.gif', format="gif -index "+str(i)) for i in range(3)]
    def __init__(self, parent, *args, **kwargs):
        kwargs['text']=''
        Label.__init__(self, parent, *args, **kwargs)
        self.parent = parent
        self.runnng = False
        self.pos = 0
    def start(self):
        self.running = True
        self.parent.after(0,self.update)

    def update(self):
        self.config(text = self.positions_text[self.pos])
        #self.config(image = self.positions_imgs[self.pos])
        self.pos = (self.pos+1)%len(self.positions_text)
        #self.pos = (self.pos+1)%len(self.positions_imgs)
        if self.running:
            self.parent.after(100,self.update)
        else:
            self.config(text = '✓')
    def stop(self):
        self.running = False

var1 = IntVar()
chk1 = Checkbutton(main, text='process1', onvalue=2, offvalue=0, variable=var1)
chk1.grid(row=1)
lbl1 = Loader(main) # create an instance of the Loader class
lbl1.grid(row=1, column=1)

var2 = IntVar()
chk2 = Checkbutton(main, text='process2', variable=var2)
chk2.grid(row=2)
lbl2 = Loader(main) # create an instance of the Loader class
lbl2.grid(row=2, column=1)

strt = Button(main, text='Start', command=lambda: threading.Thread(target=threadspawner).start())
strt.grid(columnspan=2)

main.mainloop()

NB: I have also made some other minor changes in the code.


text:
Q: Passing empty string to EF6 This code runs fine in the SQL Server Management Studio:
SELECT [PassNumber] FROM [dbo].[Customers] WHERE [PassNumber] <> 'A'

This code also works as expected:
string query = "PassNumber <> 'A'";
DbSqlQuery<Customer> data = db.Customers.SqlQuery( string.Format("select * from customers where {0}", query) );

Now it is changed to exclude empty rows and this code works fine on SSMS:
SELECT [PassNumber] FROM [Customers] WHERE [PassNumber] <> ''

But I can't find a way to correctly format the query string. I have tried all possible combinations that I thought of, but the code throws an exception: "Incorrect syntax near the keyword '<>'."
string query = "PassNumber <> '' ";
DbSqlQuery<Customer> data = db.Customers.SqlQuery( string.Format("select * from customers where {0}", query) );

NOTE: For simplicity, the check for null value has been left out of the examples in the question.

A: Why don't you use LINQ when querying in EF. Then everything might be easier:
var customerList = db.Customers.Where(c => c.PassNumber == string.Empty).ToList();

A: Have you tried to use
is null

clause on the SQL?
Oris not null

A: If you insist on doing this by raw SQL you should use:
db.Customers.SqlQuery("select * from customers where PassNumber <> @p0, string.Empty);

Or
db.Customers.SqlQuery("select * from customers where LEN(PassNumber) > 0);


text:
Q: Error while running the exe file made with pyinstaller I tried to make a standalone executable of my python script with auto-py-to-exe , it basically provides easy interface for creating executable with pyinstaller, so I made my python script's exe, it's console based and when I try to run the exe that I made of my script, then console opens up for a second a closes with bunch of errors quickly. However, the script runs fine in idle.
I had attached a screenshot of the error I received. As per my observations most probably the error is occurring due to the import of VLC module as in error trace you will see it occurred from line 2 and that line I had imported VLC. I have also observed by changing the line number of import for VLC.
I am quite a beginner, So I need to know the steps for the solution.

from bs4 import BeautifulSoup
import vlc
import pafy
import urllib.request
import time

textToSearch = 'tremor dimitri vegas '
query = urllib.parse.quote(textToSearch)
urlq = "https://www.youtube.com/results?search_query=" + query
response = urllib.request.urlopen(urlq)
html = response.read()
soup = BeautifulSoup(html, 'html.parser')
track_links=[]
i=0
for vid in soup.findAll(attrs={'class':'yt-uix-tile-link'}):
    i=i+1
    print('https://www.youtube.com' + vid['href'])
    track_links.append('https://www.youtube.com' + vid['href'])
    if i==2:
        break
print()

url = track_links[1]
video = pafy.new(url)
best = video.getbestaudio()
playurl = best.url
ins = vlc.Instance()
player = ins.media_player_new()

code = urllib.request.urlopen(url).getcode()
if str(code).startswith('2') or str(code).startswith('3'):
    print('Stream is working and playing song')
else:
    print('Stream is dead')

Media = ins.media_new(playurl)
Media.get_mrl()
player.set_media(Media)
player.play()

time.sleep(20)
player.stop()#breaking here just for check purpose

now here is the complete error trace
`Traceback (most recent call last):
 File "site-packages\PyInstaller\loader\pyiboot01_bootstrap.py", line   149, in _
 _init__
 File "ctypes\__init__.py", line 348, in __init__
 OSError: [WinError 126] The specified module could not be found

 During handling of the above exception, another exception occurred:

 Traceback (most recent call last):
 File "liveyoutbe.py", line 2, in <module>
 File "<frozen importlib._bootstrap>", line 961, in _find_and_load
 File "<frozen importlib._bootstrap>", line 950, in  _find_and_load_unlocked
 File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
 File "c:\python36\lib\site-packages\PyInstaller\loader\pyimod03_importers.py",
 line 627, in exec_module
 exec(bytecode, module.__dict__)
 File "site-packages\vlc.py", line 207, in <module>
 File "site-packages\vlc.py", line 163, in find_lib
 File "site-packages\PyInstaller\loader\pyiboot01_bootstrap.py", line  151, in _
_init__
 __main__.PyInstallerImportError: Failed to load dynlib/dll 'libvlc.dll'. Most pr
 obably this dynlib/dll was not found when the application was frozen.
 [6032] Failed to execute script liveyoutbe`

A: Python VLC needs external dependencies like the DLL files you see in the error. So you need to add them to your executable output with add-data.
Just copy all those *.dll inside your current VLC install path (e.g C:\Program Files\VideoLAN\VLC) besides to your script and use below command to generate your executable:
pyinstaller.exe -F --add-data "./libvlc.dll;." --add-data "./axvlc.dll;." --add-data "./libvlccore.dll;." --add-data "./npvlc.dll;." script.py

Edit: It seems that you still need one more dependency which is plugins directory. Just add the whole plugins directory in your VLC path to your executable output. For that after executing above command you would get a spec file add a.datas += Tree('<path_to_vlc_plugins_dir>', prefix='plugins') to the file like this:
# -*- mode: python -*-

block_cipher = None

a = Analysis(['script.py'],
             pathex=['<root_project_path>'],
             binaries=[],
             datas=[('./libvlc.dll', '.'), ('./axvlc.dll', '.'), ('./libvlccore.dll', '.'), ('./npvlc.dll', '.')],
             hiddenimports=[],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher,
             noarchive=False)

a.datas += Tree('<path_to_vlc_plugins_dir>', prefix='plugins')
pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          [],
          name='script',
          debug=False,
          bootloader_ignore_signals=False,
          strip=False,
          upx=True,
          runtime_tmpdir=None,
          console=True )

Finally, execute this:
pyinstaller script.spec


text:
Q: Type "only refers to a type, but is being used as a value here" when exporting I have a file called types.ts which has all my types in. I want to export some of these, like so:
export type Example {
  something: string;
}

I have another file called index.ts, which is the entry point for my code. I want to export the Example type. When I try the following:
import { Example } from "./types";

export default {
  Example
}

I get the following error:

'Example' only refers to a type, but is being used as a value
here.ts(2693)

I'm not sure how to export a type from another file correctly. I have also tried the following:
export * from "./types";
export { Example } from "./types";

But this doesn't work as it's not part of the export, due to my export default which contains other stuff, however this might be an entirely different issue if this is the correct way to do it.
What's the correct / best way to achieve this?

A: When you do
export default {
  Example
}

...you're exporting an object literal with an Example property (written with shorthand notation) as the default export of a module. That means it's expecting Example to be a variable whose value will be copied to the Example property of the object being exported. But in your case, Example is a type, not a variable.
If you want to export Example as the default export of a module, you'd do it like this:
export default Example;

If you want to export Example as a named type export, you don't use default:
export { Example };


text:
Q: Random file creater, Batch-file Im trying to make a batch-file that creates random directories and create files in the folders. But I am unable to make it work.
This is what I have tried:
 @echo off
 cd "%userprofile%\desktop\Safe_Space"
 md "%random%"
 md "%random%"
 md "%random%"
 cd "*"
 copy /Y NUL %random%.txt >NUL

A: This will create 10 folders with random names and 1 file within each folder with random names.
This will create a completely empty file in the created directories:
@echo off
setlocal enabledelayedexpansion
for /l %%i in (1,1,10) do (
    set tempf=!random!
    mkdir !tempf!
    copy /y NUL !tempf!\!random! >NUL
)

Increasing/Decreasing the 10 in for /l %%i in (1,1,10) do ( will increased the number of folders and files. To add more files to folders, repeat echo nul > %random.txt or simply create another loop to create multiple files in the folders.
fsutil is a another option, but requires admin privileges, it will create a nul variable in the file.
@echo off
setlocal enabledelayedexpansion
for /l %%i in (1,1,10) do (
    set tempf=!random!
    mkdir !tempf!
    fsutil file createnew !tempf!\!random! 1
)

This creates a new file, with some text, in this case the word nul will be written to file, but you can change that:
@echo off
setlocal enabledelayedexpansion
for /l %%i in (1,1,10) do (
    set tempf=!random!
    mkdir !tempf!
    echo nul > !tempf!\!random!
)

A: You can create directories and files by using FOR, RANDOM and basic instructions.
RANDOM create a random number between 0 and 32767. You can control the range of RANDOM using bottomlimit and upperlimit, e.g. 1-1000:
SET /a bottomlimit = 1
SET /a upperlimit = 1000

Don't forget to use SETLOCAL ENABLEDELAYEDEXPANSION (check How do SETLOCAL and ENABLEDELAYEDEXPANSION work?) and inside the loop the !VARIABLE! notation instead of %VARIABLE%. The following example creates 5 directories and 10 empty files. You can change these values as you like, using
FOR /l %%i in (1,1,10) instead of FOR /l %%i in (1,1,2) creates 2 directories.
FOR /l %%i in (1,1,10) means a loop starts at 1, steps by 1, and finishes at 10.
@echo off
SETLOCAL ENABLEDELAYEDEXPANSION

REM creating 5 directories...
FOR /l %%i in (1,1,5) DO (
    SET dirName=!RANDOM!
    REM create a directory with random name
    MKDIR !dirName!
    CD !dirName!

    REM creating 10 files...
    FOR /l %%i in (1,1,10) DO (
        REM create an empty file with random name
        COPY NUL !RANDOM!>NUL
    )

    CD ..
)

The instruction COPY NUL !RANDOM!>NUL doesn't require administation privileges
the >NUL eliminates unwanted output to console


text:
Q: Difference between [src] and src in Angular2 In Angular1,

This will hide the broken image icon if the imageUrl is empty.
But in Angular2, both

and the equivalent of ngSrc

still show the small broken image icon as the image placeholder if imageUrl is empty.
What's the actual difference there?

A: You can conditionally add your img by using *ngIf

A: [src]="imageUrl" is property binding that assigns the value of imageUrl to the src property. This works with all kind of values.
src="{{imageUrl}}" also does property binding but {{}} does string interpolation, this means that imageUrl is stringified before it's assigned to the src property. Don't use this style if you want to pass objects or arrays, or boolean.
When DomSanitizer is used [src]="..." is mandatory because the value no longer is a string, but an object and using {{}} would stringify it in an invalid way.

A: The difference is only semantics for your use case.
Using the interpolation option  tells angular to put the value of imageUrl into that place holder.  In your case, insert it into the value of src property.
Using the template expression option  tells angular to explicitly set the value of the src property to the value of imageUrl.