text:
Q: Are rogue intents possible or is something else happening? Background
We have a legacy Android app which has recently developed a wild bug. It's not affecting many users but it breaks all functionality requiring admin and support to be involved. It is bad enough that it has to be fixed. We have not been able to reproduce the bug and there is no logging.
The current team does not have much or any Android experience and aren't familiar with the code base.
Error Description
The app has three states:

*

*Activated, tokens

*Activated, no tokens

*Not-activated, no tokens

Something is causing the app to go from state (1) to state (2), i.e. tokens are being lost or deleted. After this the app remains in state (2).

*

*API 7

*Occurs on Android 4.1 +

*Re-occurs for some users

*Tokens are retrieved from a server & stored on device.

Theory
The app can be launched via a browsable intent which will delete all tokens and "re-activate" it. This will send it from state (1) to state (2).
Code Description
Intent filter:
<intent-filter>
  <action android:name="android.intent.action.MAIN" />

  <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
  <data android:scheme="myscheme" />

  <category android:name="android.intent.category.DEFAULT" />
  <category android:name="android.intent.category.BROWSABLE" />

  <action android:name="android.intent.action.VIEW" />
</intent-filter>

Start code:
public void onStart() {
    super.onStart();

    Uri activationUrl = getIntent().getData();
    boolean busyActivating = (activationUrl != null);

    if (busyActivating) {
        // delete tokens
        // save activation url
        // state - activated no tokens
    } else if (isActivated()) {
        startNormally();
    } else {
        askToActivate();
    }
}

Conclusion
To me it looks like there is some type of rogue intent causing and activated app to enter the busyActivating flow.
I was able to replicate this by forcing the intent twice but it has been confirmed that users aren't doing this.
Is this at all possible? Is something else going on here?

EDIT: We couldn't figure out why this was happening and in the end I just changed the code to be a bit more robust and hoped for the best.
Even though this question will get old and die, if you do come across it in the future please respond if you experienced something similar!


text:
Q: AngularJs - Use custom filter inside directive controller Scenario
I have an array of users containing information about them, I do an ng-repeat combined with a custom directive that generates an HTML user card, keeping the scope of each card relative to the individual user, inside the user model there is a value that I need to filter with a custom filter before the template gets compiled, because if I do it inside the template the time it takes to be filtered makes the tooltip not to show until the value is ready and that looks as if something is not working.
My code so far
// userCard directive
angular.module('userCard', []).directive('UserCard', function() {
  return {
    restrict: 'EA',
    templateUrl: 'userCard.tpl.html',
    scope: {
        user: '='
    },
    controller: ['$scope', 'fromNowFilter', function($scope, fromNowFilter) {

        angular.forEach($scope.user.reminders, function(reminder) {
            reminder.last_sent = reminder.last_sent === null ? 'No reminder has been sent!' : fromNowFilter(reminder.last_sent);
        });
    }],
    link: function(scope, element) {
        // Add the base class to the user card element
        element.addClass('user-card');
    }
  };
});

// fromNow custom filter
angular.module('userCard').filter('fromNow', function() {
  return function(date) {
    return moment(date).fromNow();
  };
});

// The error I keep getting
Unknown provider: fromNowFilterProvider <- fromNowFilter

A: Try inject filterprovider and run your filter.
controller: ['$scope', '$filter', function($scope, $filter) {
       var fromNowFilter = $filter('fromNow');
        angular.forEach($scope.user.reminders, function(reminder) {
            reminder.last_sent = reminder.last_sent === null ? 'No reminder has been sent!' : fromNowFilter(reminder.last_sent);
        });
    }],

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pattern to fetch REST data "lazily" I am making a UIScrollView where the content is infinite, for example a calendar with events in it. I am fetching the events from a backend using a REST call.
I am wondering if anyone have a pattern/chunk of code where the limits of:

*

*When to fetch more data
and

*How much more to fetch
is easily adjustable.
For example i'd like to experiment with fetching events for 30 days (15 forward and 15 backwards), and when the user scrolls 10 days forward (5 days from limit) i'd like to fetch 30 more days forward, meaning i now have 60 days.
Thanks

A: Using a scroll view (whether UIScrollView directly, or UITableView, which could help you with memory management - unloading of non-visible content) you can use the scrollViewDidScroll: delegate method and the contentOffset property to check where the user is / has scrolled to and whether it's getting close to the end of the data you currently have. The algorithm you use is dependent upon the height of each item / day in your scroll view. In combination with the contentOffset you can tell what day the user is scrolled to.

A: I made i simple method myself.
I have a void method in my model that takes a date, a numberOfDaysToFetch and a limit.
numberOfDaysToFetch could be 90 and limit could be 30.
As the scrollview scrolls through the views (each representing a day) i call the method for each day that is visible.
If data for the day is not present locally or the day is closer than limit (30) to data not present locally, the method will call a service to fetch data (asyncrounously) for example from the newest date and numberOfDaysToFetch forward.
This means the method will first get 6 months of data. 3 forwards and 3 backwards. When scrolling 2 months forward, 3 more months of data is fetched.
Whenever a response is received from the service the data received is stored locally and a notification is thrown and a method will be called to update the views in the scrollview.
I can now adjust limit and numberOfDaysTo to what fits the performance of the webservice best.


text:
Q: Mac OS X does not send cookies to WebDAV resource my WebDAV server (based on Tomcat's DefaultServlet) requires NTLM authentication. The server works fine with Windows clients.
A Mac (OS X 10.6.8) client performs the HTTP authentication handshake on each request, when I connect the Mac Finder to the server. This is because it does not send the session cookie back to my server. Is there a configuration option that I can set to tell it to accept and send the session cookie?
When I connect via Safari to the server, the session cookie is sent.
Thanks in advance.
Wolfgang


text:
Q: Query to convert datetime column to a different time zone I am trying to assemble a date, time & time zone and then convert it to UTC time zone.
In the query below an error is created with the database field which stores the time zone --- namely t.timezone
The value of t.timezone is Asia/Tokyo .  All other time zones are in a similar format.
select (select CONCAT( DATE(m.last_mailing at time zone 'utc' + INTERVAL '1 day'), ' ', MAKE_TIME(m.email_delivery_hour::int, 0, 0))::timestamp with time zone t.timezone) at time zone 'utc' FROM acts2301_membership.member_subscriptions m INNER JOIN acts2301_email_queue.timezone t ON (m.timezone_reference = t.reference) WHERE m.subscription_reference = '514';

A: The below is a query that executes, following the logic in your question. However, much depends on how the time zones of the various pieces of data and your server are set (see also my comment on your question), so you may find you have to tweak where you specify t.timezone and where UTC:
SELECT ((date_trunc('day', (m.last_mailing AT TIME ZONE 'UTC')::timestamp) +
         interval ('1 day') +
         (m.email_delivery_hour::int::text || ':00:00')::time
        )::timestamptz AT TIME ZONE t.timezone
       )::timestamptz AT TIME ZONE 'UTC'
FROM acts2301_membership.member_subscriptions m
JOIN acts2301_email_queue.timezone t ON m.timezone_reference = t.reference
WHERE m.subscription_reference = '514';

Also notice the beauty of proper code formatting...


text:
Q: Why does this output wrong (get/set methods) Just going through get/set methods and I'm having trouble with my output. Instead of displaying the First/Last name of the object it is displaying null/null.
Could anyone offer any insight, i'm not familiar with get/set methods.
Code
public class Person {

private String firstName;
private String lastName;

public Person (String a, String b){

a = firstName;
b = lastName;
}

public String getfirstName(){

     return firstName;
}

public void setfirstName(){

     this.firstName = firstName;
}

public String getlastName(){

    return lastName;
}

public void setlastName(){

    this.lastName = lastName;
}

public String toString() {

String s = "First name:" + firstName + "Last name:" + lastName;
return s;

}
}

This is my class just to create the object and run to toString method
public class PersonDriver {

public static void main(String[]args){

    Person p1 = new Person ("Thomas", "Brown");

    System.out.print(p1.toString());
 }
}

A: You need to assign the parameters to the instance variables and not the reverse. What you're doing currently is reassigning a and b which were passed to the constructor, whereas you need to assign the values of a and b to the firstName and lastname fields of the class.
public Person (String a, String b){
    firstName = a;
    lastName = b;
}

A: You inverted the variables within your constructor
You need  Change below code
public Person (String a, String b){

   a = firstName;
   b = lastName;
}

to
public Person (String a, String b){

    firstName = a;
    lastName = b;
}

A: Primarily setters has to be
public void setFirstName(String firstName){

     this.firstName = firstName;
}

public void setLastName(String lastName){

    this.lastName = lastName;
}

A: Your setters should take an argument - the value to be set. Your constructor should assing the values of the arguments to the class properties not the other way round.

A: I think the constructor has to be like
public Person (String a, String b){
    firstName = a;
    lastName = b;
}

A: You need to swap the variabels. You assign the value of the object the parameters.
public Person (String a, String b){

firstName= a;
lastName= b;
}

Also your set method are useless without parameters :
public void setlastName(String parameter){

this.lastName = parameter;

}

A: You sure your methods shouldn't be more in line with this?
public class Person {

  private String firstName;
  private String lastName;

  public Person (String a, String b){

   firstName=a;
   lastName=b;
  }

  public String getfirstName(){

    return firstName;
  }

  public void setfirstName(String firstName){

    this.firstName = firstName;
  }

  public String getlastName(){

    return lastName;
  }

  public void setlastName(String lastName){

    this.lastName = lastName;
  }

  public String toString() {

  String s = "First name:" + firstName + "Last name:" + lastName;
  return s;

  }
  }

You need to pass the setter methods the values you would want to set the variables to. Apart from that, like the others mentioned, you swapped the variable names in the constructor. :)


text:
Q: Cannot run pool.amap() twice in pathos.multiprocessing I want to parallelize simulation of multiple agents. Because I want my results to be instances of a class, to avoid issues with serialization I use pathos.multiprocessing instead of multiprocessing.
I do it like this:
import pathos.multiprocessing as mp

sim_agent(T): #simulate single agent for T periods
    ag = agent()
    for t in range(T):
         ag.step()
    return ag

def simulate_parallel(N, T):
    if __name__ == '__main__':
        pool = mp.ProcessPool()
        results = pool.amap(sim_agent, [T]*N)
        agents = results.get()
        return agents

I can run simulate_parallel once. When I do it again, I get an error:
--> 142         agents = results.get()

~/anaconda3/anaconda3/lib/python3.7/site-packages/multiprocess/pool.py in get(self, timeout)
    655             return self._value
    656         else:
--> 657             raise self._value
    658
    659     def _set(self, i, obj):

~/anaconda3/anaconda3/lib/python3.7/site-packages/multiprocess/pool.py in _handle_tasks(taskqueue, put, outqueue, pool, cache)
    429                         break
    430                     try:
--> 431                         put(task)
    432                     except Exception as e:
    433                         job, idx = task[:2]

