问:
ParseError: expected "indent", got "!"
I am trying to build an Vuejs application with stylus.
I install stylus stylus-loader style-loader css-loader  add added in build/webpack.base.conf.js at rules array.

```<code>{
  test: /\.styl$/,
  loader: ['style-loader', 'css-loader', 'stylus-loader']
}
</code>```

and I created a empty file in src folder name main.styl and added in main.js.

when I run npm run dev its showing an error,

Module build failed: ParseError: expected "indent", got "!"

What wrong goes here...

答:
I met the same problem about import *.styl into the main.js.

My solution: open the webpack.base.conf.js, find the "module.rules" part, assert

```<code>{
  test: /\.css$/,
  use: ['style-loader', 'css-loader', 'stylus-loader'],
},
</code>```

My project based on "vue^2.5.2", vue-cli^2.8.2, I hope that can help you.

my webpack.base.conf.js file:

Title: ParseError: expected "indent", got "!"

Body:
I am trying to build an Vuejs application with stylus.
I install stylus stylus-loader style-loader css-loader  add added in build/webpack.base.conf.js at rules array.

{
  test: /\.styl$/,
  loader: ['style-loader', 'css-loader', 'stylus-loader']
}

and I created a empty file in src folder name main.styl and added in main.js.

when I run npm run dev its showing an error,

Module build failed: ParseError: expected "indent", got "!"

What wrong goes here...

Body:
I met the same problem about import *.styl into the main.js.

My solution: open the webpack.base.conf.js, find the "module.rules" part, assert

{
  test: /\.css$/,
  use: ['style-loader', 'css-loader', 'stylus-loader'],
},

My project based on "vue^2.5.2", vue-cli^2.8.2, I hope that can help you.

my webpack.base.conf.js file:


来源: stackexchange

问:
Union Struct C# - Equivalent Or Equals?
see struct below

```<code>struct STRUCT_ITEM
{

short Index;

    union
    {
        short Value;

        struct
        {
            unsigned char Type;
            unsigned char Values;
        };

    } Effect[3];
};
</code>```

Hello .. Good evening. I would like if it is possible to convert a structure in C ++ to C #?
I would like the new structure to contain the array of 3 objects, as you can see in the code in C ++.

Is to be used like this:

```<code>var Item = new Item ();

Item.Effect [2] .Type = 2;
</code>```

I just get it that way:

```<code>    [FieldOffset(0)]
    public short Index;

    [FieldOffset(2)]
    public short MountHP;

    [FieldOffset(2)]
    public byte EF1;

    [FieldOffset(3)]
    public byte EFV1;

    [FieldOffset(4)]
    public byte EF2;

    [FieldOffset(5)]
    public byte EFV2;

    [FieldOffset(6)]
    public byte EF3;

    [FieldOffset(7)]
    public byte EFV3;
</code>```

Is it possible to contain array in the structure? This structure contains the maximum size of 8 bytes.

Who can help, I am grateful! Thank you so much

答:
Try this.
and Yes, The array can use in Sturcture.

```<code>    [StructLayout(LayoutKind.Explicit)]
    public struct STRUCT_SUB_ITEM
    {
        [FieldOffset(0)]
        public short Value;
        [FieldOffset(0)]
        public byte Type;
        [FieldOffset(1)]
        public byte Values;
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct STRUCT_ITEM
    {
        short index;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
        public STRUCT_SUB_ITEM[] Effect;
    }
</code>```

and Test just like this.

```<code>    static void test3()
    {
        STRUCT_ITEM item = new STRUCT_ITEM();
        item.Effect = new STRUCT_SUB_ITEM[3];

        item.Effect[0].Type = 1;
        item.Effect[0].Values = 2;

        item.Effect[1].Type = 1;
        item.Effect[1].Values = 2;

        item.Effect[2].Type = 1;
        item.Effect[2].Values = 2;

        Console.WriteLine(item.Effect[2].Value);
    }
</code>```

And an Array with restrict types (bool, int, double, ... ) Using Fixed keyword,  it dosen't need alloc memory.

```<code>    [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Ansi)]
    public unsafe struct STRUCT_ITEM2
    {
        [FieldOffset(0)]
        public fixed byte item_01[260];
    }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Union Struct C# - Equivalent Or Equals?

Body:
see struct below

struct STRUCT_ITEM
{

short Index;

    union
    {
        short Value;

        struct
        {
            unsigned char Type;
            unsigned char Values;
        };

    } Effect[3];
};

Hello .. Good evening. I would like if it is possible to convert a structure in C ++ to C #?
I would like the new structure to contain the array of 3 objects, as you can see in the code in C ++.

Is to be used like this:

var Item = new Item ();

Item.Effect [2] .Type = 2;

I just get it that way:

    [FieldOffset(0)]
    public short Index;

    [FieldOffset(2)]
    public short MountHP;

    [FieldOffset(2)]
    public byte EF1;

    [FieldOffset(3)]
    public byte EFV1;

    [FieldOffset(4)]
    public byte EF2;

    [FieldOffset(5)]
    public byte EFV2;

    [FieldOffset(6)]
    public byte EF3;

    [FieldOffset(7)]
    public byte EFV3;

Is it possible to contain array in the structure? This structure contains the maximum size of 8 bytes.

Who can help, I am grateful! Thank you so much

Body:
Try this.
and Yes, The array can use in Sturcture.

    [StructLayout(LayoutKind.Explicit)]
    public struct STRUCT_SUB_ITEM
    {
        [FieldOffset(0)]
        public short Value;
        [FieldOffset(0)]
        public byte Type;
        [FieldOffset(1)]
        public byte Values;
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct STRUCT_ITEM
    {
        short index;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
        public STRUCT_SUB_ITEM[] Effect;
    }

and Test just like this.

    static void test3()
    {
        STRUCT_ITEM item = new STRUCT_ITEM();
        item.Effect = new STRUCT_SUB_ITEM[3];

        item.Effect[0].Type = 1;
        item.Effect[0].Values = 2;

        item.Effect[1].Type = 1;
        item.Effect[1].Values = 2;

        item.Effect[2].Type = 1;
        item.Effect[2].Values = 2;

        Console.WriteLine(item.Effect[2].Value);
    }

And an Array with restrict types (bool, int, double, ... ) Using Fixed keyword,  it dosen't need alloc memory.

    [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Ansi)]
    public unsafe struct STRUCT_ITEM2
    {
        [FieldOffset(0)]
        public fixed byte item_01[260];
    }


问:
get value of [object HTMLDivElement]
I am trying to make my son a spelling quiz.
I want to enter his weekly words in mysql with id, word, and weekNo fields
I am using a js text to speech to say the word, and he types it into a textbox. After he submits it there is a function to check if it is correct, then the next word in the mysql row is spoken.
I am getting the next row with...

```<code>     $.ajax({
       type: "POST",
       url: "getNext.php",
       data: "count=" + $number,
       success: function(results){
         $('#results').append(results);
       }
     });
