问:
Android Studio : Error:Cause: unable to find valid certification path to requested target
Where to get more information about this error in Android Studio

```<code>Error:Cause: unable to find valid certification path to requested target
</code>```

I dont know from where it is coming and what to look for?

Below is the snippet from my Build.gradle.

```<code>buildscript {
    repositories {
        jcenter() {
            url "http://jcenter.bintray.com/"

        }
      //  mavenCentral()
        maven { url 'https://maven.fabric.io/public' }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.2'
        classpath 'io.fabric.tools:gradle:1.+'
    }
}

allprojects {
    repositories {
        jcenter() {
            url "http://jcenter.bintray.com/"
        }
      //  mavenCentral()
        maven { url 'https://maven.fabric.io/public' }
    }
}

apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

repositories {
    jcenter() {
        url "http://jcenter.bintray.com/"

    }
    maven { url 'https://maven.fabric.io/public' }  }
</code>```

答: The only way I got this running is going to letsencrypt generate my certificate and then set it up in the server from where the repo is consume, but for I see there just add Https in all of them as is a known repo/s, if you're behind a proxy use a vpn to connect to internet so you are directly passing through the proxy and will work</p>

Body:
Where to get more information about this error in Android Studio

Error:Cause: unable to find valid certification path to requested target

I dont know from where it is coming and what to look for?

Below is the snippet from my Build.gradle.

buildscript {
    repositories {
        jcenter() {
            url "http://jcenter.bintray.com/"

        }
      //  mavenCentral()
        maven { url 'https://maven.fabric.io/public' }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.2'
        classpath 'io.fabric.tools:gradle:1.+'
    }
}

allprojects {
    repositories {
        jcenter() {
            url "http://jcenter.bintray.com/"
        }
      //  mavenCentral()
        maven { url 'https://maven.fabric.io/public' }
    }
}

apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

repositories {
    jcenter() {
        url "http://jcenter.bintray.com/"

    }
    maven { url 'https://maven.fabric.io/public' }  }


来源: stackexchange

问:
Reactjs Module not found | Css import
I will try to be concise, I must work on a Reactjs project for school project, my task is to take a existing html/css theme and and put it in React components.

But I have a problem since the start, I used CreateReactApp for a clean start and import index.css of the theme.
Create a basic form base on the theme and have this error. (She disapear when I delete index.css)

Error I see
Failed to compile

./src/css/index.css

Module not found: Can't resolve '../images/category-1-bg.jpg' in
  'C:\Users\50031\Documents\React-Project-master\src\css'

Structure of the project is that
Structure project

Thanks so much, I already check for an answer but I suck as hell in code and understand nothing.... Sorry

答: Install css-loader so that it will include the image during build time.</p>

ContentLicense: CC BY-SA 3.0

Title: Reactjs Module not found | Css import


问:
Are parentheses around the result significant in a return statement?
Is there a difference between these two statements inside a function?

```<code>bool returnValue = true;
// Code that does something
return(returnValue);
</code>```

and this?

```<code>bool returnValue = true;
// Code
return returnValue;
</code>```

The former has parentheses around returnValue.

答:
They are identical. I see the parenthesis syntax quite often, and I always ask those who use it: why? And none can answer why they use it.

To bluntly sum it up, parenthesis around returning expressions are used by people who don't quite grasp the difference between function-like macros and functions, or who are confused about the operator precedence or order of evaluation rules in C. There is no coding style benefit from using parenthesis.

Thus

```<code>return value;
</code>```

is more correct than

```<code>return (value)
</code>```

because the latter suggests you don't quite know what you are doing :)

ContentLicense: CC BY-SA 4.0

Body:
Is there a difference between these two statements inside a function?

bool returnValue = true;
// Code that does something
return(returnValue);

and this?

bool returnValue = true;
// Code
return returnValue;

The former has parentheses around returnValue.

Body:
They are identical. I see the parenthesis syntax quite often, and I always ask those who use it: why? And none can answer why they use it.

To bluntly sum it up, parenthesis around returning expressions are used by people who don't quite grasp the difference between function-like macros and functions, or who are confused about the operator precedence or order of evaluation rules in C. There is no coding style benefit from using parenthesis.

Thus

return value;

is more correct than

return (value)

because the latter suggests you don't quite know what you are doing :)


问:
Ionic2 serve not working
When i write ionic serve nothing opens. I have tried changing nodejs versions. Reinstalling ionic cordova. Also cleared cache and other ways on internet. Nothing works. Please help. No errors are shown but a window is not opened.

Info:

```<code>C:\Projects\cutePuppyPics>ionic info

cli packages: (C:\Users\Tullo\AppData\Roaming\npm\node_modules)

    @ionic/cli-utils  : 1.19.0
    ionic (Ionic CLI) : 3.19.0

global packages:

    cordova (Cordova CLI) : 7.1.0

local packages:

    @ionic/app-scripts : 3.1.4
    Cordova Platforms  : none
    Ionic Framework    : ionic-angular 3.9.2

System:

    Node : v8.9.1
    npm  : 5.5.1
    OS   : Windows 10

Environment Variables:

    ANDROID_HOME : not set

Misc:

    backend : pro
</code>```

Serve:

```<code>C:\Projects\cutePuppyPics>ionic serve
Starting app-scripts server: --address 0.0.0.0 --port 8100 --livereload-port 35729 --dev-logger-port 53703 --nobrowser -
Ctrl+C to cancel
[20:52:58]  watch started ...
[20:52:58]  build dev started ...
[20:52:58]  clean started ...
[20:52:58]  clean finished in 12 ms
[20:52:58]  copy started ...
[20:52:58]  deeplinks started ...
[20:52:58]  deeplinks finished in 40 ms
[20:52:58]  transpile started ...
[20:53:03]  transpile finished in 5.17 s
[20:53:03]  preprocess started ...
[20:53:04]  preprocess finished in 4 ms
[20:53:04]  webpack started ...
[20:53:04]  copy finished in 5.44 s
[20:53:13]  webpack finished in 9.14 s
[20:53:13]  sass started ...
[20:53:14]  sass finished in 1.68 s
[20:53:14]  postprocess started ...
[20:53:14]  postprocess finished in 16 ms
[20:53:14]  lint started ...
[20:53:14]  build dev finished in 16.32 s
[20:53:14]  watch ready in 16.47 s`enter code here`
[20:53:14]  dev server running: http://localhost:8100/

[OK] Development server running!
     Local: http://localhost:8100
     External: http://192.168.10.8:8100
     DevApp: cutePuppyPics@8100 on LAPTOP-NNU75MUT
</code>```

答:
force an ip adresse

ionic serve --address YOUR_IP_ADDRESS

your ip adresse should be available , i think you can use 192.168.10.8 or 127.0.0.1

Title: Ionic2 serve not working

Body:
When i write ionic serve nothing opens. I have tried changing nodejs versions. Reinstalling ionic cordova. Also cleared cache and other ways on internet. Nothing works. Please help. No errors are shown but a window is not opened.

Info:

C:\Projects\cutePuppyPics>ionic info

cli packages: (C:\Users\Tullo\AppData\Roaming\npm\node_modules)

    @ionic/cli-utils  : 1.19.0
    ionic (Ionic CLI) : 3.19.0

global packages:

    cordova (Cordova CLI) : 7.1.0

local packages:

    @ionic/app-scripts : 3.1.4
    Cordova Platforms  : none
    Ionic Framework    : ionic-angular 3.9.2

System:

    Node : v8.9.1
    npm  : 5.5.1
    OS   : Windows 10

Environment Variables:

    ANDROID_HOME : not set

Misc:

    backend : pro

Serve:

C:\Projects\cutePuppyPics>ionic serve
Starting app-scripts server: --address 0.0.0.0 --port 8100 --livereload-port 35729 --dev-logger-port 53703 --nobrowser -
Ctrl+C to cancel
[20:52:58]  watch started ...
[20:52:58]  build dev started ...
[20:52:58]  clean started ...
[20:52:58]  clean finished in 12 ms
[20:52:58]  copy started ...
[20:52:58]  deeplinks started ...
[20:52:58]  deeplinks finished in 40 ms
[20:52:58]  transpile started ...
[20:53:03]  transpile finished in 5.17 s
[20:53:03]  preprocess started ...
[20:53:04]  preprocess finished in 4 ms
[20:53:04]  webpack started ...
[20:53:04]  copy finished in 5.44 s
[20:53:13]  webpack finished in 9.14 s
[20:53:13]  sass started ...
[20:53:14]  sass finished in 1.68 s
[20:53:14]  postprocess started ...
[20:53:14]  postprocess finished in 16 ms
[20:53:14]  lint started ...
[20:53:14]  build dev finished in 16.32 s
[20:53:14]  watch ready in 16.47 s`enter code here`
[20:53:14]  dev server running: http://localhost:8100/

[OK] Development server running!
     Local: http://localhost:8100
     External: http://192.168.10.8:8100
     DevApp: cutePuppyPics@8100 on LAPTOP-NNU75MUT


问:
Firebase persistence in swift 3
As per firebase official documentation for swift we should use following line to enable persistence in iOS.

```<code>Firebase.defaultConfig().persistenceEnabled = true
</code>```

But if we use the above line in swift 3.0 it gives error.

Any idea how to enable persistence in swift 3.0?

答:
In AppDelegate.swift </p>

```<code>Database.database().isPersistenceEnabled = true
</code>```

Title: Firebase persistence in swift 3

Body:
As per firebase official documentation for swift we should use following line to enable persistence in iOS.

Firebase.defaultConfig().persistenceEnabled = true

But if we use the above line in swift 3.0 it gives error.

Any idea how to enable persistence in swift 3.0?

Body:
In AppDelegate.swift

Database.database().isPersistenceEnabled = true


问:
Why does locationManager popup immediately disappear when used in another class?
I am using the MapKit to use CLLocationManagerDelegate to get the user's location. If I were to request for the user's location in ViewController's viewDidLoad() function, then the popup appears, asking the user for the user's input. Note: the two properties required to ask for the location (Location When In Use, and Location Always And When In Use) is added to Info.plist

That is,