~/anaconda3/anaconda3/lib/python3.7/site-packages/multiprocess/connection.py in send(self, obj)
    207         self._check_closed()
    208         self._check_writable()
--> 209         self._send_bytes(_ForkingPickler.dumps(obj))
    210
    211     def recv_bytes(self, maxlength=None):

~/anaconda3/anaconda3/lib/python3.7/site-packages/multiprocess/connection.py in _send_bytes(self, buf)
    394         n = len(buf)
    395         # For wire compatibility with 3.2 and lower
--> 396         header = struct.pack("!i", n)
    397         if n > 16384:
    398             # The payload is large so Nagle's algorithm won't be triggered

error: 'i' format requires -2147483648 <= number <= 2147483647

I also get the same error when I try to use pool.amap() in other functions. Even when I make N and T small, it is still the same behavior: I can run simulate_parallel once and cannot do it for the second time. Why could that be? Thanks!


text:
Q: Convert to DateTime Format Hello is there a way to convert this string "Saturday 04/23/2013 11:05 PM" to a valid DateTime Format?
Because it gives me FormatExceptionError everytime I execute this condition:

String was not recognized as a valid DateTime because the day of week was incorrect.

if(DateTime.Parse("Saturday 04/23/2013 11:05 PM") < DateTime.Today)
{
//code here
}

Is there a solution to this problem?

A: use DateTime.ParseExact()
string _strdate = "Tuesday 04/23/2013 11:05 PM"; // should be tuesday
DateTime _date = DateTime.ParseExact(_strdate,"dddd MM/dd/yyyy hh:mm tt",
                                     CultureInfo.InvariantCulture)

*

*DateTime.ParseExact()

*Custom Date and Time Format Strings

A: If you expect invalid data you should use TryParse or TryParseExact
DateTime myDate;
if(DateTime.TryParse("Saturday 04/23/2013 11:05 PM", out myDate))
{
   if (myDate < DateTime.Today) { //code here }
}
else
{
   //Do something here for invalid data
}

A: String was not recognized as a valid DateTime because the day of week was incorrect.
04/23/2013 is Tuesday, not Saturday .
Maybe the exception occurs when your datetime statement is Contradiction.
Hope it help...

A: The date and day of week do not match. 23rd April of 2013 is Tuesday and not Saturday. In no calendar of world you will have this day as Saturday. That's why it gives error String was not recognized as a valid DateTime because the day of week was incorrect.
So may be it converts your date and then validates. Hence it is failing in validation.
But when Tuesday is provided, This will work.
string str = "Tuesday 04/23/2013 11:05 PM";

DateTime dt = DateTime.ParseExact(str, "dddd MM/dd/yyyy hh:mm tt", CultureInfo.InvariantCulture);


text:
Q: Popen.stdin.write is not working with Python3 Popen.stdin.write is not working with Python3
I am initiating a telnet connection to a remote device and start sending the commands.
Below is a simple example which makes a telnet connection to the remote device and starts sending device specific commands [i.e "vr" , "KP on"]

import subprocess

telnet_client = subprocess.Popen(
    ["telnet", "192.168.1.120", "4002"],
    stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
    universal_newlines=True)

#Get Version
telnet_client.stdin.write('vr\n')
telnet_client.stdin.flush()

#Power on the device
telnet_client.stdin.write('kp on\n')
telnet_client.stdin.flush()

#Factory default
telnet_client.stdin.write('fd\n')
telnet_client.stdin.flush

Every stdin.write() is not throwing any exception or any error, just returns number of bytes written. But actually the message is not sent.
Ubuntu machine1:
I observed after installing Python3 in the machine, the above implementation stopped working with Python2.7
Ubuntu machine2:
In another Ubuntu machine after installing Python3, the above implementation works with Python2.7 but it doesn't work with Python3.
So common thing, in any direction Popen.stdin.write doesn't work with Python3. I believe some packages are screwing the system.

A: This is all set.
Actually server is receiving the data after calling stdin.flush
telnet_client.stdin.write('vr\n')
telnet_client.stdin.flush()

A: I was facing the same issue. process.stdin.write() works in Python 2.7, but not in Python 3. Though I couldn't debug what the issue was, I was able to achieve the functionality with process.communicate(). Documentation. This is the recommended way of communicating with a process. Also, the string we pass as input to this method needs to end with a '\n'.

A: To make stdin work I have used the following 2 lines to communicate in python3
p.stdin.write(bytes(string+'\n', 'utf-8'))
p.stdin.flush()

and from the child process, I am doing stdout.flush to communicate back to the parent.


text: Q: Images a bit broken in Typo3 I have first experienced troubles with pictures when their size has been generated as 0 when inserted for example as a picture content element. Now I have started using RTE and when I try to insert a picture a windows pops up up with the list of available pictures but when I select one, the popped up windows goes blank and never recovers. When I deploy the app on the server everything works fine. What might be wrong with my local environment?


text:
Q: Ruby, Getting error when running in interactive ruby I'm new in ruby, everything is fine when I run it in eclipse (Screenshot) and I get the desired output but when I run it in interactive ruby I get the error in the screen shot

# MyVector Class
class  MyVector
  include Enumerable
  def initialize (a)
    if !(a.instance_of? Array)
      raise "ARGUMENT OF INITIALIZER MUST BE AN ARRAY"
    else
      @array = a
    end
  end

  def toArray
    @temp = Array.new(@array.length())
    i=0
    while(i<@array.length())
      @temp[i] = @array[i]
      i+=1
    end
    @temp
  end

  def to_s
    @array.to_s
  end

  def length
    @array.length()
  end

  def [](i)
    @array[i]
  end

  def each2(a)
    raise Error, "INTEGER IS NOT LIKE VECTOR" if a.kind_of?(Integer)
    Vector.Raise Error if length != a.length
    return to_enum(:each2, a) unless block_given?
    length.times do |i|
      yield @array[i], a[i]
    end
    self
  end

  def * (a)
    if a.kind_of? MyVector
      Vector.Raise Error if length != a.length
      p = 0
      each2(a) {|a1, a2|p += a1 * a2}
      p

    elsif a.kind_of? MyMatrix
      @temp = Array.new(a.transpose().length())
      i=0
      while(i<@temp.length())
        @temp[i] = (a.transpose()[i] * self)
        i+=1
      end
      MyVector.new(@temp)
    end
  end

end

# MyMatrix Class
class MyMatrix
  include Enumerable
  def initialize a
    @array=Array.new(a.length())
    i=0
    while(i<a.length)
      @array[i]=MyVector.new(a[i])
      i+=1
    end
  end

  def to_s
    "["+@array.map { |i| "'" + i.to_s + "'" }.join(",")+"]"
  end

  def length
    @array.length()
  end

  def [](i)
    @array[i]
  end

  def transpose
    @temp = Array.new(@array.length())
    i=0
    while(i<@array.length())
      @temp[i] = @array[i].toArray()
      i+=1;
    end
    MyMatrix.new(@temp.transpose())
  end

  def *m
    if m.kind_of? MyMatrix
      @temp=Array.new(@array.length())
      i=0
      while (i<@array.length())
        @temp[i] = (@array[i] * m).toArray()
        i+=1
      end
      MyMatrix.new(@temp)
    end
  end
end

A: Those commands you're running (cd D:\, and ruby hwk7.rb) are supposed to be run from the terminal, not from inside irb. Quit IRB and try running them again.


text:
Q: How can I execute a VBScript file from Ant script? I want to run a VBScript file from an Ant script. How can I do that?

A: Have a look at the exec task. It allows you to execute a system command from your Ant script.
EDIT:
An example could be:
<target name="RunVbScript">
    <exec executable="cscript">
        <arg value="MyScript.vbs"/>
        <arg value="argument 1" />
        <arg value="argument 2" />
        <arg value="argument n" />
    </exec>
</target>


text:
Q: What is the difference between Avalanche and WaterScrumFall? Recently I learnt about a new methodology based on waterfall and scrum: Water-Scrum-Fall.
Some say that is the new "reality" and is what scrum pragmatist use nowadays....
But, from the definition of "Avalanche":

The Avalanche model is a Software Engineering project management
  anti-pattern, it is a combination of a sequential process such as the
  Waterfall model and Agile software development methodologies [...]

What do you think about these two models? Aren't those the same?

More info:
http://www.infoq.com/news/2011/12/water-scrum-fall-is-the-norm
http://www.slideshare.net/harsoft/water-scrumfall-isrealityofagileformost

A: Water-Scrum-Fall is essentially when agile/scrum development processes are only applied to the development team's work(usually the implementation step in waterfall), and most of the previous project management 'waterfall' system remains in place. Those articles are primarily listing it as the reality for most shops where the development team does not have full control of the process, so agile cannot be used across the entire project. I don't believe either one is really trying to say it should be adopted, but it is somewhat common. The second article is more focused on the benefits/drawbacks so companies that find themselves in this model can improve what they have without massive process redesign.
Avalanche is best described as a faulty implementation of scrum where each 'sprint' is most of a waterfall. Each stage/department iterates rapidly on its own subset of work and has to communicate the results of those steps to the other departments. The result is often that each phase of the 'waterfall' is happening at the same time for the entire product. It is also characterized by extreme breakdowns in communication. Features are often being redesigned while being implemented or tested by departments that can't keep track of what stage each feature is at. The result is mass chaos and confusion, extremely difficult to manage projects, and poor morale as work is regularly(read: very frequently) invalidated by changing requirements/design.
The key difference between the two is that Water-Scrum-Fall is scrum in waterfall, which doesn't fundamentally break either model. Avalanche is waterfall in scrum, which is a slow motion catastrophe.


text:
Q: Consumir JSON con Angular. Error Estoy tratando de consumir un json con angular y me está dando el error:

error TS2322: Type 'Observable<{} | Prueba>' is not assignable to type 'Observable'.
    Type '{} | Prueba' is not assignable to type 'Prueba'.
      Type '{}' is not assignable to type 'Prueba'.
        Property 'date' is missing in type '{}'.

Mi servicio:

@Injectable()
export class MyService {

  constructor(private http: Http) { }

  private urlTo = 'http://url.com/json/';

  getData(): Observable<Prueba> {
    return this.http.get(this.urlTo)
      .map((response: Response) => <Prueba>response.json())
      .do(data => console.log('All: ' + JSON.stringify(data)))
      .catch(this.handleError);
  }

La clase prueba:

export class Prueba {
    public date: number;
    public name: string;
    public age: number;
}

A: He encontrado la solución a mi propio problema.

 getData(): Observable<Prueba> {
    return this.http.get(this.urlTo)
      .map((response: Response) => response.json())
      .do(data => console.log('All: ' + JSON.stringify(data)))
      .catch(this.handleError);
  }

Sobraba el <Prueba>
En la línea del map. Dónde ponía antes <Prueba>.response.json()


text:
Q: allocating data structures while making the borrow checker happy (second try) As a follow up to my question from yesterday (allocating data structures while making the borrow checker happy),
here is a simplified case. I would like to create a data structure and return both it and a reference to it. The following code does not compile:
fn create() -> (String, &str) {
  let s = String::new();
  let r = &s;
  return (s,r);
}

fn f() {
  let (s,r) = create();
  do_something(r);
}

If I restructure my code as follows, everything works fine:
fn create<'a>(s : &'a String) -> &'a str {
  let r = &s;
  return r;
}