</code>```

getNext.php

```<code>    $result = mysql_query("SELECT * FROM spelling LIMIT
    {$_POST['count']},1");
    while($row = mysql_fetch_array($result))
    {
    echo "<div class='result'>".$row['word'] ."</div>";
    }
</code>```

On the index.php I can display $row['word'] one by one on submit with

```<code>    <div id='results'></div>
</code>```

My problem is I don't know how to get the value from the ajax call into the TTS, everything I try it says "object HTMLDivElement"

Here is the line where I need to get the ajax value...

```<code>    var message = new SpeechSynthesisUtterance(AJAX.VALUE.HERE);
</code>```

答:
According to my guess, you are getting the response from ajax that is an html tag with id="result". You may get the actual value by  ajaxResponse.innerText

In other way, if you are getting output as 'object HTMLDivElement' then that is a div element, and it has property innerText to access its value
so final code would be

var message = new SpeechSynthesisUtterance(AJAX.VALUE.HERE.innertText);

Title: get value of [object HTMLDivElement]

Body:
I am trying to make my son a spelling quiz.
I want to enter his weekly words in mysql with id, word, and weekNo fields
I am using a js text to speech to say the word, and he types it into a textbox. After he submits it there is a function to check if it is correct, then the next word in the mysql row is spoken.
I am getting the next row with...

     $.ajax({
       type: "POST",
       url: "getNext.php",
       data: "count=" + $number,
       success: function(results){
         $('#results').append(results);
       }
     });

getNext.php

    $result = mysql_query("SELECT * FROM spelling LIMIT
    {$_POST['count']},1");
    while($row = mysql_fetch_array($result))
    {
    echo "
".$row['word'] ."
";
    }

On the index.php I can display $row['word'] one by one on submit with

My problem is I don't know how to get the value from the ajax call into the TTS, everything I try it says "object HTMLDivElement"

Here is the line where I need to get the ajax value...

    var message = new SpeechSynthesisUtterance(AJAX.VALUE.HERE);


问:
Maintain object references through Serialize/Deserialize
When serializing, I would like to serialize an object only once, then any references to that object should be serialized as a reference to the object. This is because, when I later deserialize the objects, I would like to maintain those references. To illustrate my goal, the code below should output "After Serialization: true".</p>

```<code>class Program
{
    static void Main(string[] args)
    {
        MyObject obj = new MyObject() { Name = "obj" };
        MyObject[] myObjs = new MyObject[]
        {
            obj, obj
        };

        Console.WriteLine("Object Refs Equal?");
        Console.WriteLine(string.Format("Before Serialization: {0}",
            object.ReferenceEquals(myObjs[0], myObjs[1])));

        XmlSerializer toXml = new XmlSerializer(typeof(MyObject[]));
        using (FileStream toFile = File.Create(@"C:\foo.xml"))
        {
            toXml.Serialize(toFile, myObjs);
        }

        XmlSerializer fromXml = new XmlSerializer(typeof(MyObject[]));
        using (FileStream fromFile = File.OpenRead(@"C:\foo.xml"))
        {
            MyObject[] deserialized = (MyObject[])fromXml.Deserialize(fromFile);

            Console.WriteLine(string.Format("After Serialization: {0}",
            object.ReferenceEquals(deserialized[0], deserialized[1])));
        }

        Console.ReadLine();
    }
}

[Serializable]
public class MyObject
{
    public string Name { get; set; }
}
</code>```

答: If you're using .NET 3 or later, you should use the DataContractSerializer and set PreserveObjectReferences to true.

OwnerDisplayName: CodeChef

ContentLicense: CC BY-SA 2.5

Body:
When serializing, I would like to serialize an object only once, then any references to that object should be serialized as a reference to the object. This is because, when I later deserialize the objects, I would like to maintain those references. To illustrate my goal, the code below should output "After Serialization: true".

class Program
{
    static void Main(string[] args)
    {
        MyObject obj = new MyObject() { Name = "obj" };
        MyObject[] myObjs = new MyObject[]
        {
            obj, obj
        };

        Console.WriteLine("Object Refs Equal?");
        Console.WriteLine(string.Format("Before Serialization: {0}",
            object.ReferenceEquals(myObjs[0], myObjs[1])));

        XmlSerializer toXml = new XmlSerializer(typeof(MyObject[]));
        using (FileStream toFile = File.Create(@"C:\foo.xml"))
        {
            toXml.Serialize(toFile, myObjs);
        }

        XmlSerializer fromXml = new XmlSerializer(typeof(MyObject[]));
        using (FileStream fromFile = File.OpenRead(@"C:\foo.xml"))
        {
            MyObject[] deserialized = (MyObject[])fromXml.Deserialize(fromFile);

            Console.WriteLine(string.Format("After Serialization: {0}",
            object.ReferenceEquals(deserialized[0], deserialized[1])));
        }

        Console.ReadLine();
    }
}

[Serializable]
public class MyObject
{
    public string Name { get; set; }
}

OwnerDisplayName: Kent Boogaart


问:
Problems with file.path with csv import via sidekiq on heroku
I am using a background job in order to import user data from a csv file into my datase. First I did this "hard" in my User model by simply calling a method in my User model and by passing the file path which is transmitted via a form file_field:

```<code>User.import_csv(params[:file].path)
</code>```

Worked well locally and on production (heroku).

Now when it comes to huge CSV files, I understood that I need a job to perform this import in the background. I am familiar with redis and sidekiq so the job was built quickly.

```<code>CsvImportJob.perform_async(URI.parse(params[:file].path))
</code>```

and in my worker:

```<code>def perform(file_path)

  User.import_csv(file_path)

end
</code>```

Well, that also works perfect locally but as soon as I hit this on production, I see the following error in my log:

```<code>» 10 Aug 2015 13:56:26.596 2015-08-10 11:56:25.987726+00:00 app worker.1 - - 3 TID-oqvt6v1d4 ERROR: Actor crashed!
» 10 Aug 2015 13:56:26.596 2015-08-10 11:56:25.987728+00:00 app worker.1 - - Errno::ENOENT: No such file or directory @ rb_sysopen - /tmp/RackMultipart20150810-6-14u804c.csv
» 10 Aug 2015 13:56:26.596 2015-08-10 11:56:25.987730+00:00 app worker.1 - - /app/vendor/ruby-2.2.2/lib/ruby/2.2.0/csv.rb:1256:in `initialize'
</code>```

This is meant to be the file_path variable.
Somehow heroku is not able to find the file when I pass it to a sidekiq job. When I do this without sidekiq, it works.

I don't really know how to tackle this issue so any help is appreciated.

答:
You can't pass a file object to the perform method.

The fix is to massage the data beforehand and pass in the parameters you need directly.

Something like...

```<code>def import_csv(file)
  CSV.foreach(file.path, headers: true) do |row|
    new_user = { email: row[0], password: row[1] }
    CsvImportJob.perform_async(new_user)
  end
end
</code>```

Note: you'd call CsvImportJob.perform_later for Sidekiq with ActiveJob and Rails 5.

Body:
I am using a background job in order to import user data from a csv file into my datase. First I did this "hard" in my User model by simply calling a method in my User model and by passing the file path which is transmitted via a form file_field:

User.import_csv(params[:file].path)

Worked well locally and on production (heroku).

Now when it comes to huge CSV files, I understood that I need a job to perform this import in the background. I am familiar with redis and sidekiq so the job was built quickly.

CsvImportJob.perform_async(URI.parse(params[:file].path))

and in my worker:

def perform(file_path)

  User.import_csv(file_path)

end

Well, that also works perfect locally but as soon as I hit this on production, I see the following error in my log:

» 10 Aug 2015 13:56:26.596 2015-08-10 11:56:25.987726+00:00 app worker.1 - - 3 TID-oqvt6v1d4 ERROR: Actor crashed!
» 10 Aug 2015 13:56:26.596 2015-08-10 11:56:25.987728+00:00 app worker.1 - - Errno::ENOENT: No such file or directory @ rb_sysopen - /tmp/RackMultipart20150810-6-14u804c.csv
» 10 Aug 2015 13:56:26.596 2015-08-10 11:56:25.987730+00:00 app worker.1 - - /app/vendor/ruby-2.2.2/lib/ruby/2.2.0/csv.rb:1256:in `initialize'

This is meant to be the file_path variable.
Somehow heroku is not able to find the file when I pass it to a sidekiq job. When I do this without sidekiq, it works.

I don't really know how to tackle this issue so any help is appreciated.

Body:
You can't pass a file object to the perform method.

The fix is to massage the data beforehand and pass in the parameters you need directly.

Something like...

def import_csv(file)
  CSV.foreach(file.path, headers: true) do |row|
    new_user = { email: row[0], password: row[1] }
    CsvImportJob.perform_async(new_user)
  end
end

Note: you'd call CsvImportJob.perform_later for Sidekiq with ActiveJob and Rails 5.


问:
Aligning a text and line parallel

There are 4 div's which has text and a line. The text will be coming from the service call and it may vary. The issue is that the line is not properly displayed it is of different length.The main condition is
1)All the line should end at the same point.
2)The line should be of 30px right from the margin and
3)The gap between the text and line should be 12px.

.about{
    display: inline-block;
}
hr{
  display:inline-block;
  width:200px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>

<div class="about">Chapter</div><hr/></div>
<div>
<div class="about">Learning Objectives</div><hr/></div>
<div>
<div class="about">Pages</div><hr/></div>
<div>
<div class="about">Sections</div><hr/></div></code>```

I tried with min,max-width but unable find a solution.Can anyone give a better solution?

答:
Make some changes to your CSS as:

```<code>.about {
  display: inline-block;
  vertical-align: top;
  margin-right: 12px;
}
hr{
  display:inline-block;
  width:200px;
  margin-bottom:0;
}
</code>```

.about {
  display: inline-block;
  margin-right:12px;
  vertical-align: top;
}
hr{
  display:inline-block;
  width:200px;
  margin-bottom:0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <div class="about">Chapter</div><hr/>
</div>
<div>
  <div class="about">Learning Objectives</div><hr/>
</div>
<div>
  <div class="about">Pages</div><hr/>
</div>
<div>
  <div class="about">hhhhhhhhhhhhhhh</div><hr/>
</div></code>```

Title: Aligning a text and line parallel

Body:
There are 4 div's which has text and a line. The text will be coming from the service call and it may vary. The issue is that the line is not properly displayed it is of different length.The main condition is
1)All the line should end at the same point.
2)The line should be of 30px right from the margin and
3)The gap between the text and line should be 12px.

.about{
    display: inline-block;
}
hr{
  display:inline-block;
  width:200px;
}

Chapter

Learning Objectives

Pages

Sections

I tried with min,max-width but unable find a solution.Can anyone give a better solution?

Body:
Make some changes to your CSS as:

.about {
  display: inline-block;
  vertical-align: top;
  margin-right: 12px;
}
hr{
  display:inline-block;
  width:200px;
  margin-bottom:0;
}

.about {
  display: inline-block;
  margin-right:12px;
  vertical-align: top;
}
hr{
  display:inline-block;
  width:200px;
  margin-bottom:0;
}

<div>
  <div class="about">Chapter</div><hr/>
</div>
<div>
  <div class="about">Learning Objectives</div><hr/>
</div>
<div>
  <div class="about">Pages</div><hr/>
</div>
<div>
  <div class="about">hhhhhhhhhhhhhhh</div><hr/>
</div>


问:
Updated Android Studio to 3.0 and getting this issue
```<code>Error:Execution failed for task ':App:mergeDebugResources'.
    > There were multiple failures while executing work items
       > A failure occurred while executing com.android.build.gradle.tasks.MergeResources$FileGenerationWorkAction
          > Error while processing /media/nikhilesh/App/src/main/res/drawable/ic_add_black_24dp.xml : Can't process attribute android:fillColor="@color/green": references to other resources are not supported by build-time PNG generation. See http://developer.android.com/tools/help/vector-asset-studio.html for details.
</code>```

How can we solve this?

答:
You just need to add the following line inside your default config of your app
  build.gradle:

```<code>defaultConfig{
       vectorDrawables.useSupportLibrary = true
    }
</code>```

Body:
Error:Execution failed for task ':App:mergeDebugResources'.
    > There were multiple failures while executing work items
       > A failure occurred while executing com.android.build.gradle.tasks.MergeResources$FileGenerationWorkAction
          > Error while processing /media/nikhilesh/App/src/main/res/drawable/ic_add_black_24dp.xml : Can't process attribute android:fillColor="@color/green": references to other resources are not supported by build-time PNG generation. See http://developer.android.com/tools/help/vector-asset-studio.html for details.

How can we solve this?

Body:
You just need to add the following line inside your default config of your app
  build.gradle:

defaultConfig{
       vectorDrawables.useSupportLibrary = true
    }


问:
PHP/Javascript - Changing button image and making database calls onClick()?
I have a button on a page. The button is an image sprite, and it choose ADD in green. I want the user to be able to click this button, and then do a few things:

1) That button makes a call to add an item to my MySQL database, without reloading the page. (I think this needs AJAX.)

2) The button background image sprite changes such that it now says REMOVE in red.

I don't understand how to do this. I'd greatly appreciate a basic walk through on how to do it.

答:
Have a look at this page that i created to demonstrate css sprites.

I call a function on click of the button that changes the image of the button.
You can call a function that does an ajax call inside this function.(Try looking at the source)

Take a look here to learn about ajax and database related stuff.


问:
How to customizing django.contrib.auth.views.login form
My url is

```<code>`url(r'^login/', 'django.contrib.auth.views.login'),`
</code>```

In my login.html template I'm using

```<code>  <form method="post" action=".">
    {% csrf_token %}

    <p>
      <label for="id_username">Username:</label>
      {{ form.username }}
    </p>
    <p>
      <label for="id_password">Password:</label>
      {{ form.password }}
    </p>
    {% if next %}
      <input type="hidden" name="next" value="{{ next }}" />
    {% else %}
      <input type="hidden" name="next" value="/" />
    {% endif %}
    <input type="submit" value="Login"/>
  </form>
</code>```

Now I want use placeholder instead of label. How can I do this. and also want a customize look and feels with bootstrap. Please help how can I do this.

答:
This can be easily done in template using django package widget_tweaks.

So your code looks like:

```<code><form>
  <div class="form-group">
    {% render_field form.username placeholder="<your text>" %}
  </div>
  <div class="form-group">
    {% render_field form.password placeholder="<your text>" %}
  </div>
  <button type="submit" class="btn btn-default">Submit</button>
</form>
</code>```

For more refer the page https://pypi.python.org/pypi/django-widget-tweaks

Body:
My url is

`url(r'^login/', 'django.contrib.auth.views.login'),`

In my login.html template I'm using

  <form method="post" action=".">
    {% csrf_token %}

      Username:
      {{ form.username }}

      Password:
      {{ form.password }}

    {% if next %}
      <input type="hidden" name="next" value="{{ next }}" />
    {% else %}
      <input type="hidden" name="next" value="/" />
    {% endif %}
    <input type="submit" value="Login"/>
  </form>

Now I want use placeholder instead of label. How can I do this. and also want a customize look and feels with bootstrap. Please help how can I do this.

Body:
This can be easily done in template using django package widget_tweaks.

So your code looks like:

<form>
  <div class="form-group">
    {% render_field form.username placeholder="<your text>" %}
  </div>
  <div class="form-group">
    {% render_field form.password placeholder="<your text>" %}
  </div>
  <button type="submit" class="btn btn-default">Submit</button>
</form>

For more refer the page https://pypi.python.org/pypi/django-widget-tweaks


问:
nodejs/express/busboy - saving uploaded json data into database
I am using bodyboy
https://github.com/mscdex/connect-busboy
upload functionality. Basically I do not need to save files, its just user uploads a file and I want to save it into my database.

So to be precise, if anyone can tell me how to console contents of file uploaded

```<code>req.busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
            console.log(fieldname)
            console.log(file)
            console.log(filename)
            console.log('readin file')
        });