```<code>import UIKit
import MapKit
class ViewController: UIViewController, CLLocationManagerDelegate {
      var locationManager: CLLocationManager?

      override func viewDidLoad() {
           super.viewDidLoad()
           locationManager = CLLocationManager()
           self.locationManager?.desiredAccuracy = kCLLocationAccuracyBest
           self.locationManager?.requestWhenInUseAuthorization()
           self.locationManager?.delegate = self
           self.locationManager?.startUpdatingLocation()
      }
}
</code>```

The code above works fine; when the program begins, it show a popup asking the user for their location.

However, If I was to create a new class MapController and put the same code inside that class, and create a new instance of MapController inside viewDidLoad(), then the popup immediately disappears when the program is run.

That is,

```<code>import UIKit
class ViewController: UIViewController {

     override func viewDidLoad() {
           super.viewDidLoad()
           let mapController = MapController(viewController: self)
           mapController.initialise()
     }
}

import MapKit
class MapController: NSObject, CLLocationManagerDelegate {
      private let viewController: UIViewController
      private var locationManager: CLLocationManager

      required init(viewController: UIViewController) {
          self.viewController = viewController
          locationManager = CLLocationManager()
      }

      func initialise() {
           self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
           self.locationManager.requestWhenInUseAuthorization()
           self.locationManager.delegate = self
           self.locationManager.startUpdatingLocation()
      }
}
</code>```

When the code above is run, the popup asking for the user's location immediately disappears.

My question being: why does the popup stay when the locationManager code is in the viewDidLoad(), but when the code is separated into another class, and called into viewDidLoad(), it immediately disappears. Why does this happen?

How can I separate the locationManager code into another class without the popup immediately disappearing?

答:
It's a memory management issue. In ViewController, you create a local variable named mapController in viewDidLoad. At the end of viewDidLoad, that MapController instance goes out of scope and gets deallocated.

Instead of using a local variable in viewDidLoad, create a property.

```<code>class ViewController: UIViewController {
     var mapController: MapController!

     override func viewDidLoad() {
           super.viewDidLoad()

           mapController = MapController(viewController: self)
           mapController.initialise()
     }
}
</code>```

But this now creates a reference cycle since MapController is keeping a strong reference to the view controller.

So you also need to change the viewController property of MapController to be weak.

Body:
I am using the MapKit to use CLLocationManagerDelegate to get the user's location. If I were to request for the user's location in ViewController's viewDidLoad() function, then the popup appears, asking the user for the user's input. Note: the two properties required to ask for the location (Location When In Use, and Location Always And When In Use) is added to Info.plist

That is,

import UIKit
import MapKit
class ViewController: UIViewController, CLLocationManagerDelegate {
      var locationManager: CLLocationManager?

      override func viewDidLoad() {
           super.viewDidLoad()
           locationManager = CLLocationManager()
           self.locationManager?.desiredAccuracy = kCLLocationAccuracyBest
           self.locationManager?.requestWhenInUseAuthorization()
           self.locationManager?.delegate = self
           self.locationManager?.startUpdatingLocation()
      }
}

The code above works fine; when the program begins, it show a popup asking the user for their location.

However, If I was to create a new class MapController and put the same code inside that class, and create a new instance of MapController inside viewDidLoad(), then the popup immediately disappears when the program is run.

That is,

import UIKit
class ViewController: UIViewController {

     override func viewDidLoad() {
           super.viewDidLoad()
           let mapController = MapController(viewController: self)
           mapController.initialise()
     }
}

import MapKit
class MapController: NSObject, CLLocationManagerDelegate {
      private let viewController: UIViewController
      private var locationManager: CLLocationManager

      required init(viewController: UIViewController) {
          self.viewController = viewController
          locationManager = CLLocationManager()
      }

      func initialise() {
           self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
           self.locationManager.requestWhenInUseAuthorization()
           self.locationManager.delegate = self
           self.locationManager.startUpdatingLocation()
      }
}

When the code above is run, the popup asking for the user's location immediately disappears.

My question being: why does the popup stay when the locationManager code is in the viewDidLoad(), but when the code is separated into another class, and called into viewDidLoad(), it immediately disappears. Why does this happen?

How can I separate the locationManager code into another class without the popup immediately disappearing?

Body:
It's a memory management issue. In ViewController, you create a local variable named mapController in viewDidLoad. At the end of viewDidLoad, that MapController instance goes out of scope and gets deallocated.

Instead of using a local variable in viewDidLoad, create a property.

class ViewController: UIViewController {
     var mapController: MapController!

     override func viewDidLoad() {
           super.viewDidLoad()

           mapController = MapController(viewController: self)
           mapController.initialise()
     }
}

But this now creates a reference cycle since MapController is keeping a strong reference to the view controller.

So you also need to change the viewController property of MapController to be weak.


问:
How to create table and its structure using jquery for HTML
I have values coming from database in a variable by parsing it from JSON. Now I want to create a HTML table structure like below

```<code><table class="table dataList fiberEngg">
    <tbody>
        <tr>
            <td>
                <div class="row noPadding">
                    <div class="col-xs-6 colPadding">
                        MHBHNDMUNVMBSPN006_BU
                        <a class="button"><i class="fa fa-map-marker" aria-hidden="true"></i></a><a class="button"><i class="fa fa-list" aria-hidden="true"></i></a>
                    </div>
                    <div class="col-xs-6 colPadding">
                        <p><strong>Request Id :</strong>053214</p>
                        <p><strong>Last Updated by :</strong>Sameer Parab</p>
                        <p><strong>Status :</strong>Partial HOTO with Partial LIT</p>
                        <p><strong>Pending Since :</strong>1 Day</p>
                    </div>
                </div>
            </td>
        </tr>
    </tbody>
</table>
</code>```

and my JSON is below

```<code>[
    {
        "SPAN_ID": "GJVAPIMHKAKHSPN003_BU",
        "MAINTENANCEZONECODE": "INMUMIBH01",
        "REQ_ID": 4.0,
        "LAST_UPDATE_BY": "HARDIK1.SHAH",
        "STATUS_NAME": "HOTO without LIT",
        "PENDING_DAYS": 7.0
    }
]
</code>```

how can I create a table structure in below code

```<code> success: function (response) {

    var datalist = JSON.parse(response);
    var table = $("#tblFiberEngData");
    table.empty();

    datalist.forEach(function (dataRow) {
        //here i want to create structure
    });
}
</code>```

答:
Do something like this inside your success area.

Start from my_table and below.

```<code>var data = [
    {
        "SPAN_ID": "GJVAPIMHKAKHSPN003_BU",
        "MAINTENANCEZONECODE": "INMUMIBH01",
        "REQ_ID": 4.0,
        "LAST_UPDATE_BY": "HARDIK1.SHAH",
        "STATUS_NAME": "HOTO without LIT",
        "PENDING_DAYS": 7.0
    },
     {
        "SPAN_ID": "WDASDF@R#&^@I",
        "MAINTENANCEZONECODE": "WKUYTEISA",
        "REQ_ID": 4.0,
        "LAST_UPDATE_BY": "TEST",
        "STATUS_NAME": "OK",
        "PENDING_DAYS": 7.0
    }
];

var datatojson = JSON.stringify(data);
var parsedata = jQuery.parseJSON(datatojson);

// start from this inside success: function (response) { bla.. bla..
var my_table = $(".my_table");
my_table.empty();

$.each(parsedata,function( key, val ){
    var my_tr = "<tr>"
        + "<td>"
        + "<div class='row noPadding'>"
        + "<div class='col-xs-6 colPadding'>"
        + val.SPAN_ID
        + "<a class='button'><i class='fa fa-map-marker' aria-hidden='true'></i></a><a class='button'><i class='fa fa-list' aria-hidden='true'></i></a>"
        + "</div>"
        + "<div class='col-xs-6 colPadding'>"
        + "<p><strong>Request Id :</strong>" + val.REQ_ID + "</p>"
        + "<p><strong>Last Updated by :</strong>" + val.LAST_UPDATE_BY + "</p>"
        + "<p><strong>Status :</strong>" + val.STATUS_NAME + "</p>"
        + "<p><strong>Pending Since :</strong>" + val.PENDING_DAYS + "</p>"
        + "</div>"
        + "</div>"
        + "</td>"
        + "</tr>";

    my_table.append(my_tr);
});
</code>```

And jsfiddle based on your code : https://jsfiddle.net/synz/kez21quf/

Body:
I have values coming from database in a variable by parsing it from JSON. Now I want to create a HTML table structure like below

                        MHBHNDMUNVMBSPN006_BU

Request Id :053214

Last Updated by :Sameer Parab

Status :Partial HOTO with Partial LIT

Pending Since :1 Day

and my JSON is below

[
    {
        "SPAN_ID": "GJVAPIMHKAKHSPN003_BU",
        "MAINTENANCEZONECODE": "INMUMIBH01",
        "REQ_ID": 4.0,
        "LAST_UPDATE_BY": "HARDIK1.SHAH",
        "STATUS_NAME": "HOTO without LIT",
        "PENDING_DAYS": 7.0
    }
]

how can I create a table structure in below code

 success: function (response) {

    var datalist = JSON.parse(response);
    var table = $("#tblFiberEngData");
    table.empty();

    datalist.forEach(function (dataRow) {
        //here i want to create structure
    });
}

Body:
Do something like this inside your success area.

Start from my_table and below.

var data = [
    {
        "SPAN_ID": "GJVAPIMHKAKHSPN003_BU",
        "MAINTENANCEZONECODE": "INMUMIBH01",
        "REQ_ID": 4.0,
        "LAST_UPDATE_BY": "HARDIK1.SHAH",
        "STATUS_NAME": "HOTO without LIT",
        "PENDING_DAYS": 7.0
    },
     {
        "SPAN_ID": "WDASDF@R#&^@I",
        "MAINTENANCEZONECODE": "WKUYTEISA",
        "REQ_ID": 4.0,
        "LAST_UPDATE_BY": "TEST",
        "STATUS_NAME": "OK",
        "PENDING_DAYS": 7.0
    }
];

var datatojson = JSON.stringify(data);
var parsedata = jQuery.parseJSON(datatojson);

// start from this inside success: function (response) { bla.. bla..
var my_table = $(".my_table");
my_table.empty();