fn f() {
  let s = String::new();
  let r = create(&s);
  do_something(r);
}

Unfortunately, in some cases structuring the code as in the first example is much preferable. Is there some way to make rust accept the first version?
Since both versions of the code do exactly the same thing, there shouldn't be any problems with safety. The question is just whether rust's type system is powerful enough to express it.

A: The Rust rules on references are that an object can either have

*

*any amount of immutable references,

*or exactly one mutable reference.

In other words, you cannot have an immutable reference and a mutable reference to the same object at the same time. Since the object counts as a mutable reference to itself, you cannot modify the object while an immutable reference to the object is present.
This is why your first piece of code does not compile. When you return (String, &str), String contains a mutable reference to a byte array, and &str contains an immutable reference to the same byte array. It violates the borrow checker rules.
However, you may ask, how does the second piece of code work? It works because you never attempt to modify s. If you modify s after r is created, then it will fail to compile:
fn f() {
    let mut s = String::new();
    let r = &s;
    s += "modified"; // ERROR: cannot borrow `s` as mutable because it is also borrowed as immutable
    do_something(r);
}

You shouldn't need to return a data structure and a reference to itself. Simply invoke the reference when it is necessary, rather than storing it in a variable. This will make sure that the borrow checker doesn't complain about references colliding.
fn f() {
    let s = String::new();
    // If a function takes &str, passing &String will be implicitly converted to &str
    do_something(&s);
    s += "modified"; // Perfectly fine, will still compile
    do_something_else(&s);
}

If you want to learn more about why the &String => &str conversion works, see the std::convert::AsRef trait.

A: I found a solution: use a raw pointer instead of a reference. The following code works:
fn create() -> (String, *const u8) {
  let s = String::new();
  let r = s.as_ptr();
  return (s,r);
}

fn f() {
  let (s,r) = create();
  do_something(r);
}


text:
Q: add custom buttons on alertify confirm dialog box I am using Alertify js 1.6.1 to show dialog box when user leaves a page. Apart from Ok and Cancel, I need to add one extra button "continue" in alertify js confirm dialog box. Is there a way to add custom button functionality? Let me know if you have any ideas on it. Thanks

A: You can build your own or extend the existing confirm:
    alertify.dialog('myConfirm', function() {
      var settings;
      return {
        setup: function() {
          var settings = alertify.confirm().settings;
          for (var prop in settings)
            this.settings[prop] = settings[prop];
          var setup = alertify.confirm().setup();
          setup.buttons.push({
            text: '<u>C</u>ontinue',
            key: 67 /*c*/ ,
            scope: 'auxiliary',
          });
          return setup;
        },
        settings: {
          oncontinue: null
        },
        callback: function(closeEvent) {
          if (closeEvent.index == 2) {
            if (typeof this.get('oncontinue') === 'function') {
              returnValue = this.get('oncontinue').call(this, closeEvent);
              if (typeof returnValue !== 'undefined') {
                closeEvent.cancel = !returnValue;
              }
            }
          } else {
            alertify.confirm().callback.call(this, closeEvent);
          }
        }
      };
    }, false, 'confirm');

see example


text:
Q: Is it possible to read the beginning of an S3 Inputstream more than once? I'm currently getting a ResponseInputStream<GetObjectResponse> from the S3Client (SDK 2), read it into a byte array and open two ByteArrayInputStream to pass them to Apache Tika and ImageIO.read.
Tika detectes the mimeType, BufferedImage is used to get height and width. Now both operations do not need to read the whole file (at least not for all image types). But reading into a byte array requires the consumption of the whole file.
Now how could I open two streams and just discard it when I'm done? Is the only way to perform two getObject calls to S3? Mark and reset isn't supported by the SDK.

A: One possible way is while uploading the image, if you add the metadata info in the request, then you only need to call GetObjectMetadata method and you can get the information that you need without retrieving the whole object again.
s3Client.putObject(bucketName, stringObjKeyName, "Uploaded String Object");

            // Upload a file as a new object with ContentType and title specified.
            PutObjectRequest request = new PutObjectRequest(bucketName, fileObjKeyName, new File(fileName));
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType("plain/text");
            metadata.addUserMetadata("title", "someTitle");
            request.setMetadata(metadata);
            s3Client.putObject(request);


text:
Q: qmake on OS X: disable x86/i386 arch (build only x86_64) I'm trying to get qmake to produce a makefile which does not include -arch i386 in CFLAGS/LFLAGS and so far I'm not succeeding. I tried the following:

*

*CONFIG-=x86

*QMAKE_CFLAGS-="-arch i386"
and a couple of other variations. The only one that does work is removing x86.prf from mkspecs/features/mac but I don't think it's a proper solution.
The current commandline looks approximately like this:
qmake -makefile -nocache CONFIG-=release CONFIG+=Debug CONFIG+=mac
 CONFIG+=CMDMAKE CONFIG-=x86 CONFIG+=x64
 QMAKE_MAKEFILE=makefile_mac_Debugx64 QMAKE_LFLAGS="<...>"
 QMAKE_CXXFLAGS="<..>" QMAKE_CFLAGS="<...>" QTVER=4.8.4 project.pro

A: I believe that qmake uses the compiler available in the PATH. If you want to use x86_64 compiler, alter PATH (and possibly INCLUDE, LIB and LIBPATH) environment variables for x86_64 compiler to be available, and then run qmake.

A: Tentative solution (need to verify a few things to confirm it, but seems to work):
1) make a separate build of Qt for x64 only, i.e.:
./configure -platform macx-g++42 -arch x64 -debug-and-release <...>

2) use qmake from that build to generate x64 makefiles.
It apparently still needs CONFIG-=x86 but that looks to be enough to prevent stray -arch i386 in the generated makefiles.


text:
Q: What is the accuracy of file creation time? I wanna do some measurements and video recording at the same time. It is crutial that I can align them after the measurement. My idea is to get the creation time of the video in ms and than add 1/fps milliseconds for each frame and look up the measurement closest to that calculated time.
If I use C# for example and use the CreationTime-property of the recorded video, I should be able to do this synchronisation, shouldn't I? How good is the CreationTime? I need an accuracy about 60 ms...

A: File time stamps on FAT drives are rounded to the nearest two seconds (even number) when the file is written to the drive. The file time stamps on NTFS drives are rounded to the nearest 100 nanoseconds when the file is written to the drive.
Time Stamps Change When Copying From NTFS to FAT

A: According to this link, the creation time on FAT volumes is good down to 10 milliseconds. I can only assume that NTFS would do better, but I can't verify that.
http://msdn.microsoft.com/en-us/library/ms724290(v=vs.85).aspx


text:
Q: How can I add left and right borders for one of the UITabBar items? If you look at the image below, you'll see two vertical lines -- isolating the middle tab item. (The lines are faint)
In code, how can I create these two lines?

A: You can:
1. add selected Image with lines in .png
2. set background image with lines and change this image depend on selected tab.
3. create your own view, inherited from UIView and add it as subview (in this case you have to implement own switch logic)

A:  This will help you to add the seperators
//Add seperators Line
        if let items = self.tabBar.items {
            //Get the height of the tab bar
            let height = self.tabBar.bounds.height
            let width = self.tabBar.bounds.width

//Calculate the size of the items
            let numItems = CGFloat(items.count)
            let itemSize = CGSize(
                width: tabBar.frame.width / numItems,
                height: tabBar.frame.height)

            for (index, _) in items.enumerated() {
                //We don't want a separator on the left of the first item.
                if index > 0 {

//Xposition of the item
                    let xPosition = itemSize.width * CGFloat(index)

                    let separator = UIView(frame: CGRect(
                        x: xPosition, y: 0, width: 3.5, height: height))
                    separator.backgroundColor = UIColor.white
                    tabBar.insertSubview(separator, at: 1)
               }
           }

extension UIImage {
class func imageWithColor(color: UIColor, size: CGSize) -> UIImage {
    let rect: CGRect = CGRectMake(0, 0, size.width, size.height)
    UIGraphicsBeginImageContextWithOptions(size, false, 0)
    color.setFill()
    UIRectFill(rect)
    let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image
}

}


text:
Q: Trouble moving around multiple While loops while ctr <=len(d)-1:
    latlong = re.findall(r'&ll=(.*?)&z=14', d[ctr], re.DOTALL)
    lat2, long2 = latlong[0].split(',')
    while ctra <=len(name)-1:
        if lat2 == lat[ctra] and long2 == long[ctra]:
            ctr = ctr +1
            break
        continue
        else:
            aname = re.findall(r'">(.*?)<' , d[ctr], re.DOTALL)

Simple problem is the lat2 and long2 matches I want to add one to the counter and then jump back up to the original While statement.  How do I do it.  This is my most recent attempt at and it isn't working.  I'm trying to check for multiple entries before putting an entry into the list.
I'm comparing latitude/longitude coordinates coming in from a website to ones that are already in the lat[ctra]/long[ctra].  If they don't match I want to continue with the next lat[ctra]/long[ctra] listing in the database.  All possible entries already in the database need to be checked against, quite naturally, until either a match is found or I have gone through the whole database.  Once all entries have been gone through then I want to add lat2/long2 to the database as well as the address, name, etc that goes with the coordinate.  I can add them in but I can't remove duplicate entries.

A: Here's the pseudocode :
outer_while :
    # do ya thing
    inner_while:
        if lat2 == long2 :
            ctr += 1
            break


text:
Q: Electroweak contribution to the anomalous magnetic dipole moment of the muon There are 3 diagrams that contributes to the anomalous magnetic moment of the muon (in unitary gauge):

The $Z$-contribution is gauge invariant, so we can focus on diagram (i)
The problem is that when I try to calculate diagram (i), I found:
$$F_2(q^2) \sim \int d^4l \ \frac{l^2}{(l^2-\Delta)^3}$$
which diverges.
Doing the same calculation in the $R_{\xi}$ gauge is possible to prove that the result is in fact gauge invariant,
so we can choose $\xi = 1$ to get the result given in R. Jackiw, S. Weinberg, Phys. Rev. D 5 (1972).
Do I need to add counterterms to fix the calculation done in unitary gauge?
(I heard that by adding counterterms, $F_2$ should not change, which means its not going to solve the problem.)
A similar problem occurs with the $W$ contribution.
What am I missing?


text:
Q: Beautifullsoup: How to grab the contents of an  tag thats within a ? I have been trying to extract the name from a twitter profile, the only problem I'm having is that beautifulsoup grabs the entire element. I have tried the {"class":} to specify the element but whenever I do this it results in getting

AttributeError: 'NoneType' object has no attribute 'text' error.

My code:
url = "https://twitter.com/barackobama"
html_doc = urllib.request.urlopen(url)
soup = BeautifulSoup(html_doc, 'lxml')

name = soup.find('h1').text
print(name)

A: If you want to get the text from child link of header instead of complete header text, try
url = "https://twitter.com/barackobama"
html_doc = urllib.request.urlopen(url)
soup = BeautifulSoup(html_doc, 'lxml')

name = soup.find('h1').a.text
print(name)
# 'Barack Obama'


text:
Q: How connect SciChart to Nuxt I need how coonect SciChart to Nuxt.js
i did

npm init nuxt-app "scichart"
npm install scichart
and i catch error

packeg.json
{
  "name": "scichart",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "dev": "nuxt",
    "build": "nuxt build",
    "start": "nuxt start",
    "generate": "nuxt generate",
    "buildsci": "webpack",
    "startsci": "webpack-dev-server"
  },
  "dependencies": {
    "core-js": "^3.15.1",
    "nuxt": "^2.15.7",
    "scichart": "^2.0.0"
  },
  "devDependencies": {
    "copy-webpack-plugin": "^6.3.2",
    "webpack": "^4.46.0 ",
    "webpack-cli": "^4.9.0",
    "webpack-dev-server": "^4.3.1"
  }
}