</code>```

Here how can I read the file, or even if I need anymore step?

答:
Actually connect-busboy is a connect middleware for busboy.

You can use following sample code ,

```<code>    req.busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
          console.log('File [' + fieldname + ']: filename: ' + filename + ', encoding: ' + encoding + ', mimetype: ' + mimetype);
          file.on('data', function(data) {
            console.log('File [' + fieldname + '] got ' + data.length + ' bytes');
          });
          file.on('end', function() {
            console.log('File [' + fieldname + '] Finished');
          });
    });
</code>```

If you want to read your stream then you need to play with your stream or please try to use following way

```<code>   req.busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
               var buffer = '';
               console.log('File [' + fieldname + ']: filename: ' + filename + ', encoding: ' + encoding + ', mimetype: ' + mimetype);
               file.on('data', function(data) {
                  buffer += data;
                 console.log('File [' + fieldname + '] got ' + data.length + ' bytes');
               });
               file.on('end', function() {
                 console.log('File [' + fieldname + '] Finished');
                 var val = JSON.parse(buffer);
                // use `val` here ...
               }).setEncoding('utf8');
         });
</code>```

And make sure you have used proper headers in your request otherwise please check sample test case code to here.

Hopes this will help you !

Body:
I am using bodyboy
https://github.com/mscdex/connect-busboy
upload functionality. Basically I do not need to save files, its just user uploads a file and I want to save it into my database.

So to be precise, if anyone can tell me how to console contents of file uploaded

req.busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
            console.log(fieldname)
            console.log(file)
            console.log(filename)
            console.log('readin file')
        });

Here how can I read the file, or even if I need anymore step?

Body:
Actually connect-busboy is a connect middleware for busboy.

You can use following sample code ,

    req.busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
          console.log('File [' + fieldname + ']: filename: ' + filename + ', encoding: ' + encoding + ', mimetype: ' + mimetype);
          file.on('data', function(data) {
            console.log('File [' + fieldname + '] got ' + data.length + ' bytes');
          });
          file.on('end', function() {
            console.log('File [' + fieldname + '] Finished');
          });
    });

If you want to read your stream then you need to play with your stream or please try to use following way

   req.busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
               var buffer = '';
               console.log('File [' + fieldname + ']: filename: ' + filename + ', encoding: ' + encoding + ', mimetype: ' + mimetype);
               file.on('data', function(data) {
                  buffer += data;
                 console.log('File [' + fieldname + '] got ' + data.length + ' bytes');
               });
               file.on('end', function() {
                 console.log('File [' + fieldname + '] Finished');
                 var val = JSON.parse(buffer);
                // use `val` here ...
               }).setEncoding('utf8');
         });

And make sure you have used proper headers in your request otherwise please check sample test case code to here.

Hopes this will help you !


问:
position inside getview is getting changed in onCheckedChaneListener which is inside Adapter
I have Created a Listview with CustomAdapter which is having radio button in each row [ Single choice ] bt its resulting wrong after adapter has been setted</p>

```<code>  if (arr_data.get(position).isdefaultCurrency())   holder.radio_currency.setChecked(true);
  } else {
        holder.radio_currency.setChecked(false);
    }
    holder.radio_currency.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {

                for (int k = 0; k < arr_data.size(); k++) {
                    if (k == position) {
                        arr_data.get(k).setIsdefaultCurrency(true);
                    } else {
                        arr_data.get(k).setIsdefaultCurrency(false);
                    }
                }
            } else {
                arr_data.get(position).setIsdefaultCurrency(false);
            }
            notifyDataSetChanged();
        }
    });
</code>```

答:
My Issue was resolved simply by Using OnClickListener instead of OnCheckedChangeListener.</p>

```<code>  holder.radio_currency.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            for (int k = 0; k < arr_data.size(); k++) {
                if (k == position) {
                    arr_data.get(k).setIsdefaultCurrency(true);
                } else {
                    arr_data.get(k).setIsdefaultCurrency(false);
                }
            }
            notifyDataSetChanged();
        }
    });
</code>```

Body:
I have Created a Listview with CustomAdapter which is having radio button in each row [ Single choice ] bt its resulting wrong after adapter has been setted

  if (arr_data.get(position).isdefaultCurrency())   holder.radio_currency.setChecked(true);
  } else {
        holder.radio_currency.setChecked(false);
    }
    holder.radio_currency.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {

                for (int k = 0; k < arr_data.size(); k++) {
                    if (k == position) {
                        arr_data.get(k).setIsdefaultCurrency(true);
                    } else {
                        arr_data.get(k).setIsdefaultCurrency(false);
                    }
                }
            } else {
                arr_data.get(position).setIsdefaultCurrency(false);
            }
            notifyDataSetChanged();
        }
    });

Body:
My Issue was resolved simply by Using OnClickListener instead of OnCheckedChangeListener.

  holder.radio_currency.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            for (int k = 0; k < arr_data.size(); k++) {
                if (k == position) {
                    arr_data.get(k).setIsdefaultCurrency(true);
                } else {
                    arr_data.get(k).setIsdefaultCurrency(false);
                }
            }
            notifyDataSetChanged();
        }
    });


问:
Increases Time of Splash Screen in Swift 4
I am working in a Swift 4 project and I had set the LaunchScreen.storyboard. I want to increase the display time of it.

I have seen solutions over here but they are in Objective-C, but I want a solution in Swift. Does anybody know how can I achieve this.

答:
It is possible if you make a fake splash screen that you will have full ability to make any animation and sound effect. A fake splash screen is just a UIView or UIViewController that shown after app launch.

For example, add a real splash screen with the same background color with your fake splash screen. On the fake splash screen, you can make it show as long as you want.


问:
I am busy writing a C# IBM MQ Client app and keep getting "Exception: The type initializer for 'IBM.WMQ.Nmqi.UnmanagedNmqiMQ' threw an exception."
I have got the MQ Client running successfully and the messages are available using it.

WE have set up the necessary Environment variables:
MQCHLLIB and MQCHLTAB and MQSSLKEYR.

The .TAB file is in the right folder.
However when I execute the following code:

```<code>private static bool ConnectMq()
    {
        try
        {
            queueManager = new MQQueueManager("ECG_MBTST_QM", Init(false));
            queueManager.Connect();
            if (queueManager.IsConnected)
            {
                Console.WriteLine("Connected...");
            }
            return true;
        }
        catch (MQException exp)
        {
            Console.WriteLine("Exception Message: " + exp.Message);
        }
        catch (Exception exp)
        {
            Console.WriteLine("Exception: " + exp.Message);
        }
        return false;
    }
    private static Hashtable Init()
    {
        Hashtable properties;
        properties = new Hashtable
            {
                {MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_CLIENT}
            };

        return properties;
    }
</code>```

I get the error message as described.
I have no choice but to use a CCDT file as that is what the server host has specified.
I believe the server is v7 and I am referencing the v8 WMQ libraries.
In theory this should work.

I have tried with using the standard set of properties as well (values have been altered for security purposes):

```<code>properties = new Hashtable
            {
                {MQC.TRANSPORT_PROPERTY, "TCP"},
                {MQC.CHANNEL_PROPERTY, "Channel"},
                {MQC.CONNECTION_NAME_PROPERTY, "IBM_MQ_Conn"},
                {MQC.PORT_PROPERTY, "1414"},
                {MQC.HOST_NAME_PROPERTY, "IP Address"},
                {MQC.SSL_CIPHER_SPEC_PROPERTY, "TLS_RSA_WITH_AES_128_CBC_SHA"}
            };