$.each(parsedata,function( key, val ){
    var my_tr = "<tr>"
        + "<td>"
        + "<div class='row noPadding'>"
        + "<div class='col-xs-6 colPadding'>"
        + val.SPAN_ID
        + "<a class='button'><i class='fa fa-map-marker' aria-hidden='true'></i></a><a class='button'><i class='fa fa-list' aria-hidden='true'></i></a>"
        + "</div>"
        + "<div class='col-xs-6 colPadding'>"
        + "<p><strong>Request Id :</strong>" + val.REQ_ID + "</p>"
        + "<p><strong>Last Updated by :</strong>" + val.LAST_UPDATE_BY + "</p>"
        + "<p><strong>Status :</strong>" + val.STATUS_NAME + "</p>"
        + "<p><strong>Pending Since :</strong>" + val.PENDING_DAYS + "</p>"
        + "</div>"
        + "</div>"
        + "</td>"
        + "</tr>";

    my_table.append(my_tr);
});

And jsfiddle based on your code : https://jsfiddle.net/synz/kez21quf/


问:
SQL Select Like Keywords in Any Order
I am building a Search function for a shopping cart site, which queries a SQL Server database.  When the user enters "Hula Hoops" in the search box, I want results for all records containing both "Hula" and "Hoop", in any order.  Furthermore, I need to search multiple columns (i.e. ProductName, Description, ShortName, MaufacturerName, etc.)

All of these product names should be returned, when searching for "Hula hoop":

Hula hoop

Hoop Hula

The Hoopity of xxhula sticks

(Bonus points if these can be ordered by relevance!)

答:
SQL Server Full Text Search should help you out. You will basically create indexes on the columns you want to search. in the where clause of your query you will use the CONTAINS operator and pass it your search input.

you can start HERE or HERE to learn more

ContentLicense: CC BY-SA 2.5

Title: SQL Select Like Keywords in Any Order


问:
What is the best way to group data pairs in javascript?
Instead of using associative arrays (objects), what is the best way to associate two values so they are always associated and can both be accessed as separate values? Associative arrays are annoying because their order isn't guaranteed and you can't access them using indexes.

I could create two separate arrays but if I randomize their order for display their association would not match, and if they are separate in code there is a good chance I can make a mistake when recording their values, putting them in the wrong order so they don't perfectly match up.

答:
I do not now which kind of data you should store but maybe you could try to store data in a single variable in this way:</p>

```<code>var data = [];

data[0] = "Test" + "|" + Value;
</code>```

Body:
I do not now which kind of data you should store but maybe you could try to store data in a single variable in this way:

var data = [];

data[0] = "Test" + "|" + Value;


问:
How to create a smooth animated text marquee?
I know that there are lot of different threads about horizontal text animation/text scrolling, but unfortunately none of them give smooth scrolling with repeatable text. I have tried double/thickness animation using various WPF controls containing text. Also tried animating with visual brush which gives me by far the most elegant scrolling compared to other approaches (for e.g. playing with Canvas.Left property etc.) but that too goes blur the text, if the text length or the animation speed is too high.

I'm over to a pure DirectX C# implementation using SharpDX library. Should also mention that I'm a beginner with DirectX programming.  Here is the code:

```<code>public void RunMethod()
{
    // Make window active and hide mouse cursor.
    window.PointerCursor = null;
    window.Activate();

    var str = "This is an example of a moving TextLayout object with no snapped pixel boundaries.";

    // Infinite loop to prevent the application from exiting.
    while (true)
    {
        // Dispatch all pending events in the queue.
        window.Dispatcher.ProcessEvents(CoreProcessEventsOption.ProcessAllIfPresent);

        // Quit if the users presses Escape key.
        if (window.GetAsyncKeyState(VirtualKey.Escape) == CoreVirtualKeyStates.Down)
        {
            return;
        }

        // Set the Direct2D drawing target.
        d2dContext.Target = d2dTarget;

        // Clear the target.
        d2dContext.BeginDraw();
        d2dContext.Clear(Color.CornflowerBlue);

        //float layoutXOffset = 0;
        float layoutXOffset = layoutX;

        // Create the DirectWrite factory objet.
        SharpDX.DirectWrite.Factory fontFactory = new SharpDX.DirectWrite.Factory();

        // Create a TextFormat object that will use the Segoe UI font with a size of 24 DIPs.
        textFormat = new TextFormat(fontFactory, "Verdana", 100.0f);

        textLayout2 = new TextLayout(fontFactory, str, textFormat, 2000.0f, 100.0f);

        // Draw moving text without pixel snapping, thus giving a smoother movement.
        // d2dContext.FillRectangle(new RectangleF(layoutXOffset, 1000, 1000, 100), backgroundBrush);
        d2dContext.DrawTextLayout(new Vector2(layoutXOffset, 0), textLayout2, textBrush, DrawTextOptions.NoSnap);

        d2dContext.EndDraw();

        //var character = str.Substring(0, 1);
        //str = str.Remove(0, 1);
        //str += character;
        layoutX -= 3.0f;

        if (layoutX <= -1000)
        {
            layoutX = 0;
        }

        // Present the current buffer to the screen.
        swapChain.Present(1, PresentFlags.None);
    }
}
</code>```

Basically it creates an endless loop and subtracts the horizontal offset. Here are the challenges:  I need repeatable text similar to HTML marquee without any gaps, Would probably need to extend it to multiple monitors.

Please suggest.

答:
I don't know neither how to use DirectX nor sharpdx, but if you want you can consider this solution

I had a similar problem a while ago, but with the text inside a combobox. After a bounty i got what i was looking for. I'm posting the relevant piece of code as an example, but you can check the complete answer here

Basically, whenever you have a textblock/textbox that contain a string that cannot be displayed completely, cause the length exceed the textblock/box lenght you can use this kind of approach. You can define a custom usercontrol derived from the base you need (e.g. SlidingComboBox : Combobox) and define an animation for you storyboard like the following

```<code>_animation = new DoubleAnimation()
 {
      From = 0,
      RepeatBehavior = SlideForever ? RepeatBehavior.Forever : new RepeatBehavior(1), //repeat only if slide-forever is true
      AutoReverse = SlideForever
 };
</code>```

In my example i wanted this behaviour to be active only when the mouse was on the combobox, so in my custom OnMouse enter i had this piece of code

```<code>if (_parent.ActualWidth < textBlock.ActualWidth)
{
     _animation.Duration = TimeSpan.FromMilliseconds(((int)textBlock.Text?.Length * 100));
     _animation.To = _parent.ActualWidth - textBlock.ActualWidth;
     _storyBoard.Begin(textBlock);
}
</code>```

Where _parent represent the container of the selected item. After a check on the text lenght vs combobox lenght i start the animation and end it at the end of the text to be displayed

Note that in the question i mentioned there are also other soltions. I'm posting the one that worked for me

Body:
I know that there are lot of different threads about horizontal text animation/text scrolling, but unfortunately none of them give smooth scrolling with repeatable text. I have tried double/thickness animation using various WPF controls containing text. Also tried animating with visual brush which gives me by far the most elegant scrolling compared to other approaches (for e.g. playing with Canvas.Left property etc.) but that too goes blur the text, if the text length or the animation speed is too high.

I'm over to a pure DirectX C# implementation using SharpDX library. Should also mention that I'm a beginner with DirectX programming.  Here is the code:

public void RunMethod()
{
    // Make window active and hide mouse cursor.
    window.PointerCursor = null;
    window.Activate();

    var str = "This is an example of a moving TextLayout object with no snapped pixel boundaries.";

    // Infinite loop to prevent the application from exiting.
    while (true)
    {
        // Dispatch all pending events in the queue.
        window.Dispatcher.ProcessEvents(CoreProcessEventsOption.ProcessAllIfPresent);

        // Quit if the users presses Escape key.
        if (window.GetAsyncKeyState(VirtualKey.Escape) == CoreVirtualKeyStates.Down)
        {
            return;
        }

        // Set the Direct2D drawing target.
        d2dContext.Target = d2dTarget;

        // Clear the target.
        d2dContext.BeginDraw();
        d2dContext.Clear(Color.CornflowerBlue);

        //float layoutXOffset = 0;
        float layoutXOffset = layoutX;

        // Create the DirectWrite factory objet.
        SharpDX.DirectWrite.Factory fontFactory = new SharpDX.DirectWrite.Factory();

        // Create a TextFormat object that will use the Segoe UI font with a size of 24 DIPs.
        textFormat = new TextFormat(fontFactory, "Verdana", 100.0f);

        textLayout2 = new TextLayout(fontFactory, str, textFormat, 2000.0f, 100.0f);

        // Draw moving text without pixel snapping, thus giving a smoother movement.
        // d2dContext.FillRectangle(new RectangleF(layoutXOffset, 1000, 1000, 100), backgroundBrush);
        d2dContext.DrawTextLayout(new Vector2(layoutXOffset, 0), textLayout2, textBrush, DrawTextOptions.NoSnap);

        d2dContext.EndDraw();

        //var character = str.Substring(0, 1);
        //str = str.Remove(0, 1);
        //str += character;
        layoutX -= 3.0f;

        if (layoutX <= -1000)
        {
            layoutX = 0;
        }

        // Present the current buffer to the screen.
        swapChain.Present(1, PresentFlags.None);
    }
}

Basically it creates an endless loop and subtracts the horizontal offset. Here are the challenges:  I need repeatable text similar to HTML marquee without any gaps, Would probably need to extend it to multiple monitors.

Please suggest.

Body:
I don't know neither how to use DirectX nor sharpdx, but if you want you can consider this solution

I had a similar problem a while ago, but with the text inside a combobox. After a bounty i got what i was looking for. I'm posting the relevant piece of code as an example, but you can check the complete answer here

Basically, whenever you have a textblock/textbox that contain a string that cannot be displayed completely, cause the length exceed the textblock/box lenght you can use this kind of approach. You can define a custom usercontrol derived from the base you need (e.g. SlidingComboBox : Combobox) and define an animation for you storyboard like the following

_animation = new DoubleAnimation()
 {
      From = 0,
      RepeatBehavior = SlideForever ? RepeatBehavior.Forever : new RepeatBehavior(1), //repeat only if slide-forever is true
      AutoReverse = SlideForever
 };

In my example i wanted this behaviour to be active only when the mouse was on the combobox, so in my custom OnMouse enter i had this piece of code