A: There are now a number of samples on the SciChart.js Github showing how to setup SciChart in frameworks. These include:

*

*Next.js

*Nuxt.js

*React

*Vue.js

*Blazor

*Angular

*Just Javascript (no framework)
Plus many more. The common problem with these frameworks is loading WebAssembly. SciChart.js uses WebAssembly to achieve really high performance 2D & 3D charts & graphs. Wasm file needs to be in the output folder when your project is built. This is different for every framework.
There is now a page on the SciChart.js Documentation showing how to load webassembly flawlessly without requiring Webpack or Copy plugins in package.json.
See the how-to article here: Creating a new SciChartSurface and loading Wasm

Deploying Wasm (WebAssembly) and Data Files with your app
If you receive an error message when running your app, you may not
have deployed the Wasm (WebAssembly) or data files correctly. Below
are some steps on how to resolve that.
Error: Could not load SciChart WebAssembly module. Check your build
process and ensure that your scichart2d.wasm, scichart2d.data and
scichart2d.js files are from the same version
Option 1: Package Wasm & Data Files with WebPack (or similar)
...
Option 2: Load Wasm from URL with SciChartSurface.configure() or
useWasmFromCDN()
...
We've packaged a helpful function that
automatically loads the latest & correct version of SciChart's Wasm &
Data files from CDN.
To use this, instead of calling
SciChartSurface.configure() passing in a URL, call
SciChartSurface.useWasmFromCDN().
import {SciChartSurface} from "scichart/Charting/Visuals/SciChartSurface";

export async function initSciChart() {
    // Call this once before any SciChartSurface is shown.
    // This is equivalent to calling SciChartSurface.configure() with the CDN URL (JSDelivr)
    SciChartSurface.useWasmFromCDN();
}


text:
Q: How much air needs to be displaced to generate an audible sound? I'm reading a book where in one scene a wizard/alchemist teleports a scroll after reading.

He folded the parchment carefully and muttered a single cantrip. The note vanished with a small plop of displaced air, joining the others in a safe place.

That made me wonder, how much air would needed to be displaced so the air rushing-in creates any sound at all. Is an audible "plop" sound even possible?

A: I suggest a totally different approach. But it's only a partial approach with much guesswork, too.
The ear is able to perceive 20 µPa. (at 2 kHz). Of course you could calculate some pressure changes at the closing void, but these actually have nothing to do with the sound pressure at your ear drum.
Let's do some energy calculations. 20 µPa at 1 cm² area at your eardrum corresponds to $10^{-17} W$. Your ear needs $0.1 s$ integration time at this sound pressure to generate a usable signal.
So $10^{-18} J$ is the minimum energy which can be perceived.
A void will free some energy when collapsing. We can calculate the order of magnitude easily, if we assume a void of which one dimension is significantly smaller than the other two.
then the force acting on the big surface of the void calculates:
$F=p \cdot A$. The stored energy derives from the thickness $d$.
$E=d \cdot p \cdot A$
If we assume the pop happening direct in front of our eardrum directing all sound energy over the eardrum by generating only audible frequencies, we can calculate the absolute minimum size of the void.
This results in a void of $10^{-23} m³$ or $10^{-14} mm³$. which is in fact a very small volume.
Update: Estimations start here. The values above are hard limitations due to energy considerations. it is impossible to generate audible sounds with smaller imploding volumes.
Now we could start estimating how much bigger this cube has to be to compensate for most of the energy lost through

*

*distance between source and sink of the signal

*efficiency of converting potiential energy into sound in audible range

If that signal emerges 1 m from your ear you need 120000 times the energy, because your eardrum only catches the energy passing through $1 cm²$ of the surface of a sphere with 1m radius.
If you assume 1% efficiency, which is not uncommon for electrical speakers being much smaller than the wavelength which is desired to be emitted, the factor increases to 12,000,000. This sums up to $10^{-8} mm³$, which is a cube with $4.6 µm$ length or whatever exension you may derive from that.
Update These consideration has already some uncertainties.

*

*The thin void will produce a high directivity when collapsing. Hence, depending on the place of your ear, the factor 120000 will increase or decrease vastly.

*The expansion of the air into the void may happen really fast. Consider an average particle speed of 500 m/s and assume expansion with at least half that speed. with a thickness of approx. 0.1 mm (parchment) the void will close in 0.1 µs. When generously assuming twice the time for building up and depleting the pressure at the collision front, we get a pulse duration of 0.2 µs, which yields a base freqency of 0.5 MHz.which will force a spreadened spectrum with much energy in high frequencies. (Floris in a comment noted correctly that a square pulse will always contain audible frequencies) Which means most of the generated sound energy will be really far from audible spectrum. This will be even worse if assuming such small voids as in my example calculation. So 1% conversion efficiency may be very optimistic. Efficiency concerning the audible freqency range only may be several orders of magnitude below 1%.

I guess it may be useful to take a closer look to the mechanisms of a collapsing void. I strongly oppose to a speaker membrane as a valid model for these mechanics, primarily because of the high mass of a speaker membrane.
Update I want to dive a little bit into the gas dynamics of the closing void. How is the air being accelerated when the void appears?
Initially there's a sharp border between 1 atm air and vacuum. Hence there's about 100000 Pa difference. Air molecules roughly have a mean distance of 33 nm and the first layer of molecules at that border is accelerated by the pressure. A single molecule uses an area of $0.9 \cdot 10^{-15} m²$. Therefore the force on that molecule is $10^{-11} N$. Assuming a molecule mass of 28 u (Nitrogen) the resulting acceleration is $1.9 \cdot 10^{15} \frac{m}{s²}$.
Let's further assume, the acceleration will rapidly decrease due to expansion to a thousandth of this to $1.9 \cdot 10^{-12} \frac{m}{s²}$. Then the void of 0.1 mm will close in 0.2 ns.
I have much doubt concerning this estimation because I have no idea how a front of pressurised gas in a vacuum really will behave. But I think the void will close with at least the speed of sound, perhaps even a lot of faster. Which again leads me to the assumption, that the very most of the energy will be converted to inaudible ultrasound.
Update I try to explain why I consider the speed of closing the void critical for audibility of the event.
If we consider the first estimation (closing of the void within 0.2 μs), and estimate some overshoot, which extends the duration of the event to 0.4 μs, we can do a fourier transform. (Kudos to Floris for this suggestion)
$\mathcal{F}(\operatorname{rect}(a t))(f)= \frac{1}{|a|}\cdot \operatorname{sinc}\left(\frac{f}{a}\right)$
with $a = 2.5 \cdot 10^6$ we get
$0.4 \cdot 10^{-6} \operatorname{sinc}\left(\frac{f}{2.5 \cdot 10^6}\right)$
The first zero crossing is at 400 kHz, which is an order of magnitude above the audible range which means we can assume a nearly flat spectrum in that range. If we try to integrate the power spectrum,
$\int\limits_{20}^{20000} 0.16 \cdot 10^{-12} \operatorname{sinc}^2\left(\frac{f}{2.5 \cdot 10^6}\right) df$
we better use an approximation, because neither sinc cannot be integrated analytically nor its square (please correct me if I'm wrong)
It yields roughly $\frac{20000}{2.5 \cdot 10^{6}}$ (but here I'm not so sure).
In my opinion this means, that only 0.8% of the signal energy will be in the audible range. If we confine the range to the most sensitive part around 2 kHz, assuming a reduced bandwidh of 1 kHz, the perceived energy declines to 0.04% of the whole signal.
If for the whole thing, the pulse length (time for collapsing the void) is reduced further, the audible part of the emitted sound energy declines as well.
more number juggling to come

A: Sound intensity is measured on the dB scale, which is a logarithmic scale of pressure. The "threshold of hearing" is given by the graph below:

which tells you (approximately) that 0 dB is about "as low as you go" - the "threshold of hearing". Note that sound signal drops off with distance - we will have to take that into account in what follows.
If you suddenly create a vacuum of a certain volume V, then air rushing in to fill the void will create a (negative) pressure wave traveling out - for simplicity's sake let's make the void spherical, and "listen" to the plop at a distance of 1 m (where the observer might be standing when the parchment disappears).
The problem we run into is that the pressure "step" is not a single frequency tone, it's in effect the sum of many frequencies (think Fourier transform) - so we would need to estimate what percentage of the energy is in the audible range.
That's hard to do, and we are talking about magic here - so I am going to simplify. A pressure level of 0 dB corresponds to $2\times 10^{-5} Pa$ - that's a really small pressure.
Parchment is thick - let's say 0.2 mm, or about double the thickness of conventional paper (a stack of 500 sheets is about 5 cm thick, so I estimate that at 0.1 mm per sheet). For a letter size piece of paper, 30 x 20 cm2, the volume is 12 cm3. If that was a sphere, that sphere would have a radius of ${\frac{12 cm}{(4/3) \times \pi}}^{1/3}$ = 1.4 cm.
If that sphere was suddenly "gone", an equal volume of air would have to rush in. At a distance of 1 m, the apparent pressure drop would be
$$\begin{align}\\
\Delta P &= \frac{r_1^3}{r_0^3}\times P_{ambient}\\
&=0.3 Pa\\
\end{align}$$
That is a Very Loud Pop - about 80 dB. Even if we argue that only a small fraction of this pressure ends up in the audible range there is no doubt in my mind you would hear "something".
So yes, you can hear that parchment disappearing. No problem. Even if some of my approximations are off by a factor 10 or greater. We have about 5 orders of magnitude spare.
AFTERTHOUGHT
If you have ever played with a "naked" loudspeaker (I mean outside of the enclosure, so something like this one from greatplainsaudio.com):

you will have noticed that the membrane moves visibly when music is playing - and as you turn the volume down, the movement becomes imperceptible while you can still hear the sound. That, in essence, is what you are doing here. The sound level you are getting would be similar to the sound level recorded when you move a loudspeaker membrane by by about 0.2 mm. I can guarantee you would hear it. Might be fun to do the experiment... I'll have to see if I have an old one lying around and I might try it myself.
UPDATE no time to play with loudspeakers, but thought I would do the calculation "what is the smallest movement of air that results in a sound the human ear can hear?".
Again this is going to be approximate. Let's assume an in-ear headphone with a 8 mm membrane  coupling into a 3 mm ear hole. Just from the ratio of areas, we can see that sound levels will amplify - a movement of $x$ by the membrane will move the air in the earhole by $x\left(\frac{8}{3}\right)^2$. The equation that connects the movement of the membrane to the pressure produced is:
$$\Delta p = (c\rho\omega )s$$
In words: the change in pressure is the product of speed of sound, density of air, frequency, and amplitude of vibration.
Using $c = 340 m/s$, $\rho = 1.3\ kg/m^3$, $\omega = 2\pi\times1\ kHz$, and $\Delta p = 2\times10^{-5} Pa$ (the limit of audible sound at 1 kHz), we find that
$$s = 7.2\times10^{-12}m$$
And that's before I take the factor $\left(\frac{8}{3}\right)^2$ into account, which would lower the required amplitude to a staggering $1.0\times10^{-12} m$ - that's smaller than the movement of an atom.
You can see the derivation of the above at http://www.insula.com.au/physics/1279/L14.html and if you look for problem # W4 on that page you will find the calculation for a pressure level of 28 mPa at 1 kHz giving 11 nm displacement amplitude. Given that the limit of detectable sound level is about 1000x smaller, my numbers above are quite reasonable.
So the real answer to your "headline" question ("how much air needs to be displaced to generate an audible sound") is
The equivalent of one layer of atoms is more than enough
Impressive, how sensitive the ear is. And bats and dogs have even better hearing, I'm told.

A: Kudos to the question-asker for thinking about everything they read! :-)
I was pleased to note that the author of the previous answer mentioned "audible" means "audible" to the human ear. Note also that "audible" also depends on the frequency a bit...generally-speaking, as humans, for high-frequency sounds we need them a little more intense if we're going to hear them!
Maybe I'm thinking too simplistically, but the threshold of hearing for humans is a change in pressure of about 20 micropascals, (that's at a frequency of 1000 Hz, or close to so-called "soprano C", for interest). This pressure change corresponds to a change in volume of about 0.00002 of the initial volume. Since the volume of a sheet of paper is about 5.846x10^{-6} cubic metres, and the volume of the room is maybe 75 cubic metres (assuming an ordinary-size room), I get that the sudden disappearance of a piece of paper would change the volume of the room by about 6x10^{-8} of its volume. So it wouldn't actually result in an audible pressure change.
That sounds wrong to me, because, like the other question-answerers, I would also expect that you could hear a piece of paper disappear (crazy thought!). Maybe one could also think about it in terms of conservation of energy. If a piece of paper disappeared, you'd surely have to get a sound, because the energy that used to make up the piece of paper would have to "go somewhere". Perhaps we could work out the associated sound-level from that? This is fun!