</code>```

But when i use the above properties I get a 2538 error - Host not available.
Is there something I am missing with regards to how to use the CCDT file and C# together?

Thanks in advance.

edit - as requested by JoshMC

This is the latest entry from the AMQERR01.LOG file:

```<code>1/18/2017 1:51:05 AM - Process(3272.1) User(andrewhuntley) Program( MQ app.exe)
AMQ9202: Remote host '192.168.150.102' not available, retry later.

EXPLANATION:
The attempt to allocate a conversation using TCP/IP to host '192.168.150.102'
for channel  (Exception) was not successful. However the error may be a
transitory one and it may be possible to successfully allocate a TCP/IP
conversation later.

 In some cases the remote host cannot be determined and so is shown as '????'.
ACTION:
Try the connection again later. If the failure persists, record the error
values and contact your systems administrator. The return code from TCP/IP is 0
(X'0'). The reason for the failure may be that this host cannot reach the
destination host. It may also be possible that the listening program at host
'192.168.150.102' was not running.  If this is the case, perform the relevant
operations to start the TCP/IP listening program, and try again.
----- MQTCPConnection.cs : 357 ------------------------------------------------
</code>```

Please note that the server is up and running and accessible as I can connect to it using the installed IBM client.

答:
Saw this question late.

The MQ .NET client available at NuGet is not from IBM. It clearly mentions "Unofficial".

It can be used only in .NET managed mode, not in bindings or .NET Un-managed client mode as it does not have other dependent libraries.

The IBM.WMQ.Nmqi.UnmanagedNmqiMQ exception is because MQ C client libraries are not present. You can use MQC.TRANSPORT_MQSERIES_MANAGED value for MQC.TRANSPORT_PROPERTY to resolve the exception or "install" the MQ Redistributable Client if you want to use MQC.TRANSPORT_MQSERIES_CLIENT option

Body:
I have got the MQ Client running successfully and the messages are available using it.

WE have set up the necessary Environment variables:
MQCHLLIB and MQCHLTAB and MQSSLKEYR.

The .TAB file is in the right folder.
However when I execute the following code:

private static bool ConnectMq()
    {
        try
        {
            queueManager = new MQQueueManager("ECG_MBTST_QM", Init(false));
            queueManager.Connect();
            if (queueManager.IsConnected)
            {
                Console.WriteLine("Connected...");
            }
            return true;
        }
        catch (MQException exp)
        {
            Console.WriteLine("Exception Message: " + exp.Message);
        }
        catch (Exception exp)
        {
            Console.WriteLine("Exception: " + exp.Message);
        }
        return false;
    }
    private static Hashtable Init()
    {
        Hashtable properties;
        properties = new Hashtable
            {
                {MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_CLIENT}
            };

        return properties;
    }

I get the error message as described.
I have no choice but to use a CCDT file as that is what the server host has specified.
I believe the server is v7 and I am referencing the v8 WMQ libraries.
In theory this should work.

I have tried with using the standard set of properties as well (values have been altered for security purposes):

properties = new Hashtable
            {
                {MQC.TRANSPORT_PROPERTY, "TCP"},
                {MQC.CHANNEL_PROPERTY, "Channel"},
                {MQC.CONNECTION_NAME_PROPERTY, "IBM_MQ_Conn"},
                {MQC.PORT_PROPERTY, "1414"},
                {MQC.HOST_NAME_PROPERTY, "IP Address"},
                {MQC.SSL_CIPHER_SPEC_PROPERTY, "TLS_RSA_WITH_AES_128_CBC_SHA"}
            };

But when i use the above properties I get a 2538 error - Host not available.
Is there something I am missing with regards to how to use the CCDT file and C# together?

Thanks in advance.

edit - as requested by JoshMC

This is the latest entry from the AMQERR01.LOG file:

1/18/2017 1:51:05 AM - Process(3272.1) User(andrewhuntley) Program( MQ app.exe)
AMQ9202: Remote host '192.168.150.102' not available, retry later.

EXPLANATION:
The attempt to allocate a conversation using TCP/IP to host '192.168.150.102'
for channel  (Exception) was not successful. However the error may be a
transitory one and it may be possible to successfully allocate a TCP/IP
conversation later.

 In some cases the remote host cannot be determined and so is shown as '????'.
ACTION:
Try the connection again later. If the failure persists, record the error
values and contact your systems administrator. The return code from TCP/IP is 0
(X'0'). The reason for the failure may be that this host cannot reach the
destination host. It may also be possible that the listening program at host
'192.168.150.102' was not running.  If this is the case, perform the relevant
operations to start the TCP/IP listening program, and try again.
----- MQTCPConnection.cs : 357 ------------------------------------------------

Please note that the server is up and running and accessible as I can connect to it using the installed IBM client.


问:
IllegalStateException: Content has been consumed
I got struck because of IllegalStateException in the following code. Can anybody please help me? Code:

```<code>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.telephony.gsm.GsmCellLocation;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Login extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        Button bt = (Button) findViewById(R.id.logbt);
        final EditText user = (EditText) findViewById(R.id.loguser);
        final EditText pw = (EditText) findViewById(R.id.logpw);
        bt.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (user.getText().toString() != "" && pw.getText().toString() != "") {
                    Thread t = new Thread() {
                        public void run() {
                            try {
                                HttpClient client = new DefaultHttpClient();
                                String postURL = "http://surfkid.redio.de/login";
                                HttpPost post = new HttpPost(postURL);
                                ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
                                params.add(new BasicNameValuePair("username", user.getText().toString()));
                                params.add(new BasicNameValuePair("password", md5(pw.getText().toString())));
                                UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params, HTTP.UTF_8);
                                post.setEntity(ent);
                                HttpResponse responsePOST = client.execute(post);
                                HttpEntity resEntity = responsePOST.getEntity();
                                final JSONObject jObject = new JSONObject(EntityUtils.toString(resEntity));
                                Log.e("XXX", EntityUtils.toString(resEntity));
                            } catch (Exception e) {
                                Log.e("XXX", e.toString());
                            }
                        }
                    };
                    t.start();
                    // Log.e("XXX",s);
                }
            }
        });
    }

    private String md5(String in) {
        MessageDigest digest;
        try {
            digest = MessageDigest.getInstance("MD5");
            digest.reset();
            digest.update(in.getBytes());
            byte[] a = digest.digest();
            int len = a.length;
            StringBuilder sb = new StringBuilder(len << 1);
            for (int i = 0; i < len; i++) {
                sb.append(Character.forDigit((a[i] & 0xf0) >> 4, 16));
                sb.append(Character.forDigit(a[i] & 0x0f, 16));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
}
</code>```

Logcat message:

01-18 18:39:53.383: ERROR/XXX(7113):
  java.lang.IllegalStateException:
  Content has been consumed

答:
You can consume Content only at once from an Entity

in the line :

```<code>final JSONObject jObject = new JSONObject(EntityUtils.toString(resEntity));
</code>```

you have consumed content and again you are using the same at here:

```<code>Log.e("XXX",EntityUtils.toString(resEntity));
</code>```

That why it is causing IllegalStateException: Content has been consumed

So the solution is here:

```<code>String _response=EntityUtils.toString(resEntity); // content will be consume only once
final JSONObject jObject=new JSONObject(_response);
Log.e("XXX",_response);
</code>```

Body:
I got struck because of IllegalStateException in the following code. Can anybody please help me? Code:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.telephony.gsm.GsmCellLocation;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Login extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        Button bt = (Button) findViewById(R.id.logbt);
        final EditText user = (EditText) findViewById(R.id.loguser);
        final EditText pw = (EditText) findViewById(R.id.logpw);
        bt.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (user.getText().toString() != "" && pw.getText().toString() != "") {
                    Thread t = new Thread() {
                        public void run() {
                            try {
                                HttpClient client = new DefaultHttpClient();
                                String postURL = "http://surfkid.redio.de/login";
                                HttpPost post = new HttpPost(postURL);
                                ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
                                params.add(new BasicNameValuePair("username", user.getText().toString()));
                                params.add(new BasicNameValuePair("password", md5(pw.getText().toString())));
                                UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params, HTTP.UTF_8);
                                post.setEntity(ent);
                                HttpResponse responsePOST = client.execute(post);
                                HttpEntity resEntity = responsePOST.getEntity();
                                final JSONObject jObject = new JSONObject(EntityUtils.toString(resEntity));
                                Log.e("XXX", EntityUtils.toString(resEntity));
                            } catch (Exception e) {
                                Log.e("XXX", e.toString());
                            }
                        }
                    };
                    t.start();
                    // Log.e("XXX",s);
                }
            }
        });
    }

    private String md5(String in) {
        MessageDigest digest;
        try {
            digest = MessageDigest.getInstance("MD5");
            digest.reset();
            digest.update(in.getBytes());
            byte[] a = digest.digest();
            int len = a.length;
            StringBuilder sb = new StringBuilder(len << 1);
            for (int i = 0; i < len; i++) {
                sb.append(Character.forDigit((a[i] & 0xf0) >> 4, 16));
                sb.append(Character.forDigit(a[i] & 0x0f, 16));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
}

Logcat message:

01-18 18:39:53.383: ERROR/XXX(7113):
  java.lang.IllegalStateException:
  Content has been consumed

Body:
You can consume Content only at once from an Entity

in the line :

final JSONObject jObject = new JSONObject(EntityUtils.toString(resEntity));

you have consumed content and again you are using the same at here:

Log.e("XXX",EntityUtils.toString(resEntity));

That why it is causing IllegalStateException: Content has been consumed

So the solution is here:

String _response=EntityUtils.toString(resEntity); // content will be consume only once
final JSONObject jObject=new JSONObject(_response);
Log.e("XXX",_response);


问:
Centering fabricjs object onclick?
I found another question with some code that worked for an earlier version of fabricjs but I have been struggling to make it work with 1.7.20. What am I doing wrong here? If you go to this fiddle you'll see it works when you toggle to 1.4 it works but anything further on breaks it.

```<code>var canvas = new fabric.Canvas('c');
var text = new fabric.IText('Text', {
  left: 10,
  top: 10,
});
canvas.add(text);

document.getElementById('center').addEventListener('click', function(e) {
  var obj = canvas.getActiveObject();
  var leftcenter = canvas.width / 2
  var halfleft = obj.currentWidth / 2;
  obj.set("left", leftcenter - halfleft);
  obj.set("top", obj.get('top'));
  obj.setCoords();
  canvas.renderAll();
});
</code>```

```<code><button id="center">Fit To left center</button>
</code>```

Thanks in advance.

答:
You need to use width instead of currentWidth as there is no such property available in fabricjs. May be it was there in earlier versions and got removed later on.

var halfleft = (obj.width * obj.scaleX) / 2;

Updated fiddle - http://jsfiddle.net/759FV/148/

Title: Centering fabricjs object onclick?

Body:
I found another question with some code that worked for an earlier version of fabricjs but I have been struggling to make it work with 1.7.20. What am I doing wrong here? If you go to this fiddle you'll see it works when you toggle to 1.4 it works but anything further on breaks it.

var canvas = new fabric.Canvas('c');
var text = new fabric.IText('Text', {
  left: 10,
  top: 10,
});
canvas.add(text);

document.getElementById('center').addEventListener('click', function(e) {
  var obj = canvas.getActiveObject();
  var leftcenter = canvas.width / 2
  var halfleft = obj.currentWidth / 2;
  obj.set("left", leftcenter - halfleft);
  obj.set("top", obj.get('top'));
  obj.setCoords();
  canvas.renderAll();
});

<button id="center">Fit To left center</button>

Thanks in advance.


问:
correct way to start/stop postgres database pg_ctl or service postgres
I would like to know correct way of starting/stopping postgres database.
There are two ways

pg_ctl start/stop

service postgresql start/stop

I would like to know how they are different from each other, which one should I use? are their any pros/cons.

I check online but didnt get satisfactory answer.

Thanks in advance

答:
If you are using Mac with brew

To start:

```<code>brew services start postgresql
</code>```

To stop:

```<code>brew services stop postgresql
</code>```

Using pg_ctl

To start:

```<code>pg_ctl start -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log
</code>```

To stop:

```<code>pg_ctl stop -D /usr/local/var/postgres -m smart
</code>```

See: https://www.postgresql.org/docs/current/app-pg-ctl.html

ContentLicense: CC BY-SA 4.0

Body:
If you are using Mac with brew

To start:

brew services start postgresql

To stop:

brew services stop postgresql

Using pg_ctl

To start:

pg_ctl start -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log

To stop:

pg_ctl stop -D /usr/local/var/postgres -m smart

See: https://www.postgresql.org/docs/current/app-pg-ctl.html


Title: Sorting a list of dates in ascending order, without concerning the other element

Body:
This is the list:

[['2017-11-09', 21], ['2017-11-14', 39], ['2017-11-13', 43], ['2017-11-10', 37]]

This has to be the output:

[['2017-11-09', 21], ['2017-11-10', 37], ['2017-11-13', 43], ['2017-11-14', 39]]

How do I do this in Python?

Body:
You can use this too

list = [['2017-11-09', 21], ['2017-11-14', 39], ['2017-11-13', 43], ['2017-11-10', 37]]
list.sort()
print(list)


答:
Try this.

.about {
  float: left;
}
hr {
  width: auto;
  margin-left: 30px;
}
.test {
  overflow: hidden;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="test">
  <div class="about">Chapter</div>
  <hr/>
</div>
<div class="test">
  <div class="about">Learning Objectives</div>
  <hr/>
</div>
<div class="test">
  <div class="about">Pages</div>
  <hr/>
</div>
<div class="test">
  <div class="about">hhhhhhhhhhhhhhh</div>
  <hr/>
</div></code>```

Title: Aligning a text and line parallel

Body:
There are 4 div's which has text and a line. The text will be coming from the service call and it may vary. The issue is that the line is not properly displayed it is of different length.The main condition is
1)All the line should end at the same point.
2)The line should be of 30px right from the margin and
3)The gap between the text and line should be 12px.