if (_parent.ActualWidth < textBlock.ActualWidth)
{
     _animation.Duration = TimeSpan.FromMilliseconds(((int)textBlock.Text?.Length * 100));
     _animation.To = _parent.ActualWidth - textBlock.ActualWidth;
     _storyBoard.Begin(textBlock);
}

Where _parent represent the container of the selected item. After a check on the text lenght vs combobox lenght i start the animation and end it at the end of the text to be displayed

Note that in the question i mentioned there are also other soltions. I'm posting the one that worked for me


问:
Toget specific value of user data from firebase
In my application i have registration screen. It asks for username,email and password. I am pushing email and username to firebase realtime database. Suppose now the user log out from my application, uninstall the application and install it again and try to login . In login screen i am only asking for email and password, how can i retrieve the username of user. As user may uninstall the app after registration so Shared Prefrence won't work. I tried the following code but it does not give proper output.

```<code> mFirebaseDatabase = FirebaseDatabase.getInstance();
 mMessagesDatabaseReference = mFirebaseDatabase.getReference().child("userdetails");
 mMessagesDatabaseReference.child( auth.getCurrentUser().getUid()).child("USERNAME")
</code>```

My database looks like following

How to get username while logging as only email and password is asked while logging. Any help would be appreciated.

答:
In order to get the user name, you need to attach a listener on that particular node. Please use the follwing code:

```<code>DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("userdetails").child(auth.getCurrentUser().getUid()).child("USERNAME");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        String USERNAME = dataSnapshot.getValue(String.class);
        Log.d("TAG", USERNAME);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
uidRef.addListenerForSingleValueEvent(eventListener);
</code>```

Your output will be:

```<code>pritish
</code>```

Body:
In my application i have registration screen. It asks for username,email and password. I am pushing email and username to firebase realtime database. Suppose now the user log out from my application, uninstall the application and install it again and try to login . In login screen i am only asking for email and password, how can i retrieve the username of user. As user may uninstall the app after registration so Shared Prefrence won't work. I tried the following code but it does not give proper output.

 mFirebaseDatabase = FirebaseDatabase.getInstance();
 mMessagesDatabaseReference = mFirebaseDatabase.getReference().child("userdetails");
 mMessagesDatabaseReference.child( auth.getCurrentUser().getUid()).child("USERNAME")

My database looks like following

How to get username while logging as only email and password is asked while logging. Any help would be appreciated.

Body:
In order to get the user name, you need to attach a listener on that particular node. Please use the follwing code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("userdetails").child(auth.getCurrentUser().getUid()).child("USERNAME");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        String USERNAME = dataSnapshot.getValue(String.class);
        Log.d("TAG", USERNAME);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
uidRef.addListenerForSingleValueEvent(eventListener);

Your output will be:

pritish


问:
Overriding bootstrap styles, not working
I'm trying to make a simple CSS file to make my app look decently, but I have a problem with it

```<code><div class='container-fluid'>
<div id="nav">
        <div class='col-sm-6' align="center">
                <h2>Utwórz nową sesje</h2>
                <br><br>
                <input class="form-control mr-sm-2" type="text" aria-label="Search"><br>
                <a class="btn btn-primary btn-md" href="#" role="button">Stwórz</a>
            </div>

        <div  class='col-sm-6' align="center">
            <h2>Dołącz do istniejącej sesji</h2>
            <br><br>
            <input class="form-control mr-sm-2" type="text" aria-label="Search"><br>
            <a class="btn btn-primary btn-ms" href="#" role="button">Dołącz</a>
        </div>

</div>
</code>```

And no matter if I make it

```<code>#bootstap-overrides  .container-fluid {
    background-color: #3b5998;
}
</code>```

Or

```<code>.container-fluid {
    background-color: #3b5998;
}
</code>```

or

```<code>.nav {
    background-color: #3b5998;
}
</code>```

Background is still white, as if bootstrap was overrding it. I'm a beggineer at CSS.

EDIT:

```<code>@Component({
selector: 'home',
templateUrl: './home.component.css'})
</code>```

The templateUrl field was wrong, so i fixed it. However, now the entire site appears white.

答:
You Should organize your CSS links like this

```<code><link rel="stylesheet" href="bootstrap/css/bootstrap.min.css"/>
<link rel="stylesheet" href="css/custom.css"/>
</code>```

First Bootstrap file and then your custom css file

Body:
I'm trying to make a simple CSS file to make my app look decently, but I have a problem with it

Utwórz nową sesje

                <input class="form-control mr-sm-2" type="text" aria-label="Search">

                Stwórz

Dołącz do istniejącej sesji

            <input class="form-control mr-sm-2" type="text" aria-label="Search">

            Dołącz

And no matter if I make it

#bootstap-overrides  .container-fluid {
    background-color: #3b5998;
}

Or

.container-fluid {
    background-color: #3b5998;
}

or

.nav {
    background-color: #3b5998;
}

Background is still white, as if bootstrap was overrding it. I'm a beggineer at CSS.

EDIT:

@Component({
selector: 'home',
templateUrl: './home.component.css'})

The templateUrl field was wrong, so i fixed it. However, now the entire site appears white.

Body:
You Should organize your CSS links like this

<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css"/>
<link rel="stylesheet" href="css/custom.css"/>

First Bootstrap file and then your custom css file


问:
Using AJAX with MVC 5 and Umbraco
I need to use ajax in a partial view to call a function in a mvc controller to return a calculation.

FYI, I am using MVC 5 and Umbraco 7.

I currently have the ajax code within the partial view (will want to move this to a js file at some point).

Here is the ajax code:

```<code>function GetTime(name) {
    var result = "";

    $.ajax({
        url: '/TimeDifference/GetTimeDifference',
        //url: '@Url.Action("GetTimeDifference", "TimeDifference")',
        type: 'GET',
        //data: JSON.stringify({ location: name }),
        data: ({ location: name }),
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        async: false,
        cache: false,
        success: function (msg) {
            result = msg;
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(xhr.status);
      }
    });

    return result;
}
</code>```

Here is the Controller:

```<code>public class TimeDifferenceController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
      [HttpGet]
       public JsonResult GetTimeDifference(string location)
        {
            DateTime utc = DateTime.UtcNow;
            string timeZoneName = GetTimeZoneName(location);
            TimeZoneInfo gmt = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
            TimeZoneInfo local = TimeZoneInfo.FindSystemTimeZoneById(timeZoneName);

            TimeSpan utcOffset = gmt.GetUtcOffset(utc);
            TimeSpan localOffset = local.GetUtcOffset(utc);
            TimeSpan difference = localOffset - utcOffset;

            return Json(Convert.ToInt16(difference.TotalMinutes),JsonRequestBehavior.AllowGet);

           }
}
</code>```

The above code gives me a 404 Not Found Error:

```<code>Request URL:http://localhost:100/TimeDifference/GetTimeDifference?location=BVI&_=1511949514552
Request Method:GET
Status Code:404 Not Found
Remote Address:[::1]:100
</code>```

If I use:
url: '@Url.Action("GetTimeDifference", "TimeDifference")'

The @Url.Action("GetTimeDifference", "TimeDifference") is Null so it doesn't go anywhere.

I have also tried:

```<code>@Html.Hidden("URLName", Url.Action("GetTimeDifference", "TimeDifference"))
...
url:  $("#URLName").val()
</code>```

Url is still Null.

I have added entries in to the Global.asax.cs for routing i.e.

```<code>routes.MapRoute(
                 "Default", // Route name
                 "{controller}/{action}/{id}", // URL with parameters
                 new { controller = "TimeDifference", action = "Index", id = UrlParameter.Optional } // Parameter defaults
             );
</code>```

This doesn't seem to do anything.

I have gone through a lot of the questions raised previously and amended as per suggestions but nothing seems to work.

As I am new to this I'm sure it something very simple I am missing.

Many thanks,
HH

答:
Your controller won't be wired automatically, and I don't think the global.asax.cs file will work either. You can either register a custom route for your controller in an Umbraco Startup Handler: https://our.umbraco.org/documentation/reference/routing/custom-routes or you can create your controller as an Umbraco WebApi Controller, which is designed for stuff like this: https://our.umbraco.org/documentation/Reference/Routing/WebApi/.

Umbraco WebAPI controllers get wired in automatically and will return either JSON or XML automatically depending on what the calling client asks for.

Title: Using AJAX with MVC 5 and Umbraco

Body:
I need to use ajax in a partial view to call a function in a mvc controller to return a calculation.

FYI, I am using MVC 5 and Umbraco 7.

I currently have the ajax code within the partial view (will want to move this to a js file at some point).

Here is the ajax code:

function GetTime(name) {
    var result = "";

    $.ajax({
        url: '/TimeDifference/GetTimeDifference',
        //url: '@Url.Action("GetTimeDifference", "TimeDifference")',
        type: 'GET',
        //data: JSON.stringify({ location: name }),
        data: ({ location: name }),
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        async: false,
        cache: false,
        success: function (msg) {
            result = msg;
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(xhr.status);
      }
    });

    return result;
}

Here is the Controller:

public class TimeDifferenceController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
      [HttpGet]
       public JsonResult GetTimeDifference(string location)
        {
            DateTime utc = DateTime.UtcNow;
            string timeZoneName = GetTimeZoneName(location);
            TimeZoneInfo gmt = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
            TimeZoneInfo local = TimeZoneInfo.FindSystemTimeZoneById(timeZoneName);

            TimeSpan utcOffset = gmt.GetUtcOffset(utc);
            TimeSpan localOffset = local.GetUtcOffset(utc);
            TimeSpan difference = localOffset - utcOffset;

            return Json(Convert.ToInt16(difference.TotalMinutes),JsonRequestBehavior.AllowGet);

           }
}

The above code gives me a 404 Not Found Error:

Request URL:http://localhost:100/TimeDifference/GetTimeDifference?location=BVI&_=1511949514552
Request Method:GET
Status Code:404 Not Found
Remote Address:[::1]:100

If I use:
url: '@Url.Action("GetTimeDifference", "TimeDifference")'

The @Url.Action("GetTimeDifference", "TimeDifference") is Null so it doesn't go anywhere.

I have also tried:

@Html.Hidden("URLName", Url.Action("GetTimeDifference", "TimeDifference"))
...
url:  $("#URLName").val()

Url is still Null.