A: The following is not my own research, but taken from Randall Munroe' wonderful what-if "Glass Half Empty" where he describes a glass of water, bottom half filled with water, top half filled with vacuum (or: nothing).
(edited to exclude other two glasses)

But what if the empty half of the glass were actually empty—a vacuum? (Even a vacuum arguably isn't truly empty, but that's a question for quantum semantics.)
The vacuum would definitely not last long.
We'll imagine the vacuums appear at time t=0.
For the first handful of microseconds, nothing happens. On this timescale, even the air molecules are nearly stationary.
t=50µs
For the most part, air molecules jiggle around at speeds of a few hundred meters per second. But at any given time, some happen to be moving faster than others. The fastest few are moving at over 1000 meters per second. These are the first to drift into the vacuum.
t=150µs
While the water on the surface starts to boil away, the air rushing in stops it before it really gets going.
t=400µs
After a few hundred microseconds, the air rushing into the glass fills the vacuum completely and rams into the surface of the water, sending a pressure wave through the liquid. The sides of the glass bulge slightly, but they contain the pressure and do not break. A shockwave reverberates through the water and back into the air, joining the turbulence already there.
t=1ms
The shockwave from the vacuum collapse takes about a millisecond to spread out [several centimeters]. In a few more milliseconds, it reaches the humans' ears as a loud bang.

While he's assuming a vacuum inside a glass on top of water instead just in the air, he also concludes a loud bang will happen for the amount of vacuum he chose. (half a cup).
I'll take this as support for Floris' calculations.

A: For practical purposes, we can assume that the disappearance of a 1.2 cubic cm (1.2 ml) object gives a waveform that's very similar to the sudden appearance of a 1.2 ml object, except for the sign of the resulting pressure wave.
Now we do have a simple means to create that effect: setting off gunpowder will suddenly produce a lot of gas. You'd need just a few milligrams. Setting of one gram of gunpowder would produce 300 ml of gas, but also produce a sound that can reach 140 dB (!)
So we're basically looking at a sound wave that's 250x less energetic then 140 dB. Since dB are a logarithmic scale, we need to deduct 10*log(250), which is about 25 dB. So the sound would be 115 dB. Still quite loud, that.
The main challenge with this statement is that decibels work well to describe continuous power, but a wave like this is very very short. You can't even average the energy over one period of the wave, because there's no periodicity.

A: This only a partial answer.   Your understanding of acoustics needs to be enhanced a bit: for one thing, an "audible sound" means there are frequencies our ear responds to.  This means roughly 20 Hz to 20 000 Hz .  Now, if we assume (I know, I know :-) ) that the parchment left a vacuum in its place of some small but specified volume, and we assume a spherical cow with a uniform... dammmit!  just a spherical vacuum "bubble,"  then I believe there are some algorithms for calculating the amplitude of the shock wave generated as air rushes in.  Most certainly this shock wave can generate frequencies in the audible range and of an amplitude detectable by a nearby ear, but as sadly my name isn't Randall I don't have a numerical estimate.


text:
Q: How create 'tar.gz' package without root directory? I need create tar.gz package without root directory.
Now I have tree:enter image description here
Result example:enter image description here
I useed gradle task, which created tar.gz package with cfg directory:
plugins.withType(DistributionPlugin) {
    distTar() {
        into('cfg') { from 'cfg' }
            compression = Compression.GZIP
            extension = 'tar.gz'
    }
}

A: If you need to remove the root level directory from the produced archive, you can use Tar.eachFile API to change/alter the target file paths, as follows:
distTar {
    // Alter file path to remove root level directory
    eachFile { file ->
        String path = file.relativePath
        file.setPath(path.substring(path.indexOf("/")+1, path.length()))
    }
}

(I did not find any method or property from the Tar task API to implement this in a nicer way)


text:
Q: Any way for automated user profiles restore We had a Windows 2012 R2 server on a VPS hosting with Terminal services installed and about 40 active users.
Recently we encountered a system crash without any possibility to restore, so we managed to backup all user data and decided to reinstall the system.
Is there any automated way to grab user data and create user profiles not to do it manually? Some WSH script, migration tool, whatever.
Let's say, read directory content, create a user per profile with default password, and then copy all their desktop environments, settings, documents etc
I'm not very familiar with the Windows administering, thank you for understanding.
If possible I'd appreciate some script code snippet

A: Solved for my own. Sorry for not well-commented script, hope help to somebody
Creates users according to backed up user directory (process exceptions like Default User, Administrator etc), create home directories for them, migrate backed up user directories.
Const WAIT_ON_RETURN = True
Const HIDE_WINDOW = 0
Const USER_ROOT_UNC = "C:\Users" 'Set Home Folder Location Here
On Error Resume Next

Function CreateUser(strUser, strPass)

    Set objShell = CreateObject("Wscript.Shell")
    Set objEnv = objShell.Environment("Process")
    strComputer = objEnv("COMPUTERNAME")

    Set colAccounts = GetObject("WinNT://" & strComputer & ",computer")

    Set objUser = colAccounts.Create("user", strUser)
    objPasswordNoChangeFlag = objUser.UserFlags XOR ADS_UF_PASSWD_CANT_CHANGE
    objUser.Put "userFlags", objPasswordNoChangeFlag
    objUser.SetInfo

End Function