.about{
    display: inline-block;
}
hr{
  display:inline-block;
  width:200px;
}

Chapter

Learning Objectives

Pages

Sections

I tried with min,max-width but unable find a solution.Can anyone give a better solution?

Body:
Try this.

.about {
  float: left;
}
hr {
  width: auto;
  margin-left: 30px;
}
.test {
  overflow: hidden;
}

<div class="test">
  <div class="about">Chapter</div>
  <hr/>
</div>
<div class="test">
  <div class="about">Learning Objectives</div>
  <hr/>
</div>
<div class="test">
  <div class="about">Pages</div>
  <hr/>
</div>
<div class="test">
  <div class="about">hhhhhhhhhhhhhhh</div>
  <hr/>
</div>


问:
javafx make button fill width
i have one button in a borderpane. I want the button to be stretched out horizontally so it fills the entire width.

how can i do that?

答: Just set the maxWidth property of the button to MAX_VALUE.

Title: javafx make button fill width


问:
How to Disable sorting of only one specific column in Data tables?
Suppose i have the table like below :

And I want to disable sorting of Action Column

```<code><!--index.html-->
<table class="table table-striped table-bordered post-list-table" id="table" >
  <thead>
    <tr>
      <th>Title</th>
      <th>Created At</th>
      <th>Action</th>
    </tr>
  </thead>
</table>

<!--Script.js-->
$('#table').DataTable();
</code>```

答:
Try this

```<code>$('#table').dataTable({
    // display everything
    "iDisplayLength": -1,
    "aoColumns":[
        {"bSortable": true},
        {"bSortable": true},
        {"bSortable": false}
    ]
});
</code>```

for reference - https://stackoverflow.com/a/7878609/1982631

Body:
Suppose i have the table like below :

And I want to disable sorting of Action Column

      Title
      Created At
      Action

$('#table').DataTable();

Body:
Try this

$('#table').dataTable({
    // display everything
    "iDisplayLength": -1,
    "aoColumns":[
        {"bSortable": true},
        {"bSortable": true},
        {"bSortable": false}
    ]
});

for reference - https://stackoverflow.com/a/7878609/1982631


问:
Converting binary string to a hexadecimal string JAVA
I want to convert my binary(which is in string) to hexadecimal string also, this is just a program fragment since this program is just a part of another bigger program:

```<code>//the variable name of the binary string is: "binary"
int digitNumber = 1;
    int sum = 0;
    int test = binary.length()%4;
    if(test!=0) {
        binary = padLeft(binary, test);
    }
    for(int i = 0; i < binary.length(); i++){
        if(digitNumber == 1)
            sum+=Integer.parseInt(binary.charAt(i) + "")*8;
        else if(digitNumber == 2)
            sum+=Integer.parseInt(binary.charAt(i) + "")*4;
        else if(digitNumber == 3)
            sum+=Integer.parseInt(binary.charAt(i) + "")*2;
        else if(digitNumber == 4 || i < binary.length()+1){
            sum+=Integer.parseInt(binary.charAt(i) + "")*1;
            digitNumber = 0;
            if(sum < 10)
                System.out.print(sum);
            else if(sum == 10)
                System.out.print("A");
            else if(sum == 11)
                System.out.print("B");
            else if(sum == 12)
                System.out.print("C");
            else if(sum == 13)
                System.out.print("D");
            else if(sum == 14)
                System.out.print("E");
            else if(sum == 15)
                System.out.print("F");
            sum=0;
        }
        digitNumber++;
    }
    public static String padLeft(String s, int n) {
        return String.format("%0$"+n+"s", s);
    }//i added this for padding
</code>```

the problem is that i dont know if the padding works but i am sure that this program return a wrong hexadecimal conversion of the binary string I am trying to do this:

http://www.wikihow.com/Convert-Binary-to-Hexadecimal

PS: I need to implement it(not using any built-in function)

答:
By given binary number 01011011, we will convert it at first to decimal number, each number will be Math.pow() by decrementd length:

01011011 =(0 × 2(7)) + (1 × 2(6)) + (0 × 2(5)) + (1 × 2(4)) + (1 × 2(3)) + (0 × 2(2)) + (1 × 2(1)) + (1 × 2(0))

= (0 × 128) + (1 × 64) + (0 × 32) + (1 × 16) + (1 × 8) + (0 × 4) + (1 × 2) + (1 × 1)

= 0 + 64 + 0 + 16 + 8 + 0 + 2 + 1

= 91 (decimal form of binary number)

Now after get decimal number we have to convert it to hexa-decimal-number.

So, 91 is greater than 16. So, we have to divide by 16.

After dividing by 16, quotient is 5 and remainder is 11.

Remainder is less than 16.

Hexadecimal number of remainder is B.

Quotient is 5 and hexadecimal number of remainder is B.

That is, 91 = 16 × 5 +11 = B

5 = 16 × 0 + 5 = 5

=5B

Implementation:

```<code>String hexValue = binaryToHex(binaryValue);

    //Display result
    System.out.println(hexValue);

private static String binaryToHex(String binary) {
    int decimalValue = 0;
    int length = binary.length() - 1;
    for (int i = 0; i < binary.length(); i++) {
        decimalValue += Integer.parseInt(binary.charAt(i) + "") * Math.pow(2, length);
        length--;
    }
    return decimalToHex(decimalValue);
}
private static String decimalToHex(int decimal){
    String hex = "";
    while (decimal != 0){
        int hexValue = decimal % 16;
        hex = toHexChar(hexValue) + hex;
        decimal = decimal / 16;
    }
    return hex;
}

private static char toHexChar(int hexValue) {
    if (hexValue <= 9 && hexValue >= 0)
        return (char)(hexValue + '0');
    else
        return (char)(hexValue - 10 + 'A');
}
</code>```

Body:
I want to convert my binary(which is in string) to hexadecimal string also, this is just a program fragment since this program is just a part of another bigger program:

//the variable name of the binary string is: "binary"
int digitNumber = 1;
    int sum = 0;
    int test = binary.length()%4;
    if(test!=0) {
        binary = padLeft(binary, test);
    }
    for(int i = 0; i < binary.length(); i++){
        if(digitNumber == 1)
            sum+=Integer.parseInt(binary.charAt(i) + "")*8;
        else if(digitNumber == 2)
            sum+=Integer.parseInt(binary.charAt(i) + "")*4;
        else if(digitNumber == 3)
            sum+=Integer.parseInt(binary.charAt(i) + "")*2;
        else if(digitNumber == 4 || i < binary.length()+1){
            sum+=Integer.parseInt(binary.charAt(i) + "")*1;
            digitNumber = 0;
            if(sum < 10)
                System.out.print(sum);
            else if(sum == 10)
                System.out.print("A");
            else if(sum == 11)
                System.out.print("B");
            else if(sum == 12)
                System.out.print("C");
            else if(sum == 13)
                System.out.print("D");
            else if(sum == 14)
                System.out.print("E");
            else if(sum == 15)
                System.out.print("F");
            sum=0;
        }
        digitNumber++;
    }
    public static String padLeft(String s, int n) {
        return String.format("%0$"+n+"s", s);
    }//i added this for padding

the problem is that i dont know if the padding works but i am sure that this program return a wrong hexadecimal conversion of the binary string I am trying to do this:

http://www.wikihow.com/Convert-Binary-to-Hexadecimal

PS: I need to implement it(not using any built-in function)

Body:
By given binary number 01011011, we will convert it at first to decimal number, each number will be Math.pow() by decrementd length:

01011011 =(0 × 2(7)) + (1 × 2(6)) + (0 × 2(5)) + (1 × 2(4)) + (1 × 2(3)) + (0 × 2(2)) + (1 × 2(1)) + (1 × 2(0))

= (0 × 128) + (1 × 64) + (0 × 32) + (1 × 16) + (1 × 8) + (0 × 4) + (1 × 2) + (1 × 1)

= 0 + 64 + 0 + 16 + 8 + 0 + 2 + 1

= 91 (decimal form of binary number)

Now after get decimal number we have to convert it to hexa-decimal-number.

So, 91 is greater than 16. So, we have to divide by 16.

After dividing by 16, quotient is 5 and remainder is 11.

Remainder is less than 16.

Hexadecimal number of remainder is B.

Quotient is 5 and hexadecimal number of remainder is B.

That is, 91 = 16 × 5 +11 = B

5 = 16 × 0 + 5 = 5

=5B

Implementation:

String hexValue = binaryToHex(binaryValue);

    //Display result
    System.out.println(hexValue);

private static String binaryToHex(String binary) {
    int decimalValue = 0;
    int length = binary.length() - 1;
    for (int i = 0; i < binary.length(); i++) {
        decimalValue += Integer.parseInt(binary.charAt(i) + "") * Math.pow(2, length);
        length--;
    }
    return decimalToHex(decimalValue);
}
private static String decimalToHex(int decimal){
    String hex = "";
    while (decimal != 0){
        int hexValue = decimal % 16;
        hex = toHexChar(hexValue) + hex;
        decimal = decimal / 16;
    }
    return hex;
}

private static char toHexChar(int hexValue) {
    if (hexValue <= 9 && hexValue >= 0)
        return (char)(hexValue + '0');
    else
        return (char)(hexValue - 10 + 'A');
}


问:
Why does a Fortran POINTER require a TARGET?
Why does the Fortran 90 Specification specify (5.2.8) that the TARGET keyword must be used to associate a POINTER to it? Why isn't every type a valid TARGET?

For example,
```
INTEGER, POINTER :: px
INTEGER, TARGET :: x
x = 5
px => x
```
is valid syntax but
```
INTEGER, POINTER :: px
INTEGER :: x
x = 5
px => x
```
is not valid.

Why must this be?

答:
For better compiler optimization. When your code runs on 1K-100K cores speed does matter.

Btw TARGET is not always used. For example in situations when the pointer is being used for allocating memory.

```<code>...
real, pointer :: p(:), x
...
allocate(p(15))
...
x => p(1:5)
...
nullify(x)
deallocate(p)
...
</code>```

Body:
Why does the Fortran 90 Specification specify (5.2.8) that the TARGET keyword must be used to associate a POINTER to it? Why isn't every type a valid TARGET?

For example,

INTEGER, POINTER :: px
INTEGER, TARGET :: x
x = 5
px => x

is valid syntax but

INTEGER, POINTER :: px
INTEGER :: x
x = 5
px => x

is not valid.

Why must this be?

Body:
For better compiler optimization. When your code runs on 1K-100K cores speed does matter.

Btw TARGET is not always used. For example in situations when the pointer is being used for allocating memory.

...
real, pointer :: p(:), x
...
allocate(p(15))
...
x => p(1:5)
...
nullify(x)
deallocate(p)
...


答:
Best approach is make a fake splash screen.

And The hack solution is that, create a thread with time interval,
Add the following code in appDelegate method didFinishLaunchingWithOptions

Do not do this type of approach, because this approach also may lead to rejection from App Store.

```<code>Thread.sleep(forTimeInterval: 3)
</code>```

Title: Increases Time of Splash Screen in Swift 4

Body:
I am working in a Swift 4 project and I had set the LaunchScreen.storyboard. I want to increase the display time of it.

I have seen solutions over here but they are in Objective-C, but I want a solution in Swift. Does anybody know how can I achieve this.

Body:
Best approach is make a fake splash screen.

And The hack solution is that, create a thread with time interval,
Add the following code in appDelegate method didFinishLaunchingWithOptions

Do not do this type of approach, because this approach also may lead to rejection from App Store.

Thread.sleep(forTimeInterval: 3)


问:
Interactive, vertical line annotations on CanvasJS graph
I'm trying to add annotations to my CanvasJS graph in a way similar to dygraphs' functionality( example here) but haven't found a way to. I've seen an example where they replaced a point with an image (here) but it isn't quite the same, as I need the marker between points and to have it's own tooltip. Is there any way to achieve this in CanvasJS?</p>

答:
You can use indexLabels along with indexLabelLineThickness to show annotation but toolTip are shown only for dataPoints.

var chart = new CanvasJS.Chart("chartContainer", {
title: {
 text: "Line Chart with Index-Labels"
},
data: [{
 type: "line",
 indexLabelBackgroundColor: "LightBlue",
 indexLabelLineThickness: 1,
 dataPoints: [
  { x: 10, y: 71 },
  { x: 20, y: 55, indexLabel: "{y}" },
  { x: 30, y: 50 },
  { x: 40, y: 65 },
  { x: 50, y: 95 },
  { x: 60, y: 68, indexLabel: "{y}" },
  { x: 70, y: 28 },
  { x: 80, y: 34, indexLabel: "{y}" },
  { x: 90, y: 14 }
 ]
}]
});

chart.render();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer" style="height: 250px; width: 100%;"></div></code>```

Body:
You can use indexLabels along with indexLabelLineThickness to show annotation but toolTip are shown only for dataPoints.

var chart = new CanvasJS.Chart("chartContainer", {
title: {
 text: "Line Chart with Index-Labels"
},
data: [{
 type: "line",
 indexLabelBackgroundColor: "LightBlue",
 indexLabelLineThickness: 1,
 dataPoints: [
  { x: 10, y: 71 },
  { x: 20, y: 55, indexLabel: "{y}" },
  { x: 30, y: 50 },
  { x: 40, y: 65 },
  { x: 50, y: 95 },
  { x: 60, y: 68, indexLabel: "{y}" },
  { x: 70, y: 28 },
  { x: 80, y: 34, indexLabel: "{y}" },
  { x: 90, y: 14 }
 ]
}]
});

chart.render();

<script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer" style="height: 250px; width: 100%;"></div>


问:
How to "Paste as plain text" by default in Joomla 3.8 TinyMce editor?
As the title says, I need to make this default as users are pasting terribly formatted text to the editor.

I have read similar threads where it says I should add some code to TinyMCE.init section in the file \plugins\editors\tinyMCE\tinymce.php, but there is no such section in this file.

BR,
Martin

答: You will indeed need to set the paste_as_text option to true in your .init. You can read more about the options for the paste plugins here: https://www.tinymce.com/docs/plugins/paste/


问:
Caused by: java.lang.UnsatisfiedLinkError: Cannot load library: load_library[1098]: Library '/system/lib/libhoudini.so' not found
I updated Android Studio to 3.0.0 and Gradle to 3.0.0

After run my app on emulator Genymotion (API 16-19) crashed.

Error:

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
                  java.lang.ExceptionInInitializerError
                      at android.support.v4.app.SupportActivity.<init>(SupportActivity.java:68)
                      at android.support.v4.app.BaseFragmentActivityGingerbread.<init>(BaseFragmentActivityGingerbread.java:37)
                      at android.support.v4.app.BaseFragmentActivityHoneycomb.<init>(BaseFragmentActivityHoneycomb.java:29)
                      at android.support.v4.app.BaseFragmentActivityJB.<init>(BaseFragmentActivityJB.java:30)
                      at android.support.v4.app.FragmentActivity.<init>(FragmentActivity.java:79)
                      at android.support.v7.app.AppCompatActivity.<init>(AppCompatActivity.java:61)
                      at com.myapp.start.BaseActivity.<init>(BaseActivity.java:37)
                      at com.myapp.start.StartActivity.<init>(StartActivity.java:40)
                      at java.lang.Class.newInstanceImpl(Native Method)
                      at java.lang.Class.newInstance(Class.java:1319)
                      at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
                      at android.app.ActivityThread.access$600(ActivityThread.java:130)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
                      at android.os.Handler.dispatchMessage(Handler.java:99)
                      at android.os.Looper.loop(Looper.java:137)
                      at android.app.ActivityThread.main(ActivityThread.java:4745)
                      at java.lang.reflect.Method.invokeNative(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:511)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
                      at dalvik.system.NativeStart.main(Native Method)
                   Caused by: java.lang.UnsatisfiedLinkError: Cannot load library: load_library[1098]: Library '/system/lib/libhoudini.so' not found