I have added entries in to the Global.asax.cs for routing i.e.

routes.MapRoute(
                 "Default", // Route name
                 "{controller}/{action}/{id}", // URL with parameters
                 new { controller = "TimeDifference", action = "Index", id = UrlParameter.Optional } // Parameter defaults
             );

This doesn't seem to do anything.

I have gone through a lot of the questions raised previously and amended as per suggestions but nothing seems to work.

As I am new to this I'm sure it something very simple I am missing.

Many thanks,
HH


问:
Is there a way to install the scipy special module without the rest of scipy?
I'm writing some Python numerical code and would like to use some functions from the special module. So far, my code only depends on numpy, which I've found very easy to install in a variety of Python environments. Installing scipy, on the other hand, has generally been an exercise in frustration.  Is there a way to get just the special module?

Note, I see now that there is a downloadable scipy package for the Mac, but that hasn't always been the case

答: I'm not familiar with scipy in particular, but in general, modules for software packages depend on the installation of the package itself. So, yes, I'm pretty sure that you need to install scipy to use the special module.

OwnerDisplayName: Nick

LastEditorDisplayName: Jeff Bauer

OwnerDisplayName: Ben Alpert


问:
Peterson's algorithm: Can deadlock occur
if in peterson's algo, A process is preempted just after comming out of critical region before setting its flag to false. Then will not be there a deadlock. ??
plz help !</p>

答:
No deadlock. That's why we all learn this theoretical algorithm at schools.

note: You can encounter deadlock anywhere if you do something wrong. But it is not caused by a bug or property of this algorithm.


问:
Laravel 5.5 render a React component in a blade view with data from the controller
My goals is to be able to do something like this in my blade view.

```<code><Example name="{{ $user->name }}" />
</code>```

But this doesn't render anything.

When I do:

it renders the component without the props value which is normal.

So I am trying to pass data that came from my controller to my React component as a prop.

I am not sure if it's even possible.

This is my App.js:

```<code>require('./components/Example');
</code>```

This is my Example.js component:

```<code>import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class Example extends Component {
    render() {
        return (
            <div className="container">
                <div className="row">
                    <div className="col-md-8 col-md-offset-2">
                        <div className="panel panel-default">
                            <div className="panel-heading">Example</div>

                            <div className="panel-body">
                                Hello, {this.props.name}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        );
    }
}

if (document.getElementById('example')) {
    ReactDOM.render(<Example />, document.getElementById('example'));
}
</code>```

答:
You can do it like this..

```<code>@extends('layouts.app')

@section('script')
    <script type="text/javascript">
        ReactDOM.render(<Example name="{{ $user->name }}"/>, document.getElementById('example'));
    </script>
@endsection

@section('content')
    <div id="example"></div>
@endsection
</code>```

But better solution would be AJAX request to some controller that returns json data.

Best solution for you will this laravel package
laracasts/PHP-Vars-To-Js-Transformer

Body:
My goals is to be able to do something like this in my blade view.

<Example name="{{ $user->name }}" />

But this doesn't render anything.

When I do:

it renders the component without the props value which is normal.

So I am trying to pass data that came from my controller to my React component as a prop.

I am not sure if it's even possible.

This is my App.js:

require('./components/Example');

This is my Example.js component:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class Example extends Component {
    render() {
        return (

Example

                                Hello, {this.props.name}

        );
    }
}

if (document.getElementById('example')) {
    ReactDOM.render(<Example />, document.getElementById('example'));
}

Body:
You can do it like this..

@extends('layouts.app')

@section('script')
    <script type="text/javascript">
        ReactDOM.render(<Example name="{{ $user->name }}"/>, document.getElementById('example'));
    </script>
@endsection

@section('content')
    <div id="example"></div>
@endsection

But better solution would be AJAX request to some controller that returns json data.

Best solution for you will this laravel package
laracasts/PHP-Vars-To-Js-Transformer


问:
youtube-dl to exe doesn't work
this is the code

```<code>from tkinter import *
from tkinter import ttk
from tkinter import messagebox
from tkinter import filedialog
import youtube_dl
import os

class f(object):
    def __init__(self, finestra):
        self.finestra = finestra
        self.top = ttk.Frame(self.finestra, padding="10 10 10 10")
        self.top.grid(column=5, row=5)
        self.top.columnconfigure(1, weight=1)
        self.top.rowconfigure(1, weight=1)

        self.finestra.bind("<Return>",self.esegui_query)

        self.link = StringVar()
        self.esito = StringVar()
        self.bitrate = StringVar()
        self.esito.set("In Attesa")

        ttk.Label(self.top, text="Link:").grid(column=0,row=0)
        ttk.Entry(self.top, textvariable=self.link).grid(column=1,row=0)
        ttk.Button(self.top, text="Scarica", command=self.esegui_query).grid(column=2,row=0)

        ttk.Label(self.top, text="Bitrate:").grid(column=0,row=1)
        r1 = Radiobutton(self.top, text="192", variable=self.bitrate, value="192", cursor="dot")
        r1.grid(column=1,row=1)
        r2 = Radiobutton(self.top, text="320", variable=self.bitrate, value="320", cursor="dot")
        r2.grid(column=2,row=1)
        r1.select()
        ttk.Label(self.top, textvariable=self.esito).grid(column=3,row=1)

    def esegui_query(self,*argv):
        link = self.link.get()
        bitrate=self.bitrate.get()
        ydl_opts = {
        #'format': 'bestaudio/best',
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
            'preferredquality': bitrate,
                        }],
                    }
        self.esito.set("Downloading...")
        try:
            with youtube_dl.YoutubeDL(ydl_opts) as ydl:
                ydl.download([link])
            self.esito.set("Encoding...")
            for file in (os.listdir('.')):
                if file.endswith('.mp3') or file.endswith('.m4a') or file.endswith('.mp4'):
                    file2 = file[::-1][16:][::-1]
                    break
            self.esito.set("Download Completato")
        except Exception as e:
            self.esito.set("ERRORE")
            messagebox.showwarning("ERRORE",e)

finestra = Tk()
finestra.title("Download Youtube")
f = f(finestra)
finestra.mainloop()
</code>```

This code works in my IDLE python 3.6 x86, but not if i convert it in .exe with cx_Freeze

this is the code of setup.py to convert

```<code>from cx_Freeze import setup, Executable
import os,sys
os.environ['TCL_LIBRARY'] = r'C:\Program Files (x86)\Python36-32\tcl\tcl8.6'
os.environ['TK_LIBRARY'] = r'C:\Program Files (x86)\Python36-32\tcl\tk8.6'

#includes = ["youtube_dl","tkinter","os"]
include_files = [r'C:\Program Files (x86)\Python36-32\DLLs\tcl86t.dll',\
             r'C:\Program Files (x86)\Python36-32\DLLs\tk86t.dll']

base = 'Win32GUI' if sys.platform == 'win32' else None

executables = [Executable("youtube.py", base=base)]

packages = ["youtube_dl","tkinter","os"]
options = {
    'build_exe': {

        #'packages':packages,
        #'includes':includes,
        'include_files':include_files,
    },

}

setup(
    name = "youtube",
    options = options,
    version = "1.0",
    description = 'download from youtube',
    executables = executables
)
</code>```

The executable return to me this error: " 'NoneType' object has no attribute 'write' "
and this happens when the code execute this line:

```<code>with youtube_dl.YoutubeDL(ydl_opts) as ydl:
    ydl.download([link])  <-----
</code>```

I think is because youtube_dl first download a mp4 version of song and after doing the conversion. It first download and write in to the folder the song in mp4 version and i think there's the problem, convert it in mp3 and remove the mp4 version.

I think the error is in that line because have inserts some messagebox like this:

```<code>try:
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        messagebox.showwarning("ERRORE",'1') <--- this is showed
        ydl.download([link])
        messagebox.showwarning("ERRORE",'2') <--- this is not showed
    self.esito.set("Encoding...")
    for file in (os.listdir('.')):
        if file.endswith('.mp3') or file.endswith('.m4a') or file.endswith('.mp4'):
            file2 = file[::-1][16:][::-1]
            break
    self.esito.set("Download Completato")
except Exception as e:
    self.esito.set("ERRORE")
    messagebox.showwarning("ERRORE",e)
</code>```

and when i execute the .exe, the script starts but after i click to download a song the script show me just

```<code>messagebox.showwarning("ERRORE",'1')
</code>```

and the error

```<code>'NoneType' object has no attribute 'write'
</code>```

so he seems stop itself in that line

```<code>ydl.download([link])
</code>```

答:
I solved download youtube-dl.exe for windows and using it do download songs</p>

```<code>cmd = [d+r'\bin\youtube-dl.exe', '-x', '--audio-format=mp3',
       r'-o'+d+'\download\%(title)s.%(ext)s',
       '--audio-quality=%s' % (bitrate),
       '%s' % (link)
      ]

subprocess.call(cmd, shell=mshell)
</code>```

Title: youtube-dl to exe doesn't work

Body:
this is the code

from tkinter import *
from tkinter import ttk
from tkinter import messagebox
from tkinter import filedialog
import youtube_dl
import os

class f(object):
    def __init__(self, finestra):
        self.finestra = finestra
        self.top = ttk.Frame(self.finestra, padding="10 10 10 10")
        self.top.grid(column=5, row=5)
        self.top.columnconfigure(1, weight=1)
        self.top.rowconfigure(1, weight=1)

        self.finestra.bind("<Return>",self.esegui_query)

        self.link = StringVar()
        self.esito = StringVar()
        self.bitrate = StringVar()
        self.esito.set("In Attesa")

        ttk.Label(self.top, text="Link:").grid(column=0,row=0)
        ttk.Entry(self.top, textvariable=self.link).grid(column=1,row=0)
        ttk.Button(self.top, text="Scarica", command=self.esegui_query).grid(column=2,row=0)

        ttk.Label(self.top, text="Bitrate:").grid(column=0,row=1)
        r1 = Radiobutton(self.top, text="192", variable=self.bitrate, value="192", cursor="dot")
        r1.grid(column=1,row=1)
        r2 = Radiobutton(self.top, text="320", variable=self.bitrate, value="320", cursor="dot")
        r2.grid(column=2,row=1)
        r1.select()
        ttk.Label(self.top, textvariable=self.esito).grid(column=3,row=1)

    def esegui_query(self,*argv):
        link = self.link.get()
        bitrate=self.bitrate.get()
        ydl_opts = {
        #'format': 'bestaudio/best',
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
            'preferredquality': bitrate,
                        }],
                    }
        self.esito.set("Downloading...")
        try:
            with youtube_dl.YoutubeDL(ydl_opts) as ydl:
                ydl.download([link])
            self.esito.set("Encoding...")
            for file in (os.listdir('.')):
                if file.endswith('.mp3') or file.endswith('.m4a') or file.endswith('.mp4'):
                    file2 = file[::-1][16:][::-1]
                    break
            self.esito.set("Download Completato")
        except Exception as e:
            self.esito.set("ERRORE")
            messagebox.showwarning("ERRORE",e)