Function CreateCatalog(strUser)
    Dim WshShell, WshNetwork, objFS, objServer, objShare

    Set WshShell = Wscript.CreateObject("Wscript.Shell")
    Set WshNetwork = WScript.CreateObject("WScript.Network")
    Set objFS = CreateObject("Scripting.FileSystemObject")
    Call objFS.CreateFolder(USER_ROOT_UNC & "\" & strUser)
    Call WshShell.Run("cacls " & USER_ROOT_UNC & "\" & strUser & " /e /g Administrators:F", HIDE_WINDOW, WAIT_ON_RETURN)
    Call WshShell.Run("cacls " & USER_ROOT_UNC & "\" & strUser & " /e /g " & strUser & ":C", HIDE_WINDOW, WAIT_ON_RETURN)
End Function

Function CopyDirs(userName)
    arrCopyDirs = Array("Desktop", "Documents", "Downloads", "Links", "Pictures", "Videos", "Music")
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    For Each dirName in arrCopyDirs
        currentDirectory = objFSO.GetAbsolutePathName(".")
        copiedDirectory = currentDirectory & "\" & userName & "\" & dirName
        destDirectory = USER_ROOT_UNC & "\" & userName & "\" & dirName
        objFSO.CopyFolder copiedDirectory, destDirectory
    Next
End Function

Function EnumerateCatalog()
    Dim objFSO, objFolder
    Dim arrNotUsers, arrCopyDirs
    arrNotUsers = Array("Default User","MediaAdmin$","Administrator","MSSQL$MICROSOFT##WID","All Users","Plesk Administrator","Default","Public","ServerAdmin$")

    Set objFSO = CreateObject("Scripting.FileSystemObject")
    For Each objFolder In objFSO.GetFolder(".").SubFolders

        If Not Ubound(Filter(arrNotUsers, objFolder.Name)) > -1 Then
            Call CreateUser(objFolder.Name, "12345qweasdzxc")
            Call CreateCatalog(objFolder.Name)
            Call CopyDirs(objFolder.Name)

        End If

    Next
End Function

Call EnumerateCatalog()


text:
Q: How to format family tree from array I'm trying to create a pedigree and I've got the function to both build and to display the data, I'm just not sure how to format it correctly on output.
I'm trying to work with this css/html http://jsfiddle.net/bZGFA/32/
My array output of the tree information looks like this:
Array(
 [id] => IJ6wF
 [mother] => Array (
     [id] => BzOqN
     [mother] => Array (
         [id] => 1G3Pl
         [mother] =>
         [father] =>
     )
     [father] => Array (
         [id] => xWDlH
         [mother] =>
         [father] =>
     )
 )
 [father] => Array (
     [id] => Rstov
     [mother] =>
     [father] =>
 )
)

I'm using a recursive function to build the array.  I'm using the following function I found on stackoverflow to display the array.

function displayArrayRecursively($arr, $indent='') {
    if ($arr) {
        foreach ($arr as $value) {
            if (is_array($value)) {
                //
                displayArrayRecursively($value, $indent . '--');
            } else {
                //  Output
                if (!empty($value)) {
                    echo "$level $indent $value \n";
                }
            }
        }
    }
}

I'm lost on how I can configure the function to build the table.  Any help would be amazing.  Thanks!

A: printTree($array) {
    $out = "
" . "". $array["id"] . "";

    if (array_key_exists("mother", $array) || array_key_exists("father", $array)) {

        $out .= "
";

        if (array_key_exists("mother", $array)) {
            $out .= printTree($array["mother"]);
        }

        if (array_key_exists("father", $array)) {
            $out .= printTree($array["father"]);
        }

        $out .= "
";
    }

    $out .= "
";

    return $out;
}

While in the html use:

    <?php echo printTree($array); ?>


text:
Q: Meaningful concise method naming guidelines Recently I started releasing an open source project, while I was the only user of the library I did not care about the names, but know I want to assign clever names to each methods to make it easier to learn, but I also need to use concise names so they are easy to write as well.
I was thinking about some guidelines about the naming, I am aware of lots of guidelines that only care about letters casing or some simple notes. Here, I am looking after guidelines for meaningful but yet concise naming.
For example, this could be part of the guidelines I am looking after:

*

*Use Add when an existing item is going to be added to a target, Use
Create when a new item is being created and added to a target.

*Use Remove when an existing item is going to be removed from a target,
Use delete when an item is going to be removed permanently.

*Pair AddXXX methods with RemoveXXX and Pair CreateXXX methods with
DeleteXXX methods, but do not mix them.

As the above samples show,I would like to find some online material helping me with naming methods and other item complying with English grammar and word meanings.
The above guidance may be intuitive for native English speakers, but for me that English is my second language I need to be told about things like this.

A: The temptation to codify a style or convention for naming can in some cases lead to habits that are considered poor practice nowadays, such as using Hungarian Notation for example. The simple answer is to forget about naming convention and style as if it were some separate thing to be determined separately, and instead to focus on naming everything in your system based on what it actually represents. Method names will be naturally tend to be concise if you limit the functionality of each method so that it does only one thing notionally, and if your method name actually describes the one thing that the method is supposed to do.
Variables, fields, class and file names are something else.  I'd suggest that if the variable names are getting too long, then you are trying to either describe these items in too great a detail, or they represent something complex that should either be broken into smaller parts, or perhaps described in a more abstract manner.
At the end of the day, you want to avoid ugly code with names that take up an entire row, or that are so glib as to rob them of their value.

A: For me, finding a good name for something always comes back to thinking of it as an object that has to justify its existence. Ask yourself:

*

*What does the class/method/variable do, i.e. what is its wider purpose and what is it for?

*What specifically about its purpose does it need to communicate, i.e. what is the essential part that the name needs to have in it?

Most developers would agree that readability is always of paramount importance when it comes to naming. Don't just write code so that you know what you mean while you're writing it, write it so that someone looking at the code for the first time at some point in the future knows what you meant without having to think too much. You'll write the code just once, but during its lifetime it will most likely have to be edited many times and read even more times.
Code should be self-documenting, that is, your naming should make it obvious what something does. If you need to explain what a line of code does in a comment, and renaming things doesn't improve it enough, you should seriously consider refactoring that line into a new method with an appropriately descriptive name, so that reading the original method, the new method call describes what's happening. Don't be afraid to have long names; of course you shouldn't write novels in class/method/variable names, but I'd rather have a name be too long and descriptive than too short and I need to figure out what it does by looking under the hood. Except for some obvious exceptions like x/y coordinates and commonly used acronyms, avoid single-character names and abbreviations. Calling something "bkBtn" instead of "backButton" may have had a purpose back when names were limited to 8 characters and dinosaurs roamed the earth, but in these days with code-completion there's really no excuse for abbreviating.
As much as your language allows, make your code read like an English sentence. Objects use nouns, methods use verbs. Boolean methods typically start with "is", but there are many other options that convey the meaning even better, depending on the use case, such as "can", "should", or "does". Of course, not all languages can be as good as Smalltalk at this, but some symbols are generally understood to be parts of the sentence. Two Smalltalk conventions I personally like to take into other languages as much as possible are prefixing the name of loop parameters with "each", and prefixing method parameters with the article "a" (or "an", or "some" for collections). This may not be a common standard in Java, and anyone is welcome to ignore this bit, but I find that this greatly enhances the readability of code. For instance (example in Java):
public boolean shouldConsiderAbbreviating(List<String> someNames) {
  for (String eachName : someNames) {
    if (isTooLong(eachName)) {
      return true;
    }
  }
  return false;
}

This should be readable to people with just a bit of knowledge of Java as something like this:
To determine whether you should consider abbreviating a list of some names (which are strings), iterate over some names, and for each name, determine whether it is too long; if so, return true; if none is too long, return false.
Contrast the above code with just naming the argument strings and the loop variable string, especially in a more complex method. You'd have to look closely to see the difference instead of the usage being obvious from a glance at the name.

A: Naming. One of the hardest things about software development :)
When I name something, here is my set of priorities:

*

*Follow the idioms of the language. Ruby likes underscores. JavaScript likes camel case. Whatever language you're in is the convention to follow.

*Reveal the intent of the API. It's not "send_http_data" it's "post_twitter_status".

*Avoid leaking implementation details. Say, prefixing a variable with a type.

*Do not use more characters than necessary without breaking the previous  guidelines.

Obviously this is a rather simplistic approach. Naming is nuanced.
For further research, I would recommend reading The Art of Readable Code, as it provides some excellent, succinct advise on method naming. For even more research I cannot more highly recommend Bob Martin's Clean Code.

A: Do not worry about the length of method names. Make sure the method names clearly reflect what they are doing. This is paramount to anything else. If you feel that the method name is too long, use a thesaurus to find a shorter word that means the same thing. For example use Find instead of Retrieve.
Also what is just as important is the names you choose for your classes. These provide lots of context when looking at method names. A method signature like so:
public User Find(int userId);

is easier to understand than:
public Person Find(int personId);

because the context obtained from the class name User tells the programmer that Find() is for locating a specific type of person, the user of your system. The version that uses the Person class doesn't give you any context about why you would even need to use the method in the first place.

A: Finding a good naming is always a compromise between more factors. You will never be fully satisfied.
That said, even if your native language is not that way, consider that English is the language whose programming languages tokens are formed. Using English-like syntax makes code reading more "fluent" since there are no "broken reading rules" every time a keyword is found.
In general, consider things like object.method(parameters) to match a scheme like subject.verb(complements).
The key point, if you have to support generic programming, is choose a good and consistent set of "verbs" (especially the ones that need to be used in generic algorithms).
About nouns, classes should be named for what they are (in term of concept), while objects for what they are for.
That said, between list.add(component) and component.add_to(list) prefer the first. In general "active transitive" verbs better represent actions respect to their passive or reflexive counterparts. Unless design constrains foce you.

A: *

*Assume English, unless every developer that ever works on this code will speak the same non-English language.

*Study commonly accepted naming conventions and styles.  Your guiding principle should be clarity.  Styles differ by programming language.

*There isn't anything you can do with the naming that will make it easier to understand the relationships between the various objects in your code.  For that, you still need well-written comments and documentation.

A: Look at how others on your platform do it - some of the bigger players might even have code style and naming guidelines.
Some platforms prefer short names (for instance, in the Win32 C API _tcsstr is the function to find a string within a string - isn't it obvious?), others go for readability in favor of brevity (in Apple's Cocoa framework for Objective-C, the method to replace a substring in a string with another string and return the result as a copy is called stringByReplacingOccurrencesOfString: withString:). I find the latter vastly easier to understand, and only moderately harder to write (especially with code completion).
Since you read code more often than you write it (doubly true for open source libraries), and reading is harder than writing, optimize for reading. Optimize for brevity only last, and take only as much away as is possible without diluting clarity.

A: *

*Use prefix. If a bunch of methods are used to do something similar or can be in some way grouped together, put a common prefix before their names to show what these methods have in common.

*Do not use unclear abbreviation if you want others to understand the names instantly (important in API naming)


text:
Q: sorting algorithms runtime analysis I've been trying to compare the runtimes of selection sort,  quick sort and merge sort and so far, what I got is this table:
n       S(n)    S(n))/n^2   Q(n)    (Q(n))/(nlog2 n)    M(n)    M(n))/(nlog2n)
1000    1.4     1.40000E-06 0.104   1.04357E-05         0.151   1.51518E-05
2000    5.41    1.35250E-06 0.223   1.01680E-05         0.327   1.49100E-05
4000    21.23   1.32688E-06 0.486   1.01540E-05         0.704   1.47086E-05
8000    84.15   1.31484E-06 1.036   9.98783E-06         1.496   1.44226E-05
16000   336.47  1.31434E-06 2.179   9.75151E-06         3.177   1.42178E-05
32000   1322.99 1.29198E-06 4.673   9.75767E-06         6.709   1.40090E-05

n is the size of the array being sorted.
I know that S(n) is the total runtime of the sorting program. I just don't get why I'm being asked to divide this total, by its order (i.e S(n) is O(n^2)). And what these values represent or what information can I infer from these results (3rd, 5th, & 7th column)?
If anyone can briefly explain this to me, that would be greatly appreciated.

A: Knowing that something is O(n^2) is great, but it's not the whole story. As you probably know, big-O notation disregards pesky things like constant factors and lower-order terms. So it's a good guideline for how well something will scale, but doesn't tell you a lot about how well it will perform on real data. Your professor is trying to show you the constant factors involved. As you can see, SS has a constant factor that is about 1/10th of the other two. So for smaller inputs, (probably up to about 50 elements(since 50^2/10 ~= 50log2(50))) that might outweigh the O(nlogn) vs O(n^2) difference and make SS the better choice.
Edit: This table doesn't conclusively show that the algorithms are actually in the expected complexity classes. But the results you got do match what you would expect to see from O(n^2) and O(nlog2n) algorithms. So if you did the math to calculate the complexities of the algorithms, you could run a test like this one as a sanity check, but if there happened to be a log(log(log(n))) factor in one of them, you would never notice it unless you ran it on a mind-bogglingly large data set.
(even worse, you can make an exponential function or high-degree polynomial approximate a low-degree polynomial for a while and then skyrocket, and without showing mathematically that your algorithm has a certain complexity you can't really be sure you won't get bitten by something like that.)
These results should help by showing you that the n^2 and nlog2n estimates actually correspond to real runtimes, that you (probably) implemented the algorithms correctly since they're scaling as you would expect them to, and that some of the naive algorithms may not scale well, but they have good constant factors and that makes them well-suited for smaller problems.
Your Quicksort is probably implemented with singleton arrays as the base case, but you could possibly speed it up a bit by making arrays with fewer than 50 elements the base case and running insertion sort on those.