</code>```

Native methods in my app not using. What could be the problem?

答:
Check your advanced profiling Run-->Edit Configurations.. --> Profiling Tab
 --> Uncheck (Enable advanced profiling)</p>

Body:
I updated Android Studio to 3.0.0 and Gradle to 3.0.0

After run my app on emulator Genymotion (API 16-19) crashed.

Error:

E/AndroidRuntime: FATAL EXCEPTION: main
                  java.lang.ExceptionInInitializerError
                      at android.support.v4.app.SupportActivity.<init>(SupportActivity.java:68)
                      at android.support.v4.app.BaseFragmentActivityGingerbread.<init>(BaseFragmentActivityGingerbread.java:37)
                      at android.support.v4.app.BaseFragmentActivityHoneycomb.<init>(BaseFragmentActivityHoneycomb.java:29)
                      at android.support.v4.app.BaseFragmentActivityJB.<init>(BaseFragmentActivityJB.java:30)
                      at android.support.v4.app.FragmentActivity.<init>(FragmentActivity.java:79)
                      at android.support.v7.app.AppCompatActivity.<init>(AppCompatActivity.java:61)
                      at com.myapp.start.BaseActivity.<init>(BaseActivity.java:37)
                      at com.myapp.start.StartActivity.<init>(StartActivity.java:40)
                      at java.lang.Class.newInstanceImpl(Native Method)
                      at java.lang.Class.newInstance(Class.java:1319)
                      at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
                      at android.app.ActivityThread.access$600(ActivityThread.java:130)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
                      at android.os.Handler.dispatchMessage(Handler.java:99)
                      at android.os.Looper.loop(Looper.java:137)
                      at android.app.ActivityThread.main(ActivityThread.java:4745)
                      at java.lang.reflect.Method.invokeNative(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:511)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
                      at dalvik.system.NativeStart.main(Native Method)
                   Caused by: java.lang.UnsatisfiedLinkError: Cannot load library: load_library[1098]: Library '/system/lib/libhoudini.so' not found

Native methods in my app not using. What could be the problem?


问:
How to get client IP address in JavaScript?
I'm trying to get the client's IP address. This is my code so far.
Any suggestions?

```

答:
```<code>function user_location() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      console.log( this.responseText);
    }
  };
  xhttp.open("GET", "//api.ipify.org?format=json", true);
  xhttp.send();
}
</code>```


问:
Passing Data notification services to activity But didn't get any response
I am passing data from notification services to activity using event bus. but not getting any message on main activity. here my code is.

```<code>   public void onMessageReceived(RemoteMessage remoteMessage) {

    super.onMessageReceived(remoteMessage);
    EventBus.getDefault().postSticky(new String("Send data"));

    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public void onEvent(String event) {
    // your implementation
    Toast.makeText(this, event, Toast.LENGTH_SHORT).show();
    }

    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public void onMessageEvent(String message) {

    Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
     }

 public void onEventMainThread(MessageEvent event) {
     Toast.makeText(this, event + "", Toast.LENGTH_SHORT).show();
}

@Override
  protected void onResume() {
    super.onResume();

     InstaOrderApp.getInstance(this).setCurrentactvity(this);

     EventBus.getDefault().register(this);
     updateTableQty();
   }
</code>```

Any one please help me where is issue ?
thanks

答:
Did you register the event bus on your  onStart method?</p>

```<code>@Override

public void onStart() {

    super.onStart();

    EventBus.getDefault().register(this);

}
</code>```

Body:
I am passing data from notification services to activity using event bus. but not getting any message on main activity. here my code is.

   public void onMessageReceived(RemoteMessage remoteMessage) {

    super.onMessageReceived(remoteMessage);
    EventBus.getDefault().postSticky(new String("Send data"));

    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public void onEvent(String event) {
    // your implementation
    Toast.makeText(this, event, Toast.LENGTH_SHORT).show();
    }

    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public void onMessageEvent(String message) {

    Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
     }

 public void onEventMainThread(MessageEvent event) {
     Toast.makeText(this, event + "", Toast.LENGTH_SHORT).show();
}

@Override
  protected void onResume() {
    super.onResume();

     InstaOrderApp.getInstance(this).setCurrentactvity(this);

     EventBus.getDefault().register(this);
     updateTableQty();
   }

Any one please help me where is issue ?
thanks

Body:
Did you register the event bus on your  onStart method?

@Override

public void onStart() {

    super.onStart();

    EventBus.getDefault().register(this);

}


问:
AAD Reply Url Issue with https
We have an on-prem asp.net core app that leverage AAD for authentication, the app is setup to run in both:

http://domainserver/app
&
https://domainserver/app

In Azure AD the reply url for the application is setup as
http://domainserver/app/signin-oidc & https://domainserver/app/signin-oidc

When using http url, the sign-in process works fine, however in https mode, we get the following error:

AADSTS50011: The reply address ‘https://domainserver/app/signin-oidc’
  does not match the reply addresses configured for the application:
  appguid . More details: not specified

The reply https url is setup in AAD for the App exactly as it appears in the error message, so I’m not sure why it says it’s not matching.
One reason I can think of is that the SSL certificate used for https is a local domain signed certificate, and somehow it’s causing the error.  But I’m not sure if that’s the case since AAD is just responsible to redirect back to the specified url, should not really care or know about the validity of the SSL.

Here is the image showing the setting url, the redirect url and the error message url matches exactly.  You just have to trust me the part that's blocked out are also the same. :)

Anyone got any ideas why this happens?

答:
Protocol matters. Azure AD will treat http://website.com and https://website.com as different reply URLs. However Azure can only let your put in multiple Reply URLs in a same domain. There is a case solution may be helpful to you:

Issue: Using the Azure AD authentication option to sign into the Skype for Business (SfB) Web SDK and you are seeing an AAD error page . The error page should have this message:

"AADSTS50011: The reply address 'https://...' does not match the reply
  addresses configured for the application <...>"

Solution:

You need to configure the main domain name where you're hosting your app as a reply URL in the AAD registration for your app and pass it as the redirect_uri when redirecting to AAD to allow the user to sign in.

You should be using code like this to redirect the user to enter her credentials to sign into Azure AD:

```<code>var href = 'https://login.microsoftonline.com/common/oauth2/authorize?response_type=token&client_id=';
href += client_id + '&resource=https://webdir.online.lync.com&redirect_uri=' + window.location.href;
window.location.href = href;
</code>```

Note In the code above that we are using window.location.href as the value of the redirect_uri query parameter in forming the URL of the AAD endpoint where the user will sign in. This parameter tells AAD to redirect the client browser and the access token obtained by signing into AAD back to the page we're currently on - the main app page. However, AAD will only redirect the access token to URLs that are specified as Reply URLs in the app registration in AAD.

Follow these steps to check your configured Reply URLs and add additional ones:

Sign into portal.azure.com with an account that's an administrator on your tenant.

Navigate to Azure Active Directory in the left side bar > App registrations > Your app > All settings > Reply URLS.

Type the domain name where you're hosting your app and click Save.

This solution is from this document.

Update

According to your screenshot, your Reply URI is different:

```<code>https://domainserver/app/signin-oidc
</code>```

is not in your Reply URL list,

in your Reply URL list is

https://domainserver/app/signin-odic

Go to change them as same URL .

Title: AAD Reply Url Issue with https

Body:
Protocol matters. Azure AD will treat http://website.com and https://website.com as different reply URLs. However Azure can only let your put in multiple Reply URLs in a same domain. There is a case solution may be helpful to you:

Issue: Using the Azure AD authentication option to sign into the Skype for Business (SfB) Web SDK and you are seeing an AAD error page . The error page should have this message:

"AADSTS50011: The reply address 'https://...' does not match the reply
  addresses configured for the application <...>"

Solution:

You need to configure the main domain name where you're hosting your app as a reply URL in the AAD registration for your app and pass it as the redirect_uri when redirecting to AAD to allow the user to sign in.

You should be using code like this to redirect the user to enter her credentials to sign into Azure AD:

var href = 'https://login.microsoftonline.com/common/oauth2/authorize?response_type=token&client_id=';
href += client_id + '&resource=https://webdir.online.lync.com&redirect_uri=' + window.location.href;
window.location.href = href;

Note In the code above that we are using window.location.href as the value of the redirect_uri query parameter in forming the URL of the AAD endpoint where the user will sign in. This parameter tells AAD to redirect the client browser and the access token obtained by signing into AAD back to the page we're currently on - the main app page. However, AAD will only redirect the access token to URLs that are specified as Reply URLs in the app registration in AAD.

Follow these steps to check your configured Reply URLs and add additional ones:

Sign into portal.azure.com with an account that's an administrator on your tenant.

Navigate to Azure Active Directory in the left side bar > App registrations > Your app > All settings > Reply URLS.

Type the domain name where you're hosting your app and click Save.

This solution is from this document.

Update

According to your screenshot, your Reply URI is different:

https://domainserver/app/signin-oidc

is not in your Reply URL list,

in your Reply URL list is

https://domainserver/app/signin-odic

Go to change them as same URL .


答:
According to me, the one of the solutions is to create new view controller which is having your splash design & redirect it after the time whatever u want...

Redirecting code id here...

```<code>dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

    [self TabBarPush];

});
</code>```

Benefits of using new view controller as splash is that you can customise it, code it & can also add any type of animations in your splash screen as e.g.. loader etc..

If you want some data to be fetched before redirecting then you can code like this also...

```<code>[[syncEngine sharedEngine] syncAllData:^(BOOL finished) {
        [self TabBarPush];
}];
</code>```

Thank you..

Body:
According to me, the one of the solutions is to create new view controller which is having your splash design & redirect it after the time whatever u want...

Redirecting code id here...

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

    [self TabBarPush];

});

Benefits of using new view controller as splash is that you can customise it, code it & can also add any type of animations in your splash screen as e.g.. loader etc..

If you want some data to be fetched before redirecting then you can code like this also...

[[syncEngine sharedEngine] syncAllData:^(BOOL finished) {
        [self TabBarPush];
}];

Thank you..


问:
Product Method Overloading
so I was working on this problem on CodeHS, then I was stuck for so long so decided to ask here.

The exercise is to overload the product method to allow for multiplying together other types of values:

two doubles

an int and a double

a double and an int

three ints

three doubles