finestra = Tk()
finestra.title("Download Youtube")
f = f(finestra)
finestra.mainloop()

This code works in my IDLE python 3.6 x86, but not if i convert it in .exe with cx_Freeze

this is the code of setup.py to convert

from cx_Freeze import setup, Executable
import os,sys
os.environ['TCL_LIBRARY'] = r'C:\Program Files (x86)\Python36-32\tcl\tcl8.6'
os.environ['TK_LIBRARY'] = r'C:\Program Files (x86)\Python36-32\tcl\tk8.6'

#includes = ["youtube_dl","tkinter","os"]
include_files = [r'C:\Program Files (x86)\Python36-32\DLLs\tcl86t.dll',\
             r'C:\Program Files (x86)\Python36-32\DLLs\tk86t.dll']

base = 'Win32GUI' if sys.platform == 'win32' else None

executables = [Executable("youtube.py", base=base)]

packages = ["youtube_dl","tkinter","os"]
options = {
    'build_exe': {

        #'packages':packages,
        #'includes':includes,
        'include_files':include_files,
    },

}

setup(
    name = "youtube",
    options = options,
    version = "1.0",
    description = 'download from youtube',
    executables = executables
)

The executable return to me this error: " 'NoneType' object has no attribute 'write' "
and this happens when the code execute this line:

with youtube_dl.YoutubeDL(ydl_opts) as ydl:
    ydl.download([link])  <-----

I think is because youtube_dl first download a mp4 version of song and after doing the conversion. It first download and write in to the folder the song in mp4 version and i think there's the problem, convert it in mp3 and remove the mp4 version.

I think the error is in that line because have inserts some messagebox like this:

try:
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        messagebox.showwarning("ERRORE",'1') <--- this is showed
        ydl.download([link])
        messagebox.showwarning("ERRORE",'2') <--- this is not showed
    self.esito.set("Encoding...")
    for file in (os.listdir('.')):
        if file.endswith('.mp3') or file.endswith('.m4a') or file.endswith('.mp4'):
            file2 = file[::-1][16:][::-1]
            break
    self.esito.set("Download Completato")
except Exception as e:
    self.esito.set("ERRORE")
    messagebox.showwarning("ERRORE",e)

and when i execute the .exe, the script starts but after i click to download a song the script show me just

messagebox.showwarning("ERRORE",'1')

and the error

'NoneType' object has no attribute 'write'

so he seems stop itself in that line

ydl.download([link])

Body:
I solved download youtube-dl.exe for windows and using it do download songs

cmd = [d+r'\bin\youtube-dl.exe', '-x', '--audio-format=mp3',
       r'-o'+d+'\download\%(title)s.%(ext)s',
       '--audio-quality=%s' % (bitrate),
       '%s' % (link)
      ]

subprocess.call(cmd, shell=mshell)


问:
Change the color of a link over time (so that it doesn't begin a new cycle on refresh)
I'm trying to change the color of a link over time cycling through rainbow colors. When you refresh the color should still be the same it was a moment ago, not begin a new cycle (so CSS animations haven't worked for me yet either).

I am trying to apply the color of this calculation to the hover function of a link.

```<code>  var h = ( 60 * ( color[0] + time ) % 360 ) / 360;
  materials[i].color.setHSL( h, color[1], color[2] );
  var time = Date.now() * 0.00005;
</code>```

Any help would be greatly appreciated.

答:
This can be cleaned up a little, but this should get you started. I'm assuming the hue is what you actually want to save since your method is using color[0] for the calculation. So I am saving hue, but you can modify this to fit your need. It uses web storage to save the hue: https://www.w3schools.com/html/html5_webstorage.asp</p>

```<code>// init function(run on page load, either fresh or after refresh)
$(function() {
    var hue = null;

    // check if local storage supported
    if (typeof(Storage) !== "undefined") {
        // check if hue saved
        if (sessionStorage.hue) {
            hue = sessionStorage.hue;
        }
    }
    // check if hue is still null, if so, it is a fresh page load
    // or storage isn't supported and we need to calculate it
    if (!hue) {
        // call your hue function here
        hue = getNewHue();
    }
    // save hue
    saveHue(hue);
});

// run everytime the mouse hovers over your link
// you can convert this to an interval function like
// in Jordi's answer if you want
$('#colorlink').on('hover', function() {
    // get a new hue
    var hue = getNewHue();
    // call your hue function here
    saveHue(hue);
})

function saveHue(hue) {
    // set hue on link
    var hslText = "hsl(" + hue + "," + color[1] + "%," + color[2] + "%)";
    $('#colorlink').css({ color = hslText });

    // also saving this to update materials[i] as well
    // not sure if you still need this
    materials[i].color.setHSL(hue, color[1], color[2]);

    // save hue to storage in case of refresh
    sessionStorage.setItem('hue', hue);
}

function getNewHue() {
    return (60 * (color[0] + time) % 360) / 360;
}
</code>```

Body:
I'm trying to change the color of a link over time cycling through rainbow colors. When you refresh the color should still be the same it was a moment ago, not begin a new cycle (so CSS animations haven't worked for me yet either).

I am trying to apply the color of this calculation to the hover function of a link.

  var h = ( 60 * ( color[0] + time ) % 360 ) / 360;
  materials[i].color.setHSL( h, color[1], color[2] );
  var time = Date.now() * 0.00005;

Any help would be greatly appreciated.

Body:
This can be cleaned up a little, but this should get you started. I'm assuming the hue is what you actually want to save since your method is using color[0] for the calculation. So I am saving hue, but you can modify this to fit your need. It uses web storage to save the hue: https://www.w3schools.com/html/html5_webstorage.asp

// init function(run on page load, either fresh or after refresh)
$(function() {
    var hue = null;

    // check if local storage supported
    if (typeof(Storage) !== "undefined") {
        // check if hue saved
        if (sessionStorage.hue) {
            hue = sessionStorage.hue;
        }
    }
    // check if hue is still null, if so, it is a fresh page load
    // or storage isn't supported and we need to calculate it
    if (!hue) {
        // call your hue function here
        hue = getNewHue();
    }
    // save hue
    saveHue(hue);
});

// run everytime the mouse hovers over your link
// you can convert this to an interval function like
// in Jordi's answer if you want
$('#colorlink').on('hover', function() {
    // get a new hue
    var hue = getNewHue();
    // call your hue function here
    saveHue(hue);
})

function saveHue(hue) {
    // set hue on link
    var hslText = "hsl(" + hue + "," + color[1] + "%," + color[2] + "%)";
    $('#colorlink').css({ color = hslText });

    // also saving this to update materials[i] as well
    // not sure if you still need this
    materials[i].color.setHSL(hue, color[1], color[2]);

    // save hue to storage in case of refresh
    sessionStorage.setItem('hue', hue);
}

function getNewHue() {
    return (60 * (color[0] + time) % 360) / 360;
}


问:
AndroidMediaPlayer error code -1005
I implemented a video activity based on MediaPlayer and with a MediaPlayer.OnErrorListener.

In Android-L, the onError is invoked with:

onError(mp, what=1, extra=-1005)

What does code -1005 mean?

Edit: I looked in the error code definition in pvmf_return_codes.h suggested by Complete list of MediaPlayer error codes

答: -1005 is "connection lost", see this webpage for a complete list of codes.</p>

Title: AndroidMediaPlayer error code -1005


问:
Logic: is ( A && !(B || C)) || ( B || C ) the same as ( A || B || C )?
I've encountered some obj-c code and I'm wondering if there's a way to simplify it:

```<code>#if ( A && !(B || C)) || ( B || C )
</code>```

is this the same as?

```<code>#if ( A || B || C )
</code>```

If not, is there another way to formulate it that would be easier to read?

[edit]
I tried the truth table before asking the question, but thought I had to be missing something because I doubted that Foundation.framework/Foundation.h would employ this more complex form.   Is there a good reason for it?

Here's the original code (from Foundation.h):

```<code>#if (TARGET_OS_MAC && !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE)) || (TARGET_OS_EMBEDDED || TARGET_OS_IPHONE)
</code>```

答:
Yes it is the same. Using De Morgan rules:

(A && !(B || C)) || (B || C) = (A && !B && !C) || (B || C).
So the second will be true when A = 1 and B, C = 0. If that is not the case the second part (B || C) will be true when B || C. So it is equal to the first.

Body:
I've encountered some obj-c code and I'm wondering if there's a way to simplify it:

#if ( A && !(B || C)) || ( B || C )

is this the same as?

#if ( A || B || C )

If not, is there another way to formulate it that would be easier to read?

[edit]
I tried the truth table before asking the question, but thought I had to be missing something because I doubted that Foundation.framework/Foundation.h would employ this more complex form.   Is there a good reason for it?

Here's the original code (from Foundation.h):

#if (TARGET_OS_MAC && !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE)) || (TARGET_OS_EMBEDDED || TARGET_OS_IPHONE)


问:
Rails Angular webpack foreman
I created a new rails app with this command

```<code>rails new anrails --webpack=angular -d postgresql -T
</code>```

and except few warnings and errors likes these