text:
Q: Class Inheritance with .NET EF4.1 + MySQL I'm trying to implement class inheritance in .NET using Entity Framework 4.1 and MySQL as database, with code-first approach. The model below works with SQL Server, but fails in MySQL with the following error:
Schema specified is not valid. Errors:
(11,6) : error 0064: Facet 'MaxLength' must not be specified for type 'mediumtext'.

The model is a classic simple example:
public abstract class Vehicle
{
    public int Id { get; set; }
    public int Year { get; set; }
}

public class Car : Vehicle
{
    public string CarProperty { get; set; }
}

public class Bike : Vehicle
{
    public string BikeProperty { get; set; }
}

public class Db : DbContext
{
    public DbSet<Vehicle> Vehicles { get; set; }
    public DbSet<Car> Cars { get; set; }
    public DbSet<Bike> Bikes { get; set; }
}

With SQL Server, it creates only a table named Vehicles with columns: Id, Year, Model and Discriminator; no tables for Cars or Bikes. In MySQL, the database is not even created (if I remove the "Car" class, it creates - so it's not a problem of permission or something like that).
Any help would be appreciate! Thank you.
UPDATE 1:
I tried using Table-Per-Hierarchy approach to the relationship, switching to the context below, but it gave me another error: Can't create table 'aimpa.#sql-da8_2c' (errno: 150).
public class Db : DbContext
{
    public DbSet<Vehicle> Vehicles { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Vehicle>()
            .Map<Car>(o => o.ToTable("Cars"))
            .Map<Bike>(o=>o.ToTable("Bikes"));
    }
}

UPDATE 2:
I've submitted this as a bug to MySQL development team, because I don't know what more can I do. It seems that it should work, but it doesn't. The permanent link is http://bugs.mysql.com/63920.
UPDATE 3:
I switched to NHibertnate 3.2, in order to test this. Seems to work just fine. I'll take a better look at this ORM, but I would prefer still staying with EF.
UPDATE 4:
In the official MySQL forum, I received a response telling that the fix for this bug is in review. Should be fixed soon.

A: I was faced with the same problem today, the difference is that I'm not relying on Code First to create the tables for me, I'm creating them manually as I go.
I have followed the description given here and I ended up on the same error as you, I have manually created a "Discriminator" field on my table and changed its type to MEDIUMTEXT but the provider insisted that I was somehow providing a MaxLength property, even though MEDIUMTEXT has no MaxLength like VARCHAR, I assume this must be a bug on the provider.
Well, to work around this I have used fluent API to manually tell the discriminator column name (which I just kept as "Discriminator") and values that EF should expect from the discriminator column, in your case this would be:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Vehicle>()
            .Map<Car>(m => m.Requires("Discriminator").HasValue("Car"))
            .Map<Bike>(m => m.Requires("Discriminator").HasValue("Bike"));
}

I've changed the type of my discriminator column to VARCHAR(50) with no apparent problem, it's working well for me now. The alternative for me would be to migrate to another ORM which is just too much work, I'll wait for the next versions of the MySql provider and test if they have fixed this, meanwhile I'll stick to this solution.


text:
Q: The JSX import source cannot be set without also enabling React's "automatic" JSX transform I'm trying to use Material UI icons inside my Qwik website.
I used the answers of If possible, how to use MUI with Qwik framework? and here's my Icons.jsx file:
/** @jsxImportSource react */

import { qwikify$ } from '@builder.io/qwik-react'
import AcUnitIcon from '@mui/icons-material/AcUnit'
import MenuIcon from '@mui/icons-material/Menu'
import AddIcon from '@mui/icons-material/Add'
import RemoveIcon from '@mui/icons-material/Remove'
import DriveFileRenameOutlineOutlinedIcon from '@mui/icons-material/DriveFileRenameOutlineOutlined'

export const MuiAcUnitIcon = qwikify$(() => <AcUnitIcon />)
export const MuiMenuIcon = qwikify$(() => <MenuIcon />)
export const MuiDriveFileRenameOutlineOutlinedIcon = qwikify$(() => <DriveFileRenameOutlineOutlinedIcon className='text-white' />)
export const MuiAddIcon = qwikify$(({ sx, className }) => <AddIcon sx={sx} className={className} />)
export const MuiRemoveIcon = qwikify$(({ sx, className }) => <RemoveIcon sx={sx} className={className} />);

Everything works great in the development. But when I want to build the app for the production environment using npm run build or npm run preview, I get this error:

The JSX import source cannot be set without also enabling React's "automatic" JSX transform

And every component that has used the MUI icon would render as a blank space on my website.
I also tried How to fix vite warning: The JSX import source cannot be set?, but it made no difference.
Here's the issue that we wrote for the Qwik team. And here's a reproducable repository.
What should we do to fix this?


text:
Q: Rotation on extension-field I have corrected the question in the following.

For $x_1$ and $x_2$ real vectors which span $V=\mathbb{R}x_1\oplus \mathbb{R} x_2$.
we have a rotation $R$ on $V$ given by
\begin{eqnarray*}
R\begin{pmatrix}x_1\\x_2\end{pmatrix}=\begin{pmatrix}
\cos\theta&\sin\theta\\
-\sin\theta&\cos\theta
\end{pmatrix}\begin{pmatrix}x_1\\x_2\end{pmatrix}
\end{eqnarray*}
Now, consider $V^\mathbb C=\mathbb C\otimes_\mathbb{R}V=V\oplus iV$, it is $2$-dimensional $C$-vector space.
The question is:
How to choose a $\mathbb C$-basis such that $R$ acts on $V^\mathbb C$
as
\begin{pmatrix}
e^{i\theta}&\\
&e^{-i\theta}
\end{pmatrix}?

A: The first column of $A$ must be a non-zero member of the kernel of the matrix
$$
\pmatrix{
\cos\theta&\sin\theta\\
-\sin\theta&\cos\theta
} - e^{i\theta}\pmatrix{1&0\\0&1} =
\pmatrix{
\frac{1}{2}\left(-e^{i\theta} + e^{-i\theta}\right) & \sin \theta\\
-\sin \theta & \frac{1}{2}\left(-e^{i\theta} + e^{-i\theta}\right)
}\\
= \pmatrix{
i\sin \theta & \sin \theta\\
-\sin \theta & i\sin \theta
}
$$
Similarly, the second column of $A$ must be a non-zero member of the kernel of the matrix
$$
\pmatrix{
\cos\theta&\sin\theta\\
-\sin\theta&\cos\theta
} - e^{-i\theta}\pmatrix{1&0\\0&1} =
\pmatrix{
-i\sin \theta & \sin \theta\\
-\sin \theta & -i\sin \theta
}
$$


text:
Q: What is the purpose of UntypedFormBuilder, UntypedFormControl etc types introduced in Angular 14 When you run the update schematic to upgrade to Angular v14, it replaces all of your FormGroups, FormControls etc with the Untyped counterparts. However, if you discard all those changes, there are no errors, because it defaults the value prop of FormGroups and FormControls to any. So my question is, why does the schematic make these changes, when the existing types don't break anything?
The schematic log message says the following:

As of Angular version 14, Forms model classes accept a type parameter, and existing usages must be opted out to preserve backwards-compatibility

However, existing Forms classes are already backwards-compatible. Of the many form groups and controls in my app, when they are left unchanged, there are no typescript errors, and no build errors.
To make my question perfectly clear, why does the schematic introduce all these changes when they are not required?

A:
because it defaults the value prop of FormGroups and FormControls to any

Well, It's not true in all cases. It depends on how you define your form group. For instance, if you declare your form group like the below code and then fill it in your constructor, then your form group value type, would be any.
public formGroup: FormGroup;

public constructor(private formBuilder: FormBuilder) {
  this.formGroup = this.formBuilder.group({
    ...
  });
}

But if you instantiate your form group right after declaration then your form group value would have a specific type and maybe your code would break.
public formGroup = this.formBuilder.group({ ... });

public constructor(private formBuilder: FormBuilder) {}


text:
Q: Do Flurry Ads from AppSpot work in the Xcode simulator or just on the device I'm about to start working with Flurry, can I expect the ads to display in the simulator?

A: You can - check out http://support.flurry.com/index.php?title=Publisher/Code for integration instructions.
No special setup is required to see ads render in the simulator vs on a device.

A: I recently integrated it into our project and I can confirm to you that the ads do indeed show up in the simulator. However I had only the 5.1 Simulator available when developing and noticed issues with a device which had iOS 4 installed on it. Below iOS 5, Flurry Appspot might not be supported...


text:
Q: Lightbox with HTML content covering whole page I know there are many many lightbox plugins.
What I am looking for is a lightbox plugin that supports HTML content and has a full page option(covering the whole body/page).
My HTML content in the lightbox won't cover the whole page but the box background should cover the whole page. I know I could do this myself but it's for a small project and doing everything by myself and optimizing the lightbox for responsive would be too much for that project.
Thanks in advance for your suggestions.

A: It sounds like fancyBox would be a good option for you. It's a highly extensible Lightbox alternative nthat supports HTML content, and even supports the ability to do full-page popups by specifying 100% on the width and height parameters:
$.extend(this, {
  aspectRatio : false,
  type    : 'html',
  width   : '100%',
  height  : '100%',
  content : '
Full-screen
'
});

There's a demo page showcasing the functionality here, and in fact one of the examples showcases exactly what you are looking for here.
Hope this helps! :)


text:
Q: Getting Angular UI to work I've just installed Angular UI and I'm having trouble to make it work. Here are the stepts I followed:
index.html (Angular v1.0.1, AngularUI v0.2.1)
<script src="scripts/vendor/angular.js"></script>
<script src="scripts/vendor/jquery-1.7.2.js"></script>
<script src="scripts/vendor/jquery-ui-1.8.18.js"></script>
<script src="scripts/vendor/bootstrap.js"></script>
<script src="scripts/vendor/angular-ui.js"></script>

app.js
var publicApp = angular.module('publicApp', ['ngResource', 'ui'])

my html
<input name="dateField" class="datepicker" value="Click Here for Datepicker" ui-date>

And I get this error:
TypeError: Object [[object HTMLInputElement]] has no method 'datepicker'

Using the JS console in chrome this works:
$('.datepicker').datepicker()

What am I doing wrong?