```<code>public class Product extends ConsoleProgram
{
    public void run()
    {
        int intValue = 5;
        double doubleValue = 2.5;

        int product1 = product(intValue, intValue);
        System.out.println(product1);

        // Use method overloading to define methods
        // for each of the following method calls

        double product2 = product(doubleValue, doubleValue);
        System.out.println(product2);

        int product3 = product(intValue, intValue, intValue);
        System.out.println(product3);

        double product4 = product(intValue, doubleValue);
        System.out.println(product4);

        double product5 = product(doubleValue, intValue);
        System.out.println(product5);

        double product6 = product(doubleValue, doubleValue, doubleValue);
        System.out.println(product6);
    }

    public int product(int one, int two)
    {
        return one * two;
    }
}
</code>```

Thank you

答:
Method overloading means you can create methods with same method name by changing those methods parameters (parameter count,parameter type and parameter Patterns). Combination of method name and parameters also called as method signature

Following is an example for method overloading.

```<code>public void int myMethod(){}

public void int myMethod(int a){}

public void String myMethod(String a){}

public void double myMethod(int a , String a){}

public void int myMethod(String a,int a){}
</code>```

Note that you can't overload methods by changing return type

Title: Product Method Overloading

Body:
so I was working on this problem on CodeHS, then I was stuck for so long so decided to ask here.

The exercise is to overload the product method to allow for multiplying together other types of values:

two doubles

an int and a double

a double and an int

three ints

three doubles

public class Product extends ConsoleProgram
{
    public void run()
    {
        int intValue = 5;
        double doubleValue = 2.5;

        int product1 = product(intValue, intValue);
        System.out.println(product1);

        // Use method overloading to define methods
        // for each of the following method calls

        double product2 = product(doubleValue, doubleValue);
        System.out.println(product2);

        int product3 = product(intValue, intValue, intValue);
        System.out.println(product3);

        double product4 = product(intValue, doubleValue);
        System.out.println(product4);

        double product5 = product(doubleValue, intValue);
        System.out.println(product5);

        double product6 = product(doubleValue, doubleValue, doubleValue);
        System.out.println(product6);
    }

    public int product(int one, int two)
    {
        return one * two;
    }
}

Thank you

Body:
Method overloading means you can create methods with same method name by changing those methods parameters (parameter count,parameter type and parameter Patterns). Combination of method name and parameters also called as method signature

Following is an example for method overloading.

public void int myMethod(){}

public void int myMethod(int a){}

public void String myMethod(String a){}

public void double myMethod(int a , String a){}

public void int myMethod(String a,int a){}

Note that you can't overload methods by changing return type


问:
Syntax error When convert from MySQL to T-SQL
I'm new in SQL .
I'm converting mysql to SQL.

I've found an error when I use DateAdd function.

Here is the query:

```<code>SELECT
      [id],
      [test_code],
      [test_name],
      [test_price],
      [discount],
      DATEADD(CURRENT_TIMESTAMP, INTERVAL [test_duration] HOUR) as delivery_date,
      [is_active]
    FROM [icddrb_tblab].[dbo].[tb_test]
    WHERE [icddrb_tblab].[dbo].[tb_test].[id] =0
</code>```

It gives error:
Msg 102, Level 15, State 1, Line 7

Incorrect syntax near 'test_duration'.'

Can anyone suggest me, where is the issue.

答:
DATEADD function takes parameter like this DATEADD (datepart , number , date )

You can use this.

```<code>SELECT
      [id],
      [test_code],
      [test_name],
      [test_price],
      [discount],
      DATEADD(HOUR, [test_duration], CURRENT_TIMESTAMP ) as delivery_date,
      [is_active]
    FROM [icddrb_tblab].[dbo].[tb_test]
    WHERE [icddrb_tblab].[dbo].[tb_test].[id] =0
</code>```

Body:
I'm new in SQL .
I'm converting mysql to SQL.

I've found an error when I use DateAdd function.

Here is the query:

SELECT
      [id],
      [test_code],
      [test_name],
      [test_price],
      [discount],
      DATEADD(CURRENT_TIMESTAMP, INTERVAL [test_duration] HOUR) as delivery_date,
      [is_active]
    FROM [icddrb_tblab].[dbo].[tb_test]
    WHERE [icddrb_tblab].[dbo].[tb_test].[id] =0

It gives error:
Msg 102, Level 15, State 1, Line 7

Incorrect syntax near 'test_duration'.'

Can anyone suggest me, where is the issue.

Body:
DATEADD function takes parameter like this DATEADD (datepart , number , date )

You can use this.

SELECT
      [id],
      [test_code],
      [test_name],
      [test_price],
      [discount],
      DATEADD(HOUR, [test_duration], CURRENT_TIMESTAMP ) as delivery_date,
      [is_active]
    FROM [icddrb_tblab].[dbo].[tb_test]
    WHERE [icddrb_tblab].[dbo].[tb_test].[id] =0


问:
Jquery / Javascript error: Object doesn't support this property or method
I am getting the error "Object doesn't support this property or method" in javascript.

I took some original code by, Paul Da Silva, and modified it. I am changing from a datePicker into a timePicker.  I have renamed some fields and functions, and am still debugging it. But I did something wrong / broke something in the process.  I ran it thru jLint and fixed some of the minor issues.  I am stumped, can someone help?

The error occurs on the following line

```<code>this.bindMethodsToObj("show", "hide", "hideIfClickOutside", "keydownHandler", "selectTime");
</code>```

but the functions: "bindMethodsToObj", "show", "hide", "hideIfClickOutside", "keydownHandler", "selectTime" all exist?

Line 534:

```<code>bindMethodsToObj: function () {
    var i = 0;
    for (i = 0; i < arguments.length; i++) {
        this[arguments[i]] = this.bindToObj(this[arguments[i]]);
    }
},
</code>```

The test html page is at: http://www.gleneck.com/tv/_vhslibr14/jtpicker/jtpicker_test.htm

the javascript is at: www.gleneck.com/tv/_vhslibr14/jtpicker/jquery.jtpicker.js

I am stumped, can someone help?

答:
Line 88 of your jquery.jtpicker.js needs to be changed from:

```<code>jtPicker.R_o_w_type = {
</code>```

to:

```<code>jtPicker.prototype = {
</code>```

The prototype method is how javascript knows to add those functions to your object. It doesn't know what to do with "R_o_w_type"

Body:
I am getting the error "Object doesn't support this property or method" in javascript.

I took some original code by, Paul Da Silva, and modified it. I am changing from a datePicker into a timePicker.  I have renamed some fields and functions, and am still debugging it. But I did something wrong / broke something in the process.  I ran it thru jLint and fixed some of the minor issues.  I am stumped, can someone help?

The error occurs on the following line

this.bindMethodsToObj("show", "hide", "hideIfClickOutside", "keydownHandler", "selectTime");

but the functions: "bindMethodsToObj", "show", "hide", "hideIfClickOutside", "keydownHandler", "selectTime" all exist?

Line 534:

bindMethodsToObj: function () {
    var i = 0;
    for (i = 0; i < arguments.length; i++) {
        this[arguments[i]] = this.bindToObj(this[arguments[i]]);
    }
},

The test html page is at: http://www.gleneck.com/tv/_vhslibr14/jtpicker/jtpicker_test.htm

the javascript is at: www.gleneck.com/tv/_vhslibr14/jtpicker/jquery.jtpicker.js

I am stumped, can someone help?

Body:
Line 88 of your jquery.jtpicker.js needs to be changed from:

jtPicker.R_o_w_type = {

to:

jtPicker.prototype = {

The prototype method is how javascript knows to add those functions to your object. It doesn't know what to do with "R_o_w_type"


问:
How find last day of previous month on the basis of Month and year in SQL Server
I have a requirement where I have to find the closing balance of previous month
on the basis of month and year.

I have tried this code:

```<code>DECLARE @month NUMERIC = 11
DECLARE @Year NUMERIC = 2017

SELECT
    DATEADD(DAY, -1, DATEADD(MONTH, @Month, DATEADD(YEAR, @Year - 1900, 0)))
</code>```

but this is returning the value of last day of the current month '2017-11-30 00:00:00.000'.

Instead of this I want the last day of the previous month: '2017-10-31 00:00:00.000'

答:
You are going right just add -1 to your variable @Month for last month date:

```<code>SELECT  Dateadd(day, -1, Dateadd(month, @Month-1,
                                      Dateadd(year, @Year - 1900, 0)
                                             ))
</code>```

Result :

```<code>2017-10-31 00:00:00.000
</code>```

Body:
I have a requirement where I have to find the closing balance of previous month
on the basis of month and year.

I have tried this code:

DECLARE @month NUMERIC = 11
DECLARE @Year NUMERIC = 2017

SELECT
    DATEADD(DAY, -1, DATEADD(MONTH, @Month, DATEADD(YEAR, @Year - 1900, 0)))

but this is returning the value of last day of the current month '2017-11-30 00:00:00.000'.

Instead of this I want the last day of the previous month: '2017-10-31 00:00:00.000'

Body:
You are going right just add -1 to your variable @Month for last month date:

SELECT  Dateadd(day, -1, Dateadd(month, @Month-1,
                                      Dateadd(year, @Year - 1900, 0)
                                             ))

Result :

2017-10-31 00:00:00.000


答:
Try adding : columns.orderable

```<code>"columnDefs": [
    { "orderable": false, "targets": 2 }
  ]
</code>```

JSFiddle Here

$('#table').DataTable( {
"columnDefs": [
    { "orderable": false, "targets": 2 }
  ]
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet"/>

<table class="table table-striped table-bordered post-list-table" id="table" >
  <thead>
    <tr>
      <th>Title</th>
      <th>Created At</th>
      <th>Action</th>
    </tr>
  </thead>
</table></code>```

Title: How to Disable sorting of only one specific column in Data tables?

Body:
Suppose i have the table like below :

And I want to disable sorting of Action Column

      Title
      Created At
      Action

$('#table').DataTable();

Body:
Try adding : columns.orderable

"columnDefs": [
    { "orderable": false, "targets": 2 }
  ]

JSFiddle Here

<!--Script.js-->
$('#table').DataTable( {
"columnDefs": [
    { "orderable": false, "targets": 2 }
  ]
  });

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet"/>

<table class="table table-striped table-bordered post-list-table" id="table" >
  <thead>
    <tr>
      <th>Title</th>
      <th>Created At</th>
      <th>Action</th>
    </tr>
  </thead>
</table>