```<code>warning fsevents@1.1.2: The platform "linux" is incompatible with this module.
warning "rails-erb-loader@5.0.2" has incorrect peer dependency "webpack@2".

An unexpected error occurred: "EPROTO: protocol error, symlink '../acorn/bin/acorn' -> '/vagrant/Sites/anrails/node_modules/acorn-dynamic-import/node_modules/.bin/acorn'".

warning "webpack-dev-middleware@1.11.0" has unmet peer dependency "webpack@^1.0.0 || ^2.0.0 || ^3.0.0".
warning "webpack-dev-server@2.5.1" has unmet peer dependency "webpack@^2.2.0 || ^3.0.0".

error An unexpected error occurred: "EPROTO: protocol error, symlink '../../../multicast-dns/cli.js' -> '/vagrant/Sites/anrails/node_modules/bonjour/node_modules/.bin/multicast-dns'".
</code>```

I got the message: Webpacker successfully installed.

Then it installs the angular and its dependencies and get this error

```<code>error An unexpected error occurred: "EPROTO: protocol error, symlink '../../../json5/lib/cli.js' -> '/vagrant/Sites/anrails/node_modules/loader-utils/node_modules/.bin/json5'".
</code>```

after this I get the message: Webpacker now supports angular and typescript.

So I create a Procfile in root folder of the app

```<code>web: bundle exec rails s -b 0.0.0.0
webpacker: bin/webpack-dev-server
</code>```

and run foreman start and get the following

```<code>09:40:39 web.1       | started with pid 4514
09:40:39 webpacker.1 | started with pid 4515
09:40:40 webpacker.1 | yarn run v0.27.5
09:40:40 webpacker.1 | error Command "webpack-dev-server" not found.
09:40:40 webpacker.1 | info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
09:40:40 webpacker.1 | exited with code 1
09:40:40 system      | sending SIGTERM to all processes
09:40:41 web.1       | terminated by SIGTERM
</code>```

Running in vagrant on Windows, ruby 2.4.1p111, Rails 5.1.2, node 6.11.1, yarn 0.27.5

答:
As your code is saying: error Command "webpack-dev-server" not found. there is something wrong in your bin folder.

Mine for example looks like this:

Check your folder first and see if everything is in place.

And.. Have you tried with the current folder dot?: ./bin/webpack-dev-server?

Title: Rails Angular webpack foreman

Body:
I created a new rails app with this command

rails new anrails --webpack=angular -d postgresql -T

and except few warnings and errors likes these

warning fsevents@1.1.2: The platform "linux" is incompatible with this module.
warning "rails-erb-loader@5.0.2" has incorrect peer dependency "webpack@2".

An unexpected error occurred: "EPROTO: protocol error, symlink '../acorn/bin/acorn' -> '/vagrant/Sites/anrails/node_modules/acorn-dynamic-import/node_modules/.bin/acorn'".

warning "webpack-dev-middleware@1.11.0" has unmet peer dependency "webpack@^1.0.0 || ^2.0.0 || ^3.0.0".
warning "webpack-dev-server@2.5.1" has unmet peer dependency "webpack@^2.2.0 || ^3.0.0".

error An unexpected error occurred: "EPROTO: protocol error, symlink '../../../multicast-dns/cli.js' -> '/vagrant/Sites/anrails/node_modules/bonjour/node_modules/.bin/multicast-dns'".

I got the message: Webpacker successfully installed.

Then it installs the angular and its dependencies and get this error

error An unexpected error occurred: "EPROTO: protocol error, symlink '../../../json5/lib/cli.js' -> '/vagrant/Sites/anrails/node_modules/loader-utils/node_modules/.bin/json5'".

after this I get the message: Webpacker now supports angular and typescript.

So I create a Procfile in root folder of the app

web: bundle exec rails s -b 0.0.0.0
webpacker: bin/webpack-dev-server

and run foreman start and get the following

09:40:39 web.1       | started with pid 4514
09:40:39 webpacker.1 | started with pid 4515
09:40:40 webpacker.1 | yarn run v0.27.5
09:40:40 webpacker.1 | error Command "webpack-dev-server" not found.
09:40:40 webpacker.1 | info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
09:40:40 webpacker.1 | exited with code 1
09:40:40 system      | sending SIGTERM to all processes
09:40:41 web.1       | terminated by SIGTERM

Running in vagrant on Windows, ruby 2.4.1p111, Rails 5.1.2, node 6.11.1, yarn 0.27.5


问:
How to use custom error handler service across different modules in angular2
I have created  a module for error logging and i have extended default angular ErrorHandler class
Below is the code

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
private errorLogService: ErrorLogService;

constructor(
    errorLogService: ErrorLogService) {
    this.errorLogService = errorLogService;
}

public handleError( error: any ) : void {

    // Log to the console.
    try {
        console.error( error.message );
        console.error( error.stack );
    } catch ( handlingError ) {
        console.error( handlingError );
    }

   }
```

I have bootstrapped this in my exceptionhandling module. I want to use this in my other modules - adminmodule and clientmodule. How can i do that?

答:
You need to tell Angular to use your "GlobalErrorHandler" adding the provider into your app.module (because it represents the root level of your application)

This is an example of app.module.ts

import { NgModule, ApplicationRef, ErrorHandler } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { GlobalErrorHandler } from './error-handler'; //<-- adapt the "from" to your file
import { ServicesModule } from './services';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule],
  bootstrap: [AppComponent],
  providers: [
    {
      provide: ErrorHandler,
      useClass: GlobalErrorHandler
    }
  ]
})
export class AppModule { }
```

Body:
I have created  a module for error logging and i have extended default angular ErrorHandler class
Below is the code

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
private errorLogService: ErrorLogService;

constructor(
    errorLogService: ErrorLogService) {
    this.errorLogService = errorLogService;
}

public handleError( error: any ) : void {

    // Log to the console.
    try {
        console.error( error.message );
        console.error( error.stack );
    } catch ( handlingError ) {
        console.error( handlingError );
    }

   }

I have bootstrapped this in my exceptionhandling module. I want to use this in my other modules - adminmodule and clientmodule. How can i do that?


问:
Nesting conditionals in Java
The Problem

Given the following code:

```<code>if (enforceLength && rawContents.length != recordLength) {
</code>```

Right now if enforceLength and rawContents does not match recordLength, it returns true and triggers our warning system. Some of our recordLength however are HEADER_DIFF characters longer than the rawContents.length.

So we are hoping to put an or on rawContents.length so that it can either match recordLength or recordLength + HEADER_DIFF.

Question

Is there a straightforward way to create an OR conditional on just the second part of this if statement? i.e. so that it triggers the alert if rawContents.length does not equal recordLength but it does not if recordLength happens to be exactly HEADER_DIFF longer than expected.

A failed attempt

One attempt that failed:

```<code>if (enforceLength && rawContents.length != recordLength + HEADER_DIFF
  || rawContents.length != recordLength)
</code>```

答:
Have you thought about using a nested if?

```<code>if (enforceLength)
{
    if(test for header diff)
     {
        rawContents.length != recordLength + HEADER_DIFF
     }

    else
    {
     rawContents.length != recordLength)
    }
}
</code>```

It is more convoluted but eaiser to understand.

Title: Nesting conditionals in Java

Body:
The Problem

Given the following code:

if (enforceLength && rawContents.length != recordLength) {

Right now if enforceLength and rawContents does not match recordLength, it returns true and triggers our warning system. Some of our recordLength however are HEADER_DIFF characters longer than the rawContents.length.

So we are hoping to put an or on rawContents.length so that it can either match recordLength or recordLength + HEADER_DIFF.

Question

Is there a straightforward way to create an OR conditional on just the second part of this if statement? i.e. so that it triggers the alert if rawContents.length does not equal recordLength but it does not if recordLength happens to be exactly HEADER_DIFF longer than expected.

A failed attempt

One attempt that failed:

if (enforceLength && rawContents.length != recordLength + HEADER_DIFF
  || rawContents.length != recordLength)

Body:
Have you thought about using a nested if?

if (enforceLength)
{
    if(test for header diff)
     {
        rawContents.length != recordLength + HEADER_DIFF
     }

    else
    {
     rawContents.length != recordLength)
    }
}

It is more convoluted but eaiser to understand.


问:
Click Listeners on the Horizontal RecyclerView in a Vertical RecyclerView
I will try to explain my problem in brief here. Please refer to the github link for my project if my explanation here not enough. Github link

I have a horizontal recycler view inside a vertical recycler view. I've on click listeners for the vertical items and that just works fine.

I want to also have an onClickListener for the horizontally scrolling list. But the app crashes when I implement the same for it.

I've implemented the click listener using an interface in the adapter and implementing the interface in the fragment/activity.

I am initializing the horizontal recycler view and the adapter for it inside the main adapter and not in the  activity code.

I am getting the following error

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference

答:
After looking trough your code I found that the problem lies in the RVAdapter on like no. 380:

```<code>holder.horizontalAdapter = new SectionRVAdapter(holder.context,holder.sections, new MainActivityFragment());
</code>```