A: If I'm not mistaken you need to include jQuery before AngularJS / angular-ui files.
Here is the jsFiddle with the angular-ui date picker working: http://jsfiddle.net/pkozlowski_opensource/aGpNf/6/


text:
Q: Embbeding QgsLayoutDesignerInterface in plugin widget using QtDesigner and PyQGIS Following the example of getting the QGIS canvas in a plugin window (as described here), I'm trying to add the QgsLayoutDesignerInterface into a plugin widget.
My goal is to simply display (no edit settings needed) a map layout in a plugin widget as soon as the related map is chosen from a combobox (see image below).
Then the layout (added to the project via the project.layoutManager) can wether be directly exported as a pdf file or opened and edited in the main LayoutDesigner (no help needed for this part since I already implemented it)

I tried to promote the QWidget as a QgsLayoutDesignerInterface class to display my automated layout but I get the following error message TypeError: qgis._gui.QgsLayoutDesignerInterface represents a C++ abstract class and cannot be instantiated

A: Based on this quote from your question:

My goal is to simply display (no edit settings needed) a map layout in
a plugin widget as soon as the related map is chosen from a combobox
.

My guess is that you don't want the entire layout designer interface embedded in your widget, just the layout and associated items.
Because the QgsLayout class inherits from the QGraphicsScene base class, You can create a QGraphicsView object, and display a layout inside it by calling the setScene() method, and passing a QgsPrintLayoutObject.
Below is a basic example which you can adapt for your plugin (you can also run this in the Python console to test).
class MyDialog(QDialog):
    def __init__(self):
        QDialog.__init__(self)
        self.setGeometry(200, 200, 1500, 800)
        self.hbox = QHBoxLayout(self)
        self.side_panel = QWidget(self)
        self.side_panel.setMinimumWidth(300)
        self.cb = QComboBox(self.side_panel)
        self.layout_names = [l.name() for l in QgsProject.instance().layoutManager().layouts()]
        self.cb.addItems(self.layout_names)
        self.cb.currentTextChanged.connect(self.show_layout)
        self.hbox.addWidget(self.side_panel)
        self.layout = QgsProject.instance().layoutManager().layoutByName(self.cb.currentText()).clone()
        # Create a QGraphicsView
        self.view = QGraphicsView(self)
        self.view.setMinimumSize(800, 800)
        # Call setScene(), passing a QgsPrintLayout object
        self.view.setScene(self.layout)
        # Resize layout inside the viewport (just hardcoded here)
        self.view.scale(3, 3)
        self.hbox.addWidget(self.view)
        self.cb.setCurrentText(self.layout.name())

    def show_layout(self):
        layout_name = self.cb.currentText()
        self.layout = QgsProject.instance().layoutManager().layoutByName(layout_name).clone()
        self.view.setScene(self.layout)

dlg = MyDialog()
dlg.show()

Result:

An example with Qt Designer:

from PyQt5 import uic

Dlg, QtBaseClass  = uic.loadUiType('C:\\Path\\To\\layoutsDialog.ui')

class LayoutsDialog(QDialog, Dlg):
    def __init__(self, parent=None):
        QDialog.__init__(self)
        Dlg.__init__(self)
        self.setupUi(self)
        self.setGeometry(100, 100, 1400, 900)
        self.setWindowTitle('Display Layouts')

        self.layout_names = [l.name() for l in QgsProject.instance().layoutManager().layouts()]
        self.layoutCB.addItems(self.layout_names)
        self.print_layout = QgsProject.instance().layoutManager().layoutByName(self.layoutCB.currentText())
        self.layoutView.setScene(self.print_layout)
        self.layoutView.scale(3, 3)
        self.layoutCB.currentTextChanged.connect(self.show_layout)

    def show_layout(self):
        self.print_layout = QgsProject.instance().layoutManager().layoutByName(self.layoutCB.currentText())
        self.layoutView.setScene(self.print_layout)

dlg = LayoutsDialog()
dlg.show()


text:
Q: Javascript scope (or something) issue I have this fragment of Javascript. I need the variable highest_number later in the function and I can it generate fine. The problem is that highest_number seems to be unaccessable once the for loop ends (e.g after the closing } ).
function new_route(parts) {
    var highest_number = -1;

    alert(parts);
    if (parts[0] == "field") {}
    else if (parts[0] == "option") {
        //find last option input id
        var select_container = "container_" + parts[2];
        var thisContainer = document.getElementById(select_container);
        var optionsList = thisContainer.getElementsByTagName("input");

        for (var i = 0; i < optionsList.length; i++) {
            var option_parts = optionsList[i].getAttribute("id").split("_");

            if (option_parts[0] == "option") {
                alert(option_parts);
                if (option_parts[2] > highest_number) {
                    highest_number = option_parts[2];
                }
            }
        }
        alert(highest_number);

        var labelNode = document.createElement("label");
        var inputNode = document.createElement("input");
    }
}

Why is this happening?

A: You didn't provide all relevant information in the question, so I'm working from your question from the other day.
At least part of the issue is with getElementsByTagName('input') because it is including the submit button which doesn't have an ID.
So when you get to:
var option_parts = optionsList[i].getAttribute("id").split("_");

You're trying to do a .split() on null.
If you exclude elements in the loop that don't have an ID, it will work:
    for (var i = 0; i < optionsList.length; i++) {
             // if no ID, continue to the next item
        if( !optionsList[i].id ) continue;
        var option_parts = optionsList[i].getAttribute("id").split("_");

Side note. Please include relevant information in the question. It saves everyone time.
Here's a jsFiddle of your code in action. It is updated from the fiddle I posted before. You may want to utilize it if you have future questions regarding this code.

A: When you get the "option_parts", you're getting an array of strings.  You should make sure that you explicitly convert to integer there (well, to numbers). The comparison will be done as a numeric comparison on the first iteration, but as soon as you set "highest_number" to "option_parts[2]", then it'll be a string too.
What you could do is this:
   // ...
   var option_parts = optionsList[i].getAttribute("id").split("_");
   if (option_parts[0] === "option") {
     var index = parseInt(option_parts[2], 10); //  <----- the important thing
     if (index > highest_number)
       highest_number = index;
   }

A: The alert box is in the arm of the else statement. Try moving it to the real end of the function
function new_route (parts) {
  var highest_number = -1;

  alert (parts);
  if (parts[0] == "field") {
    } else if (parts[0] == "option") {
      //find last option input id
      var select_container = "container_"+parts[2];
      var thisContainer = document.getElementById (select_container);
      var optionsList = thisContainer.getElementsByTagName ("input");

      for (var i = 0; i< optionsList.length; i++) {
        var option_parts = optionsList[i].getAttribute("id").split("_");

        if (option_parts[0] == "option") {
          alert (option_parts);
          if (option_parts[2] > highest_number) {
            highest_number = option_parts[2];
          }
        }
      }
      alert (highest_number);

      var labelNode = document.createElement ("label");
      var inputNode = document.createElement ("input");
    }
    alert (highest_number); // Add Alert here!
  }

A: Execution will stop if a named element is searched for but can't be found. Double check (use alerts) that the right element id is being searched for using document.getElementById
  var thisContainer = document.getElementById (select_container);

Check that select_container is what you expect.


text:
Q: How open gpio in embedded linux? According to the gpio documentation of openwrt, I entered the following command in the console:
echo "26" > /sys/class/gpio/export
The console prompts " write error: Device or resource busy".
This gpio is a led pin. How should I drive this gpio?

A: GPIOs already defined in the device tree cannot be exported. Fortunately, LEDs can be controlled in another file:
echo "100" > /sys/class/leds/<device>:<color>:<func>/brightness
sleep 1
echo "0" > /sys/class/leds/<device>:<color>:<func>/brightness

LED will flash.


text:
Q: scroll based on dragenter event? how to scroll up step by step and scroll down step by step using jquery. (jquery ui not appreciated).
i have a 2 divs

if i drag an image and hover on first div (upper),it should scroll up step by stell.
if i drag and hover on 2nd div it should scroll down manually.
in both cases scrolling should stop if i came out of the div.
i am trying to implement it using events
var isleftDragPosition=true;;
            $('.upper').on('dragleave', function(){
                console.log("hidragleave");
                var isleftDragPosition=true;
            });
            $('.lower').on('dragleave', function(){
                console.log("hi2dragleave")
                var isleftDragPosition=true;
            });
            $('.upper').on('dragenter', function(){
                var isleftDragPosition=false;
                while(!isleftDragPosition){
                    var x=document.documentElement.scrollTop;
                    console.log("to upper position",x);
                    window.scrollTo(0, x-2);
                }
            });
            $('.lower').on('dragenter', function(){
                console.log("hi2dragenter",document.documentElement.scrollTop)
                window.scrollTo(1000, 1000);
            });

i am trying it with the top div to scroll up, but the code crashes my tab(hang).
how i can do that?

A: You are redefining your flag in each handler, so the change is not saved. Also, while loop might be to fast for your particular case. I modified code like this:
$('.upper').on('dragenter', function(){
    isleftDragPosition=false;
    clearInterval(interval);
    var f = function() {
      if(!isleftDragPosition){
          var x=document.documentElement.scrollTop;
          console.log("to upper position",x);
          window.scrollTo(0, x-2);
      } else {
        clearInterval(interval);
      }
    }
    setInterval(f, 1000);
});

Hope this helps.


text:
Q: How to append dataframes in Pandas without staggered format I was able to append dataframes but as they are added, they appear at the end of the one previously appended an so on.
Each dataframe has a different header name.
Here's what I've tried so far:
df1 = df1.append(dforiginal,sort=False, ignore_index=False)

What's more, every time they are appended, their index is set back to 0.  Is it possible to append each dataframe all starting at Index=0?
The screenshots below show what I'm getting(top image) and what I'm trying to accomplish (bottom image).
Thanks.
[1

A: If I got your point correctly you want to add rows instead of columns to your Dataframe, dont you?
Nevertheless, you could use for example this website to get a general overview on how to use the append function: https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html
Moreover, you can reset the index if you set the keyword ignore_index as True.


text:
Q: "Effectivity" of braid notation for knots Any knot or link can be written in braid notation (with implied closure of strands). Some natural questions:

*

*Assume I don't allow inverses - only overcrossings are used as generators. Anything known about the braid index then (might as well be $\infty$, i.e., this representation doesn't always exist)?

*Assume I additionally allow Temperley-Lieb generators (what's that called, Turaev algebra?). Same question.

*For all three variants - surely the braid representation has some overhead with respect to the minimum crossing representation of a knot. How large can it get?

A: (1) It is a theorem of Stallings [1978, "Constructions of fibred knots and links"] that closures of positive braids are always fibered links.  Thus "most" knots are not realised as the closure of a positive braid.
(2) If you allow positive (say) crossings only, and TL generators, then you can use the latter to rotate the former by 90 degrees.  Then the given diagram can be converted with at most a linear growth in complexity.
(3) Interesting question.  I'll guess that the blow up is at worst polynomial.