Right here you pass the fragment as a click listener, but instead of passing the fragment instance that you already have you create a new fragment instance. This fragment will get called when the user clicks but it doesn't have a context since it hasn't been attached (there hasn't been any fragment transaction).

What you should do instead is pass the fragment you already have. Right now you have a ListItemOnClickHandler in your RVAdapter, but it should be an interface that can handle both clicks. What I would do is the following;

Create an interface that has two methods, a regular list click (i.e. onListItemClicked()) and a method to handle horizontal clicks (i.e. onHorizontalItemClicked())

Make sure the fragment implements this interface (let's call it, ClickInterface)

Pass ClickInterface in the constructor of RVAdapter, save it in a field and when initalizing the SubsectionRVAdapter pass the SAME click listener (the same instance)

That way you can pass around your fragment without having to worry about the context not being present. You can then call the appropriate methods in the ViewHolders of each respective adapter.

Hope thats gonna work!

Body:
After looking trough your code I found that the problem lies in the RVAdapter on like no. 380:

holder.horizontalAdapter = new SectionRVAdapter(holder.context,holder.sections, new MainActivityFragment());

Right here you pass the fragment as a click listener, but instead of passing the fragment instance that you already have you create a new fragment instance. This fragment will get called when the user clicks but it doesn't have a context since it hasn't been attached (there hasn't been any fragment transaction).

What you should do instead is pass the fragment you already have. Right now you have a ListItemOnClickHandler in your RVAdapter, but it should be an interface that can handle both clicks. What I would do is the following;

Create an interface that has two methods, a regular list click (i.e. onListItemClicked()) and a method to handle horizontal clicks (i.e. onHorizontalItemClicked())

Make sure the fragment implements this interface (let's call it, ClickInterface)

Pass ClickInterface in the constructor of RVAdapter, save it in a field and when initalizing the SubsectionRVAdapter pass the SAME click listener (the same instance)

That way you can pass around your fragment without having to worry about the context not being present. You can then call the appropriate methods in the ViewHolders of each respective adapter.

Hope thats gonna work!


问:
WPF Listview SORT and FILTER performance issue
I have listview with custom sort and filter implemented on it...It is textbox based filter , as user types in,  items in the listview are filtered. Now...when i apply sort on listview,  filter is very slow because each time custom sort compare method is called for each item in listview while filtering... how I can avoid compare method call of custom sort while filtering ? </p>

答:
List performance issues can also be caused by a non-virtualized list:

for a virtualized list only the visible elements are calculated for the display, whereas for a non-virtualized list, the display is calculated for all the items.
This can be disastrous for lists of a few hundred items.

WPF: List boxes and virtualization


问:
why do the String members of my nodes print a blank line after getting created?
```<code>#include <stdio.h>
#include <stdlib.h>

#define MAXLINE 80

typedef struct Node{
    char *data;
    struct Node *next;
}Node;

int get_Line(FILE *fp, char s[], int lim);
Node* addNode(Node *front, char *data);
Node* fillList(Node *front, char *txtFile, int lim);

int main () {
    Node *dataFront = NULL;
    dataFront = fillList(dataFront,"data.txt",MAXLINE);
    printf("%s\n",dataFront->data); //prints blank line
    return 0;
}

int get_Line(FILE *fp, char s[], int lim){
    int c, i;
    for (i = 0; i < lim-1 && (c=getc(fp)) != EOF && c != '\n'; ++i)
        s[i] = c;
    if (c == '\n'){
        s[i] = c;
        ++i;
    }
    s[i] = '\0';
    return i;
}

Node* addNode(Node *front, char *data){
    Node *newNode = (Node*)malloc(sizeof(Node));
    newNode->data = data;
    newNode->next = NULL;
    if(front!= NULL)
        newNode->next = front;
    front = newNode;
    return front;
}

Node* fillList(Node *front, char *txtFile, int lim){
    FILE *fp = fopen(txtFile,"r");
    char data[lim];
    while(get_Line(fp,data,lim) > 0){
        front = addNode(front, data);
        printf("%s\n",front->data); //prints the string member of Node
                                    //front just fine
    }
    printf("%s\n",front->data); //prints blank line
    fclose(fp);
    return front;
}
</code>```

I am creating a list of nodes that contain strings by reading lines from a text file. The text file could be anything.

I put print statements in the function fillList to help debug. In the function fillList printing front->data within the while loop works, but outside the while loop a blank line is printed. In main printing the string member gives a blank line as well. I need help fixing this. Off of my debugging get_Line and addNode works fine.

EDIT 1:
My text file - data.txt - contains the following text -
   txt file screenshot
- My output can be seen in this jpeg:
output screenshot

答:
The problem is in your addNode function:

```<code>newNode->data = data;
</code>```

Here, the data parameter corresponds to the data array defined in fillList.  So the data member of each list element points back to the data array in fillList.  This means that all list elements contain the same data.  When you then leave the while loop, data contains an empty string.  And since all nodes data member points to the local data array, you get an empty string when you print front-data.

Even worse, when you return from fillList, the list elements now point to a local variable which is now out of scope.  You then invoke undefined behavior by dereferencing that invalid pointer when you call printf from main.  The blank line you see when printing from main is what happens to be in that invalid memory location, and you can't depend on that beahvior to be consistent.

You can fix this by allocating a new buffer for each list element and copying the string into that buffer.  You can do both at once using strdup:

```<code>newNode->data = strdup(data);
</code>```

Also you'll want to add code when your program exits to deallocate both the nodes in the list and the strings they contain so you don't have a memory leak.

Body:
#include <stdio.h>
#include <stdlib.h>

#define MAXLINE 80

typedef struct Node{
    char *data;
    struct Node *next;
}Node;

int get_Line(FILE *fp, char s[], int lim);
Node* addNode(Node *front, char *data);
Node* fillList(Node *front, char *txtFile, int lim);

int main () {
    Node *dataFront = NULL;
    dataFront = fillList(dataFront,"data.txt",MAXLINE);
    printf("%s\n",dataFront->data); //prints blank line
    return 0;
}

int get_Line(FILE *fp, char s[], int lim){
    int c, i;
    for (i = 0; i < lim-1 && (c=getc(fp)) != EOF && c != '\n'; ++i)
        s[i] = c;
    if (c == '\n'){
        s[i] = c;
        ++i;
    }
    s[i] = '\0';
    return i;
}

Node* addNode(Node *front, char *data){
    Node *newNode = (Node*)malloc(sizeof(Node));
    newNode->data = data;
    newNode->next = NULL;
    if(front!= NULL)
        newNode->next = front;
    front = newNode;
    return front;
}

Node* fillList(Node *front, char *txtFile, int lim){
    FILE *fp = fopen(txtFile,"r");
    char data[lim];
    while(get_Line(fp,data,lim) > 0){
        front = addNode(front, data);
        printf("%s\n",front->data); //prints the string member of Node
                                    //front just fine
    }
    printf("%s\n",front->data); //prints blank line
    fclose(fp);
    return front;
}

I am creating a list of nodes that contain strings by reading lines from a text file. The text file could be anything.

I put print statements in the function fillList to help debug. In the function fillList printing front->data within the while loop works, but outside the while loop a blank line is printed. In main printing the string member gives a blank line as well. I need help fixing this. Off of my debugging get_Line and addNode works fine.

EDIT 1:
My text file - data.txt - contains the following text -
   txt file screenshot
- My output can be seen in this jpeg:
output screenshot

Body:
The problem is in your addNode function:

newNode->data = data;

Here, the data parameter corresponds to the data array defined in fillList.  So the data member of each list element points back to the data array in fillList.  This means that all list elements contain the same data.  When you then leave the while loop, data contains an empty string.  And since all nodes data member points to the local data array, you get an empty string when you print front-data.

Even worse, when you return from fillList, the list elements now point to a local variable which is now out of scope.  You then invoke undefined behavior by dereferencing that invalid pointer when you call printf from main.  The blank line you see when printing from main is what happens to be in that invalid memory location, and you can't depend on that beahvior to be consistent.

You can fix this by allocating a new buffer for each list element and copying the string into that buffer.  You can do both at once using strdup:

newNode->data = strdup(data);

Also you'll want to add code when your program exits to deallocate both the nodes in the list and the strings they contain so you don't have a memory leak.


问:
Unity c# Iterate over a Firebase Snapshot
I have this json database

```<code>{
"shops" : {
        "7" : {
          "cod1" : {
            "name" : "name3",
            "description" : "xxx",

          },
          "cod2" : {
            "name" : "name2",
            "description" : "xxx",

          },
          "cod3" : {
            "name" : "name1",
            "description" : "xxx",

          },
</code>```

I need to iterate over the snapshot to get cod1,cod2,cod3 and i need to do something for every one of those codes that I do not previously know

```<code>public void load(string city){
//city is number 7 in this case;
        Firebase.Auth.FirebaseUser user = auth.CurrentUser;
        FirebaseDatabase.DefaultInstance
                        .RootReference.Child ("shops").Child (city)
            .GetValueAsync ().ContinueWith (task => {
            if (task.IsFaulted) {
                // Handle the error...
            } else if (task.IsCompleted) {
                DataSnapshot snapshot = task.Result;
                int i = 0;

                foreach (DataSnapshot shop in snapshot.Children) {
                        debug.text = "\nstarting with #" + i.ToString () + ": " + shop.Key+";\n";

                        i++;
                }

            }
        });
</code>```

I need debug.text to show "Starting with #1: cod1" and then again with cod2 and cod3

Now I get something like "Starting with #1: 7" that is the key of the parent of those codes

Is there a way to get those codes?

答:
Well, first of all, your JSON isn't really formatted as it should be. If you want data to be returned accurately, "shops" should be an array, not an object. Like so:

```<code>"shops" : [
  "cod1" : {
        "name" : "name3",
        "description" : "xxx"
      },
      "cod2" : {
        "name" : "name2",
        "description" : "xxx"
      },
      "cod3" : {
        "name" : "name1",
        "description" : "xxx"
      }
]
</code>```

Currently, "shops" is an object, which has a child object "7", which is the parent of cod1, cod2, and cod3. Which is also why you're seeing "7".

Body:
I have this json database

{
"shops" : {
        "7" : {
          "cod1" : {
            "name" : "name3",
            "description" : "xxx",

          },
          "cod2" : {
            "name" : "name2",
            "description" : "xxx",

          },
          "cod3" : {
            "name" : "name1",
            "description" : "xxx",

          },

I need to iterate over the snapshot to get cod1,cod2,cod3 and i need to do something for every one of those codes that I do not previously know

public void load(string city){
//city is number 7 in this case;
        Firebase.Auth.FirebaseUser user = auth.CurrentUser;
        FirebaseDatabase.DefaultInstance
                        .RootReference.Child ("shops").Child (city)
            .GetValueAsync ().ContinueWith (task => {
            if (task.IsFaulted) {
                // Handle the error...
            } else if (task.IsCompleted) {
                DataSnapshot snapshot = task.Result;
                int i = 0;

                foreach (DataSnapshot shop in snapshot.Children) {
                        debug.text = "\nstarting with #" + i.ToString () + ": " + shop.Key+";\n";

                        i++;
                }

            }
        });

I need debug.text to show "Starting with #1: cod1" and then again with cod2 and cod3

Now I get something like "Starting with #1: 7" that is the key of the parent of those codes

Is there a way to get those codes?

Body:
Well, first of all, your JSON isn't really formatted as it should be. If you want data to be returned accurately, "shops" should be an array, not an object. Like so:

"shops" : [
  "cod1" : {
        "name" : "name3",
        "description" : "xxx"
      },
      "cod2" : {
        "name" : "name2",
        "description" : "xxx"
      },
      "cod3" : {
        "name" : "name1",
        "description" : "xxx"
      }
]

Currently, "shops" is an object, which has a child object "7", which is the parent of cod1, cod2, and cod3. Which is also why you're seeing "7".