text:
Q: Notepad++ or Vim Document Wrap or Text File Wrap This is going to sound weird, bear with me. I am not looking for the regular word wrap, which I already know how to toggle.
Is there any possibility to do a "document wrap" or "text wrap" in Notepad++? Example, imagine a text file with three long lines (line number at beginning):
1 A 111111111 222222222 333333333 444444444 555555555 666666666 777777777 888888888 999999999 000000000 aaaaaaaaa bbbbbbbbb ccccccccc ddddddddd eeeeeeeee fffffffff ggggggggg hhhhhhhhh iiiiiiiii jjjjjjjjj kkkkkkkkk
2 B 111111111 222222222 333333333 444444444 555555555 666666666 777777777 888888888 999999999 000000000 aaaaaaaaa bbbbbbbbb ccccccccc ddddddddd eeeeeeeee fffffffff ggggggggg hhhhhhhhh iiiiiiiii jjjjjjjjj kkkkkkkkk
3 C 111111111 222222222 333333333 444444444 555555555 666666666 777777777 888888888 999999999 000000000 aaaaaaaaa bbbbbbbbb ccccccccc ddddddddd eeeeeeeee fffffffff ggggggggg hhhhhhhhh iiiiiiiii jjjjjjjjj kkkkkkkkk

A "document wrapped" version would look like this:
1 A 111111111 222222222 333333333 444444444 555555555 666666666 777777777 8888
2 B 111111111 222222222 333333333 444444444 555555555 666666666 777777777 8888
3 C 111111111 222222222 333333333 444444444 555555555 666666666 777777777 8888
<wrapped>
1 88888 999999999 000000000 aaaaaaaaa bbbbbbbbb ccccccccc ddddddddd eeeeeeeee
2 88888 999999999 000000000 aaaaaaaaa bbbbbbbbb ccccccccc ddddddddd eeeeeeeee
3 88888 999999999 000000000 aaaaaaaaa bbbbbbbbb ccccccccc ddddddddd eeeeeeeee
<wrapped>
1 fffffffff ggggggggg hhhhhhhhh iiiiiiiii jjjjjjjjj kkkkkkkkk
2 fffffffff ggggggggg hhhhhhhhh iiiiiiiii jjjjjjjjj kkkkkkkkk
3 fffffffff ggggggggg hhhhhhhhh iiiiiiiii jjjjjjjjj kkkkkkkkk

Best is to have Notepad++ automatically do and undo it (similar to Word Wrap toggle). However, we can also use a solution that permanently modifies the file content - perhaps using a regex to cut the excess of lines exceeding a column number, and paste them at the bottom of file.
I can also try a vim feature if any.

A: Enter the following in your vimrc, then press F12 to use.  Press u to undo the changes.
nmap <F12> :call FileWrapOuter()<CR>

function! FileWrapOuter()
    while FileWrap()
    endwhile
endfunction

function! FileWrap()
    " Go to end of file and set mark 'a'.
    norm G
    norm ma
    let w:madeChange = 0
    " Call FileWrapInner() for each long line.
    :%g/.\{80\}/call FileWrapInner()
    if w:madeChange
        " Return to mark 'a' and add <wrapped>.
        norm 'a
        norm o<wrapped>
        return 1
    endif
    return 0
endfunction

function! FileWrapInner()
    " Copy current line into 't' buffer.
    norm "tyy
    " Delete anything in line after 79th character.
    norm 0
    norm 79l
    norm d$
    " Paste 't' buffer at end of file.
    norm G
    norm "tp
    " Delete first 79 characters.
    norm 0
    norm 79x
    let w:madeChange = 1
endfunction

This assumes a maximum width of 79 characters.  For other amounts, change occurrences of 80 and 79 in the functions above.


text:
Q: Why @Column might not work for methods? I have a Spring Boot application with JPA and Hibernate Maven dependencies. Database is PosgreSQL.
I would like to create fields in a database based on methods.
So I have an entity class:
@Entity
@Table(name="test_my_entity")
public class MyEntity {

    @Id
    @GeneratedValue
    private Long id;

    protected String name;

    @Transient
    @XmlSchemaType(name = "dateTime")
    protected XMLGregorianCalendar myXMLDate;

    protected Calendar myDateProperty;

    @Column(name = "my_date")
    private Calendar isCalendar() {
        return new GregorianCalendar(myXMLDate.getYear(), myXMLDate.getMonth(), myXMLDate.getDay());
    }

    @Column(name = "my_str")
    public String myStr() {
        return "My string";
    }

    public MyEntity() {
    }
}

However I receive the following structure:

All annotations on methods are ignored.
Could anyone please give me some advice why it might happen and how to create needed fields properly?

A: The methods must follow, Java Bean convention; precisely, public Getters and Setters. Moveover, properties must exist. Try this,
@Entity
@Table(name="test_my_entity")
public class MyEntity {

    private Long id;
    protected String name;
    private Calendar myDate;
    private String myStr;

    @Transient
    @XmlSchemaType(name = "dateTime")
    protected XMLGregorianCalendar myXMLDate;

    @Id
    @GeneratedValue
    public Long getId() {
      return id;
    }

    @Column(name = "my_date")
    public Calendar getMyDate() {
      return myDate;
    }

    @Column(name = "my_str")
    public String getMyStr() {
      return myStr;
    }

    // I don't get its purpose; hence not touching it.
    private Calendar isCalendar() {
        return new GregorianCalendar(myXMLDate.getYear(), myXMLDate.getMonth(), myXMLDate.getDay());
    }
}

Refs:

*

*List of types Hibernate understand by default.

*How to make Hibernate to understand your type.

A: So I have found the solution. So that you can receive values from methods you should add @Access annotations and also make @Transient variables.
So Hibernate will create neccesary fields and during commit will use values from methods to fulfill them.
Also here is an example of how to convert XMLGregorianCalendar to Calendar -
 the format that Hibernate can use successfully.
Here is a working example:
@Entity
@Access(AccessType.FIELD)
@Table(name="test_my_entity")
public class MyEntity {

    @Id
    @GeneratedValue
    private Long id;

    @XmlAttribute(name = "name")
    @Transient
    protected String name;

    @XmlSchemaType(name = "dateTime")
    @Transient
    protected XMLGregorianCalendar myXMLDate;

    @Transient
    private Calendar calendarDate;

    @Access(AccessType.PROPERTY)
    @Column(name = "calendar_date")
    private Calendar getCalendarDate() {
        return new GregorianCalendar(myXMLDate.getYear(), myXMLDate.getMonth(), myXMLDate.getDay());
    }

    @Access(AccessType.PROPERTY)
    @Column(name = "my_str_name")
    public String getName() {
        return "My string";
    }

    //...setters here

    public MyEntity() {
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: NetSuite Send an email to all users who have a specific role in suite script I try to send an email to all users who have the role of engineer,
I would like to find a function that send emails for all users according to their  roles,
or any function that returns me all the users by their role,
Is suite script includes one of those functions?

A: Search for all employees with a particular role, then loop through them to send the email.  Here's an example of a scheduled script and a custom module that does this.
emailUtils.js
/**
 *  @NAPIVersion 2.0
 *  @NModuleScope Public
 */
define(['N/email', 'N/search'], function(email, search) {
  function sendEmailToRole(emailObject, roleId) {
    var employeeIds = getEmployeesByRole(roleId);
    employeeIds.forEach(function(employeeId) {
      emailObject.recipients = employeeId;
      email.send(emailObject)
    });
  }

  function getEmployeesByRole(roleId) {
    var results = search.create({
      type: 'employee',
      filters: [
        ['isinactive', 'is', 'F'],
        'and', ['role', 'anyof', roleId]
      ]
    }).run().getRange({ start: 0, end: 1000 });

    return (results || []).map(function(result) {
      return result.id;
    })
  }

  return {
    sendEmailToRole: sendEmailToRole
  };
});

emailSchedule.js
/**
 *  @NAPIVersion 2.0
 *  @NModuleScope Public
 *  @NScriptType ScheduledScript
 */
define(['./emailUtils'], function(emailUtils) {
  function execute() {
    var ADMINISTRATOR = 3;

    var email = {
      author: 1073,
      subject: 'SUBJ: This is a test email',
      body: 'This is the body of the test email',
    };

    emailUtils.sendEmailToRole(email, ADMINISTRATOR);
  }

  return {
    execute: execute
  }
});

A: The approach I recommend would be to make a new Saved Search of the Employees with this role (and any other criteria you'd like met), then use that Saved Search to define a dynamic Entity Group (Lists > Relationships > Groups > New). You can then set this Group as the recipient of your email.

A: You should do a saved search of employees where their role is Engineer. You can then use the sendEmail function to email each of those people


text:
Q: Laravel 5.4 Save last login in logs table I want to save a log register in my table logs_users when an user make the login successfully. For make this, logs_users table have the next fields:
+id
+user_id: Id of the user
+log_id :Number that represents the log( in this case, the number is 2)
+created_at

I dont understand how I can make this using the events in laravel 5.4 so if you can tell me the steps I will thank you

A: You can override authenticated method in the Auth\LoginController, something like:
protected function authenticated(Request $request, $user)
{
    auth()->user()->logsUsers()->create();
}

I assume you already defined logsUsers() relationship. If not, do that:
public function logsUsers()
{
    return $this->hasMany(LogsUser::class);
}


text:
Q: X is a connected and compact Hausdorff space with some properties.Prove that X is homeomorphic to $\mathbb{S}^1$. $X$ is a connected and compact Hausdorff space,and for all $x \in X$,there is a open neighborhood of $x$ homeomorphic to $(-1,1)$.Prove that $X$ is homeomorphic to $\mathbb{S}^1$.
At first,I replace X with $\mathbb{S}^1$.Naturally,I tried to prove that $X/\{x\}$ is homeomorphic to $(-1,1)$,but I found it hard to prove this.
So anyone could help me with my proof or have some other ideas?


text:
Q: Py2App: Alias mode works, but deployment doesn't I'm trying to deploy my python application using py2app.
I created the setup file using : py2applet --make-setup MyApplication.py
Then I did this to test it : python setup.py py2app -A
That worked as well. My GUI program runs.
When I try the last step: python setup.py py2app
I get this fat error.
Traceback (most recent call last):
  File "setup.py", line 18, in <module>
    setup_requires=['py2app'],
  File "/usr/local/Cellar/python/2.7.8_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/core.py", line 151, in setup
    dist.run_commands()
  File "/usr/local/Cellar/python/2.7.8_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/dist.py", line 953, in run_commands
    self.run_command(cmd)
  File "/usr/local/Cellar/python/2.7.8_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/dist.py", line 972, in run_command
    cmd_obj.run()
  File "/usr/local/lib/python2.7/site-packages/py2app/build_app.py", line 659, in run
    self._run()
  File "/usr/local/lib/python2.7/site-packages/py2app/build_app.py", line 865, in _run
    self.run_normal()
  File "/usr/local/lib/python2.7/site-packages/py2app/build_app.py", line 959, in run_normal
    self.create_binaries(py_files, pkgdirs, extensions, loader_files)
  File "/usr/local/lib/python2.7/site-packages/py2app/build_app.py", line 1214, in create_binaries
    platfiles = mm.run()
  File "/usr/local/lib/python2.7/site-packages/macholib/MachOStandalone.py", line 105, in run
    mm.run_file(fn)
  File "/usr/local/lib/python2.7/site-packages/macholib/MachOGraph.py", line 84, in run_file
    self.scan_node(m)
  File "/usr/local/lib/python2.7/site-packages/macholib/MachOGraph.py", line 110, in scan_node
    m = self.load_file(filename, caller=node)
  File "/usr/local/lib/python2.7/site-packages/macholib/MachOGraph.py", line 93, in load_file
    newname = self.locate(name, loader=caller)
  File "/usr/local/lib/python2.7/site-packages/macholib/MachOStandalone.py", line 23, in locate
    newname = super(FilteredMachOGraph, self).locate(filename, loader)
  File "/usr/local/lib/python2.7/site-packages/macholib/MachOGraph.py", line 49, in locate
    loader=loader.filename)
TypeError: dyld_find() got an unexpected keyword argument 'loader'

Why is this happening? I've spend the last few hours trying to deploy. No luck with py2app, cx_freeze, etc.

A: Here is a workaround: edit the file MachOGraph.py which in your case is located there:
/usr/local/lib/python2.7/site-packages/macholib/MachOGraph.py

Search for the term loader=loader.filename) and replace it with loader_path=loader.filename)
Credits goes to David Goldenberg for its post on bitbucket.org. https://bitbucket.org/ronaldoussoren/py2app/issues/137/py2app-problems-using-enthought-python

A: Pillow was the problem. Py2Applet doesn't play nice with it. Got rid of Pillow, and all is well.


text:
Q: Link displacement I have some links on a page.
When I click (tap) one of these links, the gray box which shows where I tap is misplaced. It seems that the link is rendered higher than it should.
Is this a known Mobile Safari issue?


text:
Q: Post Curl Custom Action to Facebook, via PHP in an Asychromous queue I have successfully created a custom Facebook open graph action, and have been able to post it from my facebook app. However, Facebooks API to post, was slowing my user experience down, so I created a queue table, that I want to execute from cron outside the user experience.
The table contains a field with the full post request, something like this:
https://graph.facebook.com/me/mynamespace:my_action?custom_item=https://www.mysite .com/thefolder/&access_token=XXXXXXX

So my cron worker will run every 2 mins.. How do I get PHP to run CURL (or something) on the above Asynchronously, i.e. not wait for facebook to respond, so I can churn through say 100 in a minute (should I be so lucky)?
oh and b) should I replace "/me/" with the persons fb user id?
Note, I am not a linux person. thanks!

A:
However, Facebooks API to post, was slooooowing my user experience down

First of all, how is it slowing it down? Are you making a server-side or client-side call to the API?
If you'd do it client-side, it'd already be asynchronous, so there shouldn't be much slowing down that would affect user experience.

How do I get PHP to run CURL (or something) on the above Asynchronously, i.e. not wait for facebook to respond, so I can churn through say 100 in a minute (should I be so lucky)?

I haven't use cURL "asynchronously" yet, but a quick google search suggest that you can try it setting CURLOPT_TIMEOUT or on up-to-date systems even CURLOPT_TIMEOUT_MS to a value of 1. But I can't tell you how reliable that'll be; if Facebook's API will process it correctly if the client (your server in this case) closes the connection quickly, etc.
I'm not sure if doing this by cron is such a good idea.
If you can't do the API call client-side, as suggested above, because you require your app access token to be send for your actions to be published, then I'd suggest still doing it server-side, but not via cron, but triggered by the user himself, by embedding an IMG or SCRIPT element into you're page (put out by PHP if you're directing the user to a new page, or created and put into the DOM client-side via JavaScript), which has it's source set as the address of your PHP script publishing the action. If you use a SCRIPT element you could even control the outcome of the operation and react to it client-side, by just returning appropriate JavaScript code in the response.
I'd think this approach should not slow down user experience noticably, and I'd also guess it might be more reliable, than "asynchronous" cURL request fired in the hundreds by a cron-called script.

oh and b) should I replace "/me/" with the persons fb user id?

With a user access token provided in the call the API can figure this out by itself.
But if you're using an app access token, then you have to use the user-id, because otherwise the API has no way of knowing which user is meant in the call.

A: You should store the user session somewhere(db, etc). Then you can send through cron worker as long as the user session is active. And use the token while posting actions. (you should use token belonging to user only :))

b) should I replace "/me/" with the persons fb user id?

then you can use /me or /id
To make the aynbchronus http call, see this post
Asynchronous PHP calls?
But there is rate limit, which would stop you from posting based on this condition (600 calls per 600 seconds, per token & per IP to be about where they stop you)
Source: http://www.quora.com/Whats-the-Facebook-Open-Graph-API-rate-limit


text:
Q: Accessing ActiveDirectory properties belong to objectClass=posixGroup I am trying to update the memberUid property of the posixGroup.

*

*I do a directory search and find my record.  If I loop through the searchresults.property I can list the values (it is defined as Multi-value) of the field.

*I define a DirectoryEntry using the searchresults.getdirectory method.

If I do anything with the property from this directoryentry, for instance check if it exists (property.contain), or list it or try to update it I get an unknown error x'8000500C'.
The fields cn and description' do not cause this problem.
If I add other user defined properties I also get the error.
How can I work with properties belonging to this type of schema?

A: Your error looks like it is:
8000500c The Active Directory datatype cannot be converted to/from a native DS datatype
This seems to imply that the data returned is not a native AD datatype.
There seems to be a workaround at this article.


text:
Q: Laravel: Having a Recipe from a DB table pulled based on allergen constraints? I am working on a meal plan generator based on user input constraints.
One of these constraints is allergens. I initially attempted having two tables, Recipes and Recipe_Allergens, as one recipe can have many allergens, and connected them by Recipe ID.
E.g. Recipe Table:

id
Recipe_Name
Type

1
Lasagna
Dinner

E.g. Recipe_Allergens Table:

id
Recipe_ID
Allergen_Description

1
1
Dairy

2
1
Gluten

The user input form is all drop down except for the allergens, which is checkbox. That's why the input must be imploded, and then exploded again:
$request->merge([
    'allergens' => implode(',', (array)$request->get('allergens'))
]);

$meal = $request->meal_type;
$allerg = $request->allergens;

$allergenarray2 = explode(",", $allerg);

I then joined these tables and did a search in order to find the appropriate Recipe ID based on the given user dietary constraints:
$recipenew = Recipe::join('recipe_allergens', 'recipe_allergens.recipe_id', '=', 'recipe.id')
    ->where('recipe.type', $meal)
    ->whereNotIn('recipe_allergens.allergen_description', $allergenarray2)
    ->get('recipe.id');

Added to a Meal Plan Table:
$x = 0;
while ($x < $days) {
    $recipeday = (new Carbon($request->date))->addDays($x);
    $recidnew = $recipenew[$x]->id;
    MealPlanDisplay::create([
        'Recipe_ID' => $recidnew,
        'Day' =>  $recipeday,
        'user_id' => $currentuserid,
    ]);
    $x = $x + 1;
}

However, the problem is I get a logic error because of this DB setup. This works if the user inputs both "Dairy" AND "Gluten" as their allergies. However, if the user only inputs "Dairy" as their allergen, they will still get "Lasagna" recommended in their meal plan because 'Gluten' and 'Recipe_ID' are isolated alone. This is bad because Lasagna still has Dairy present in the recipe.
What other programming solution is there, to check for each individual allergen in a recipe that may have multiple allergens?

A: To get the recipes that dont include the allergens, use the relation between the Recipe::class model and Allergen::class model
Option 1
If you dont want to change the structure, set the relation to hasMany
public function allergens()
{
    return $this->hasMany(Allergens::class, 'Recipe_ID');
}

And use the code
$recipenew = Recipe::where('recipe.type', $meal)->whereDoesntHave('allergens', function($QBallergens) use($allergenarray2) {
    $QBallergens->whereIn('Allergen_Description',$allergenarray2);
})->pluck('id');

Option 2
Change your structure for a many to many relation.
So you need a seperate table Allergens and a pivot table allergen_recipe with allergen_id and recipe_id as keys.
public function allergens()
{
    return $this->belongsToMany(Allergens::class);
}

and use "almost" the same code (adapted to ids).
$recipenew = Recipe::where('recipe.type', $meal)->whereDoesntHave('allergens', function($QBallergens) use($allergenarrayIds) {
    $QBallergens->whereIn('id',$allergenarrayIds);
})->pluck('id');


text:
Q: What are some tools to convert Java programs into sequence diagrams? What are some tools to convert Java programs into sequence diagrams?

A: The Netbeans IDE has reverse engineering (fast-forward to the last screenshot in the blog).

A: I believe Enterprise Architect supports Java.
http://www.sparxsystems.com.au/
I've used it for C#.NET and it reverse engineers all your classes / methods / interfaces etc and makes it easy to create sequence diagrams. It is also possible to get a sequence diagram out of a debug session, but I haven't tried that yet!

A: eclipse can be upgraded with OMONDO. Which is not free, but they had a free version some years ago and that on was capable of re-engineering Java code to sequence diagrams.
Here is another big list of UML tools.

A: Poseidon for UML


text:
Q: Sending JSON data in the body of an Alamofire Request I'm trying to make an api call to submit some data using Alamofire (version 4.0). The trouble i'm having is that when making the call I get a response from the server that the JSON data was not in a valid format.
Is there a way to check if the data data is being serialized correctly in Alamofire?
I have tried many of the solutions currently on StackOverflow and cannot find a solution. Thanks for your help.
This should be the format of the request body:
{
"reference_id": "Test001",
"data": {
    "type": "step",
    "data": {
        "2015-08-02": 8574
    }
}
}

My Swift code:
let params: [String:Any] = [
        "reference_id": "someName",
        "data": [
            "type" : "step",
            "data": [
                "2015-08-02": 8574
            ]
        ]
    ]

    print(params)

    if let userToken = userToken {
        let request = Alamofire.request(url+"API.php?Action=SaveHealthData", method: .post, parameters: params, encoding: JSONEncoding.default).responseString(completionHandler: { response in
            print(response)
        })
    }

The error I'm getting is:

Warning:  json_decode() expects parameter 1 to be string, array given in /var/www/html/API/SaveHealthData.php on line 8
      {"error":"data not in valid json format"}

A: Here is the solutions of your problem,
var dataDict : [String : Any] = [:];

dataDict["type"] = "Step"
dataDict["data"] = ["2015-08-02": 8574];

let params: [String:Any] = ["reference_id": "someName",
                            "data": String.toJSonString(data: dataDict)];

Here toJSonString is an extension of String
static func toJSonString(data : Any) -> String {

        var jsonString = "";

        do {

            let jsonData = try JSONSerialization.data(withJSONObject: data, options: .prettyPrinted)
            jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue)! as String

        } catch {
            print(error.localizedDescription)
        }

        return jsonString;
}

Happy Coding


text:
Q: What are the differences "under the hood" between running from jruby and a warbled jar? I am having a problem where a libgdx program runs fine when run from the command line with jruby <filename>.rb but when I warble it into a jar and run java -jar <filename>.jar it runs and then closes without displaying a window.
Since I'm no expert on java or jruby I'd like to know what goes on under the hood, so to speak, in an attempt to solve this problem I'm having.

A: Maybe you don't have the libgdx library inside the jar, try this, execute the jar with:
java -cp gdx.jar -jar <filename>.jar

Assuming that the libgdx.jar is in the same folder. It's simply a classpath problem probably


text:
Q: What do we call this in python? Consider the following for loop:
for x in range(0, 3):
    print "We're on time %d" % (x)

I can't seem to find the proper name of the x in the for loop. I know it is essentially a sort of arbitrary placeholder but I'd be interested in knowing the proper name if anyone does know.

A: The correct name is "iteration variable", aka "iterating var" if you don't mind bad grammar.

A: The syntax in the python 2 doc gives:
for_stmt ::=  "for" target_list "in" expression_list ":" suite
              ["else" ":" suite]

and then:
"The suite may assign to the variable(s) in the target list;"
So x in your example is a variable.
The Python 3 version is worded slightly differently:
"The for-loop makes assignments to the variables(s) in the target list."
But you can see that it still calls them variables.

A: x is a variable, or "iteration variable", if you will, which, for a python for loop is a placeholder for each individual member of an iterable (basically a container to hold an arbitrary number of a data type), and range() is an iterator (as oppposed to previous versions of python, where it was a list), which returns its unique iterable data type, which is, functionally speaking, like a list where every member is destroyed after its use to preserve memory.

A: It's obvious that x is just a variable since it is varied in each iteration of for-loop. The range of its variation is in (0,3), and the value for each iteration is from 0 to 2. (local var / iteration var)

A: It is a variable, perhaps made easier to understand when you view the loop in generator format.
Generator image


text:
Q: How to indicate width is 'flexible' in Android layout editor? I want to keep distance from left and right, but keep width of the widget flexible. How can I define it in Android?

A: I do not understand your question, but i guess you're looking for a way to give your ListView a width which is dynamic based on e.g. the screen width.
You should have a look at MATCH_PARENT

LayoutParams are used by views to tell their parents how they want to
  be laid out. See ViewGroup Layout Attributes for a list of all child
  view attributes that this class supports.
The base LayoutParams class just describes how big the view wants to
  be for both width and height. For each dimension, it can specify one
  of:

*

*FILL_PARENT (renamed MATCH_PARENT in API Level 8 and higher), which
  means that the view wants to be as big as its parent (minus padding)

*WRAP_CONTENT, which means that the view wants to be just big enough to
  enclose its content (plus padding)

*an exact number

  There are subclasses of LayoutParams for different subclasses of ViewGroup. For
  example, AbsoluteLayout has its own subclass of LayoutParams which
  adds an X and Y value.

https://developer.android.com/reference/android/view/ViewGroup.LayoutParams.html
https://developer.android.com/guide/topics/ui/declaring-layout.html


text:
Q: Is there a Find & Replace function in ReSharper? I've just implemented a custom MessageBox for my application. I'd now like to replace any calls to MessageBox.Show() with my custom implementation, which is MsgBox.Show()**. I realise I could do this with a simple global Find & Replace but I'm wondering if there's a safer/better way to do it with ReSharper?
**all the parameters being passed in are the same in both cases.

A: There is a tool called Structural search and replace in ReSharper. It is definitely safer to use than a simple Find & Replace, but it is a little bit more complex. I've tried to make an instruction for you, but I didn't test it. Try it on your own risk. Search Google for ReSharper structural search and replace to find more info.

*

*Go to ReSharper | Find | Search with pattern.

*Type $t$.Show($args$) in the text field.

*Click Add Placeholder -> Expression. Type t for name, then type MessageBox for expression type and choose the correct type from suggestion list.

*Click Add Placeholder -> Argument. Type args for name, leave other fields with default values.

*Ensure that this pattern finds your target calls by clicking Find.

*Now go back to ReSharper | Find | Search with pattern (your pattern should be still there).

*Click Replace.

*Type MsgBox.Show($args$).

*Click Replace.

*Now correct usings where necessary. Unfortunately, this only can be done semi-automatically, by finding errors via ReSharper's solution-wide analysis or by compiling your project and then clicking Alt-Enter on any error to invoke ReSharper's fix for adding usings.


text:
Q: How do I use Powershell to set Delegate permission on a mailbox? When I add a user to Outlook delegation, using this method

I see them in the following powershell command
[PS] C:\Windows\system32>Get-CalendarProcessing aaaa| fl

AutomateProcessing                  : AutoUpdate
AllowConflicts                      : False
BookingWindowInDays                 : 180
MaximumDurationInMinutes            : 1440
AllowRecurringMeetings              : True
EnforceSchedulingHorizon            : True
ScheduleOnlyDuringWorkHours         : False
ConflictPercentageAllowed           : 0
MaximumConflictInstances            : 0
ForwardRequestsToDelegates          : True
DeleteAttachments                   : True
DeleteComments                      : True
RemovePrivateProperty               : True
DeleteSubject                       : True
AddOrganizerToSubject               : True
DeleteNonCalendarItems              : True
TentativePendingApproval            : True
EnableResponseDetails               : True
OrganizerInfo                       : True
ResourceDelegates                   : {asdf.com/New York/NY Users/bbbb, bbbb}
RequestOutOfPolicy                  : {}
AllRequestOutOfPolicy               : False
BookInPolicy                        : {}
AllBookInPolicy                     : True
RequestInPolicy                     : {}
AllRequestInPolicy                  : False
AddAdditionalResponse               : False
AdditionalResponse                  :
RemoveOldMeetingMessages            : True
AddNewRequestsTentatively           : True
ProcessExternalMeetingMessages      : False
RemoveForwardedMeetingNotifications : False

However when I set the user as a delegate, I get the following error:
set-CalendarProcessing ifischer -ResourceDelegates {"aaa.com/New York/NY Users/bbb,bbb"}
ResourceDelegates can only be enabled on resource mailboxes.

A: This response is a little late, I apologize.
The powershell cmdlet you're using there (Set-CalendarProcessing) is only for 'Resource' mailboxes. This refers to objects like rooms, company cars, projectors, and other things that your organization use by booking time on a calendar.
This particular Exchange object type has a special calendar assistant available that can either automatically accept or reject calendar requests that are sent to it, or you can set a delegate. The naming here is misleading, since delegate is used elsewhere in the Exchange world to mean something else.
The error you recieved is indicating that the mailbox you're trying to run this cmdlet against is not a resource type, so it doesn't have the special calendar attendant, and therefore cannot have a delegate.
As far as I know, the only way to set the type of delegate you're trying to set is by doing it manually through the Outlook desktop client (like your screenshot shows).
I hope this helps.

A: You can can complete this with the following command:
Add-MailboxFolderPermission -Identity user1@domian:\calendar -user user2@domian -SharingPermission Delegate -AccessRights Editor

Remember to use Set-MailboxFolderPermission instead of Add-MailboxFolderPermission if they already have Access Rights to the mailbox.


text:
Q: Altering output of solve_ivp for given input I have a bit of a simple question regarding solving a differential equation I'm hoping someone can help me answer. I have a differential equation for a simple neuron model, with varying input (i.e. integrate and fire model of a neuron, with a "square" input):
def impulse_func(t, V):
    if 100 <= t <= 200:
        return 0.25
    return 0

def passive_membrane(t, V, El, R, tau, I_app):
    dVdt = (-(V - El) + R*I_app(t, V))/tau
    return dVdt

t = np.arange(0, 400, 0.1)
V0 = np.array([-60.])

V = solve_ivp(fun = passive_membrane,
              t_span = [0, 400],
              t_eval = t,
              y0=V0,
              args = (-60., 100., 10., impulse_func),
              dense_output=True,
              rtol = 1e-8, atol = 1e-8)

In this case, the values of El, R, and tau will be remaining constant. This works just as expected, with the plot being My problem is that I now need to create a "spike" in the solution which is dependent on the solution.
Specifically, if the solution passes my "threshold" value of -37, for a single unit of time I would like to set the solution value to 60 and then return to my "resting" which is -65 in the next unit of time. I've tried modifying the impulse_func and the passive_membrane functions, but it just led to an exploding solution. I'm able to do this when I write my own solver, but I'm lost on how to implement it with solve_ivp, which I'd like to use since it has much more functionality than my own poorly optimized RK2 method and because I want to be able to pass variable thresholds, times, etc.


text:
Q: JavaScript export Attachment() classes from discord.js library I am using the library browser way, I can not manage to attach the imgur png!
<script type="text/javascript" src="discord.11.6.4.min.js"></script>
<script type="text/javascript">

// Create an instance of a Discord client
const client = new Discord.Client();
const atch = new Discord.MessageAttachment();

/**
 * The ready event is vital, it means that only _after_ this will your bot start reacting to information
 * received from Discord
 */
client.on('ready', () => {
  console.log('I am ready!');
});

client.on('message', message => {
  // If the message is '!rip'
  if (message.content === '!rip') {
    // Create the attachment using MessageAttachment
    const attachment = new atch.MessageAttachment('https://i.imgur.com/w3duR07.png');
    // Send the attachment in the message channel
    message.channel.send(attachment);
  }
});

  client.login('BOT TOKEN HERE');
</script>

Thats all I have. Here is the doc link that I have got: https://discord.js.org/#/docs/main/11.6.4/examples/attachments
I can't adapt the code to get it running! OR this library isn't just completed for broswer?
The error im getting:
index.html:19 Uncaught TypeError: attachments is not a constructor

What exactly is not right here?


text:
Q: What is the correct format when setting up Bootstrap containers, rows, columns? I just started working with Bootstrap and I am trying to wrap my mind around it. I understand how the rows and columns and containers work. I just don't know what the "syntax" is for setting up the divs.
Do I want to do something like this

Content Goes In Here

Or would it be something like:

Content Goes In Here

Or it might be another way I am not seeing. I just want to make sure the way I am writing the divs for Bootstrap is correct and that I am not using too many DIV's
Do I want all my current code to be css free such ass Width, Height, Padding for the framework to work correctly etc?
Let me know on some direction. Thanks!

A: Your first example is definitely correct:

Content Goes In Here

It may seem like a lot of
 tags when you are first starting out, but try to not think of each of them as a
 but rather think of each one as the class they are. For instance, the first one is container-fluid, the second one is row and the third one is col-xs-12.
As a general rule of thumb, the less inline styling the better, yes. Whenever you identify a need to do anything with the width or something that seems like it should be handled by bootstrap, it probably should be and you should look for anything inside of bootstrap that could handle what you want to do.
Here is a more formal tutorial on Bootstrap 3: http://www.w3schools.com/bootstrap/


text:
Q: Why do I get error 462 while imported excel using Access VBA? I have an access database with I import multiple excel spreadsheets one at a time. Before importing I open the spreadsheet and sort it.  Works fine the first time, but the second time and any additional times, I get error 462.  I notice that the spreadsheet never really closes, so I think that may be the issue, but I don't know what it doesn't close.  Below is my code:
Private Sub cmdImport_ClassConfig_Data_Click()
Dim fDialog As Office.FileDialog
Dim varFile As Variant
Dim ConfigFile As String
Dim exlFile As excel.Application
Dim wbk As excel.Workbook
Dim wst As excel.Worksheet

On Error GoTo Import_Posting_Dates_Error

DoCmd.SetWarnings False
Application.AutomationSecurity = msoAutomationSecurityForceDisable

DoCmd.RunSQL "DELETE * FROM ClassConfiguration"
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
    With fDialog
        .AllowMultiSelect = False
        .Title = "Please select your CONFIG file."
        .Filters.Clear
        .Filters.Add "Excel Spreadsheets", "*.xlsx"
        .InitialFileName = "C:\Documents and Settings\%UserName%\My Documents\*xlsx"
        If .Show = True Then
            For Each varFile In .SelectedItems
                ConfigFile = varFile
            Next
        End If
    End With

Set exlFile = New excel.Application
Set wbk = exlFile.Workbooks.Open(ConfigFile, , False)
exlFile.visible = True
Set wst = wbk.Worksheets(1)
wst.Sort.SortFields.Clear
wst.Sort.SortFields.Add Key:=Range("A2:A43527"), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortTextAsNumbers
With wst.Sort
    .SetRange Range("A1:AA4000")
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With
wbk.Close True
Set wbk = Nothing
exlFile.Quit
Set exlFile = Nothing

DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12Xml, "ClassConfiguration", ConfigFile, True

Dim sUIC As String
sUIC = Me.DDTVSTShipLog.Controls("UIC")

DoCmd.RunSQL "INSERT INTO ClassConfiguration1 ( ID, ric, p_ric, UIC, sei, esd, EIC, work_center, rin, quantity, prid, Location, serial_number, efd, RIC_NOMENC, service_application_cd, hsc, [SELECT], alt_ric, sac ) " & _
    "SELECT ClassConfiguration.ID, ClassConfiguration.ric, ClassConfiguration.p_ric, Right([ClassConfiguration].[UIC],5) AS UICS, ClassConfiguration.sei, ClassConfiguration.esd, ClassConfiguration.EIC, ClassConfiguration.wcr_equip AS work_center, ClassConfiguration.rin, ClassConfiguration.quantity, ClassConfiguration.prid, ClassConfiguration.Location, ClassConfiguration.serial_number, ClassConfiguration.efd, ClassConfiguration.ric_nomenclature AS RIC_NOMENC, ClassConfiguration.sac AS service_application_cd, ClassConfiguration.hsc, ClassConfiguration.[SELECT], ClassConfiguration.alt_ric, ClassConfiguration.sac " & _
    "FROM Configuration1 RIGHT JOIN ClassConfiguration ON Configuration1.ric = ClassConfiguration.ric " & _
    "WHERE ((Not (Right([ClassConfiguration].[UIC],5))='" & sUIC & "') AND ((Configuration1.ric) Is Null));"

Me.Refresh
Forms("Build Visit Database").Refresh

Application.AutomationSecurity = msoAutomationSecurityByUI
DoCmd.SetWarnings True
MsgBox "Class Config Import complete.  Compact are Repair Database before continuing with next import.", vbOKOnly, "Import Complete"
Exit Sub

Import_Posting_Dates_Error:
If Err.Number = 2522 Then ' 2522 missing argument (File Name) - i.e no file selected
    MsgBox "No file selected, operation cancelled " & "( " & Err.Number & " ).", vbInformation, "APP NAME"
Else
    MsgBox Err.Number & " (" & Err.Description & ")", vbInformation, "APP NAME"
End If
Me.Refresh

End Sub

As you can see I do close it and set it to nothing, but it still exists for some reason.
Thanks,
Pat


text:
Q: How to create apache Alias ubuntu 12.10 I have installed the LAMP on my Ubuntu 12.10. All are working correctly.
But I want to create a alias like phpmyadmin
I have created the folder root
/home/user/Dropbox/Development/www/

And added the following lines in my apache2.conf file
Alias /dropbox " /home/user/Dropbox/Development/www/"
<Directory " /home/user/Dropbox/Development/www/">
    Options Indexes FollowSymLinks
    Order allow,deny
    Allow from all
</Directory>

When I access it like localhost/dropbox, I received 403 Error Message. Permission Not Denaid. How can I fix this easily

A: Did you restart the server afterwards?
sudo service apache2 restart

Check this out too on Ubuntu forums. It looks like a similar problem to yours and is easily fixed.

A: Is /home/user/Dropbox/Development/www/ accessible to the www-data user?  To find out for sure, drop to a Terminal, sudo -u www-data -s to become the www-data user, and cd /home/user/Dropbox/Development/www/.  If you can't get to the directory as www-data, neither can Apache.  exit to become root again, and chmod and/or chown your way out of the problem as necessary.

A: If you include a trailing to the end of tour URL path, put one at the end of your alias name too (so this trailing will be required in the URL).
Restart apache2
You surelly have to change the owner group of your new directory to www-data :
sudo chown -R yourname:www-data /home/user/Dropbox/Development/www

And change file permissions like this :
sudo chmod -R 775 /home/user/Dropbox/Development/www

...just learned...
Add this into your Directory section :
Require all granted

And now it works for me.
Hope this will help.

A: You have:
Alias /dropbox " /home/user/Dropbox/Development/www/"

And:
<Directory " /home/user/Dropbox/Development/www/">

This raises the question: why do you have a leading space inside the quotes?
An absolute path with a leading space before / is generally not valid. For example:
$ ls -ld "/home" " /home"
ls: cannot access  /home: No such file or directory
drwxr-xr-x 6 root root 4096 Oct 15 23:53 /home

So, assuming the leading space is not intentional but an error, try removing it and see if that fixes the problem.


text:
Q: Python Line_profiler and Cython function So I'm trying to profile a function within a python script of my own using line_profiler, because I want line-by-line timings. The only problem is that the function is a Cython one, and line_profiler isn't working correctly. On the first runs it was just crashing with an error. I then added
!python
cython: profile=True
cython: linetrace=True
cython: binding=True

at the top of my script and now it runs fine, except the timings and statistics are blank!
Is there a way to use line_profiler with a Cythonized function?
I could profile the non-Cythonized function, but it's so much slower than the Cythonized one that I could not use the information coming from the profiling - the slowness of the pure python one would make it impossible how I could improve the Cython one.
Here is the code of the function I'd want to profile:
class motif_hit(object):
__slots__ = ['position', 'strand']

def __init__(self, int position=0, int strand=0):
    self.position = position
    self.strand = strand

#the decorator for line_profiler
@profile
def find_motifs_cython(list bed_list, list matrices=None, int limit=0, int mut=0):
    cdef int q = 3
    cdef list bg = [0.25, 0.25, 0.25, 0.25]
    cdef int matrices_length = len(matrices)
    cdef int results_length = 0
    cdef int results_length_shuffled = 0
    cdef np.ndarray upper_adjust_list = np.zeros(matrices_length, np.int)
    cdef np.ndarray lower_adjust_list = np.zeros(matrices_length, np.int)
    #this one need to be a list for MOODS
    cdef list threshold_list = [None for _ in xrange(matrices_length)]
    cdef list matrix_list = [None for _ in xrange(matrices_length)]
    cdef np.ndarray results_list = np.zeros(matrices_length, np.object)
    cdef int count_seq = len(bed_list)
    cdef int mat
    cdef int i, j, k
    cdef int position, strand
    cdef list result, results, results_shuffled
    cdef dict result_temp
    cdef int length
    if count_seq > 0:
        for mat in xrange(matrices_length):
            matrix_list[mat] = matrices[mat]['matrix'].tolist()
            #change that for a class
            results_list[mat] = {'kmer': matrices[mat]['kmer'],
                                 'motif_count': 0,
                                 'pos_seq_count': 0,
                                 'motif_count_shuffled': 0,
                                 'pos_seq_count_shuffled': 0,
                                 'ratio': 0,
                                 'sequence_positions': np.empty(count_seq, np.object)}
            length = len(matrices[mat]['kmer'])
            #wrong with imbalanced matrices
            upper_adjust_list[mat] = int(ceil(length / 2.0))
            lower_adjust_list[mat] = int(floor(length / 2.0))
            #upper_adjust_list[mat] = 0
            #lower_adjust_list[mat] = 0
            #-0.1 to adjust for a division floating point bug (4.99999 !< 5, but is < 4.9!)
            threshold_list[mat] = MOODS.max_score(matrix_list[mat]) - float(mut) - 0.1

        #for each sequence
        for i in xrange(count_seq):
            item = bed_list[i]
            #TODO: remove the Ns, but it might unbalance
            results = MOODS.search(str(item.sequence[limit:item.total_length - limit]), matrix_list, threshold_list, q=q, bg=bg, absolute_threshold=True, both_strands=True)
            results_shuffled = MOODS.search(str(item.sequence_shuffled[limit:item.total_length - limit]), matrix_list, threshold_list, q=q, bg=bg, absolute_threshold=True, both_strands=True)
            results = results[0:len(matrix_list)]
            results_shuffled = results_shuffled[0:len(matrix_list)]
            results_length = len(results)
            #for each matrix
            for j in xrange(results_length):
                result = results[j]
                result_shuffled = results_shuffled[j]
                upper_adjust = upper_adjust_list[j]
                lower_adjust = lower_adjust_list[j]
                result_length = len(result)
                result_length_shuffled = len(result_shuffled)
                if result_length > 0:
                    results_list[j]['pos_seq_count'] += 1
                    results_list[j]['sequence_positions'][i] = np.empty(result_length, np.object)
                    #for each motif
                    for k in xrange(result_length):
                        position = result[k][0]
                        strand = result[k][1]
                        if position >= 0:
                                strand = 0
                                adjust = upper_adjust
                        else:
                                position = -position
                                strand = 1
                                adjust = lower_adjust
                        results_list[j]['motif_count'] += 1
                        results_list[j]['sequence_positions'][i][k] = motif_hit(position + adjust + limit, strand)

                if result_length_shuffled > 0:
                    results_list[j]['pos_seq_count_shuffled'] += 1
                    #for each motif
                    for k in xrange(result_length_shuffled):
                        results_list[j]['motif_count_shuffled'] += 1

                #j = j + 1
            #i = i + 1

        for i in xrange(results_length):
            result_temp = results_list[i]
            result_temp['ratio'] = float(result_temp['pos_seq_count']) / float(count_seq)
    return results_list

I'm pretty sure the triple nested loop is the main slow part - it's job is just to rearrange the results coming from MOODS, the C module doing the main work.

A: Till Hoffmann has useful information on using line_profiler with Cython here: How to profile cython functions line-by-line.
I quote his solution:
Robert Bradshaw helped me to get Robert Kern's line_profiler tool working for cdef functions and I thought I'd share the results on stackoverflow.
In short, set up a regular .pyx file and build script and pass to cythonize the linetrace compiler directive to enable both profiling and line tracing:
from Cython.Build import cythonize

cythonize('hello.pyx', compiler_directives={'linetrace': True})

You may also want to set the (undocumented) directive binding to True.
Also, you should define the C macro CYTHON_TRACE=1 by modifying your extensions setup such that
extensions = [
    Extension('test', ['test.pyx'], define_macros=[('CYTHON_TRACE', '1')])
]

A working example using the %%cython magic in the iPython notebook is here:
http://nbviewer.ipython.org/gist/tillahoffmann/296501acea231cbdf5e7

A: Api was changed. Now:
from Cython.Compiler.Options import get_directive_defaults
directive_defaults = get_directive_defaults()
directive_defaults['linetrace'] = True
directive_defaults['binding'] = True


text: Q: Adding custom PublishingRollUpImage to pagelayout Is it possible to create your own PublishingRollUpImage. Do I need to map Crawl properties with new Managed Properties to make the new one act like a PublishingRollUpImage when it comes to search results.


text:
Q: Forcing Logo to stay in line with Menu I'm trying to get my Logo, to stay in line with the Menu.
Example:
_________________|<Edge of logo------|____________________________________
_________________|<Edge of Menu ---------------------------|_______________

The 2 edges should line up regardless of page size.
Currently, when the page is re-sized, the items separate and move about independently.
Here is a link to the site: goo.gl/46yUrt
Let me know if you need any other info.
[Edit 1]
header.php Code: (not sure if this has anything to do with the independent alignments, but I've included it anyways)

<?php _e( 'Menu', 'twentythirteen' ); ?>

                    <a class="screen-reader-text skip-link" href="#content" title="<?php esc_attr_e( 'Skip to content', 'twentythirteen' ); ?>"><?php _e( 'Skip to content', 'twentythirteen' ); ?>
                    <?php wp_nav_menu( array( 'theme_location' => 'primary', 'menu_class' => 'nav-menu' ) ); ?>

Style.css code:
/**
 * 4.2 Navigation
 * ----------------------------------------------------------------------------
 */

.main-navigation {
    clear: both;
    margin: auto;
    max-width: 1028px;
    min-height: 35px;
    position: relative;
    /*float:right;
    Padding: 0 300px;*/
    z-index: 1;
    top: 30px;
    Background: #141412;
}

Logo Alignment:
.site-header .logo-align {
     padding: 30px 0px 0px 0px;
     position: relative;
     left: 20%;
}

I'm no CSS expert, a complete noob at best. I've tried adding left: 25%, which seems to work, but only as long as I don't change the page size. I've played around with Padding, Positing, and float commands, but I can't seem to line them up properly.
If you need any more information, please let me know.

A: With the help of Mariano Urbonas, instead of having the code like so:

          Logo

          Nav Bar

And trying to align each element individually, I've changed the header.php code as follows: adding both elements to 1 div.

          Logo

          Nav Bar

In doing so, I was able to add this to
 and it seems to align them correctly at any size.
background-color: #ffffff;
margin: auto;
max-width: 1028px;
width: 100%;

I was required to also remove the independent alignment code I wrote earlier.
From

 left: 20%;

From
 margin: auto;
 position: relative;

In doing these changes, it seems to work as I have expected it.

A: Try putting both logo and menu inside same div or even a  tag and apply a left margin to it.. I dont fully understanf how your page is built


text:
Q: How to share data across two different process in Python I have two different processes.

*

*Generator.py: create some data and dump to disk

*Control.py: Control script from where I can call Generator.py using subprocess.

What I am trying to achieve is that Control.py can receive the output of Generator.py without dumping it output to disk. I want to establish communication in such a way that Control.py can get data in memory from Generator.py.
Scenario is this:
Generator.py
def foo():
    myList = [1,2,3]
    return myList

foo()

Control.py:
handleA = subprocess.Popen(["python",  "Generator.py"])

My Objective is to avial myList in Control.py. In this case how can I do this ?
I was planning to use multiprocessing.Queue but question is how to share Queue object with Generator.py through subprocess ?
What is best way to achieve this ?


text:
Q: Listview visible child element In my application  i have used an "Listview". In that what i want is I have to get the count of the visible child.For example if i load that listview in my device first shoes 3 rows ,so i have to show in a textview that "Showing 3 of 10",and when user scroll the listview i have to update that textview according to scroll..I tried a lot but i didn't acheived this..
I tried for this also:
 int count=0;
for(int i = 0; i  <= listView.getLastVisiblePosition(); i++)
        {
            if(listView.getChildAt(i)!= null)
            {

                count++;  // saying that view that counts is the one that is not null, because sometimes you have partially visible items....
            }
        }

Always returning 0. Please help me to solve this.

A: Y i got the answer....
I implemented onscroll listener..
library_listview.setOnScrollListener(new OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,
                    int visibleItemCount, int totalItemCount) {
                // TODO Auto-generated method stub
                firstVisibleItem = firstVisibleItem+1;
                String vischild="Showing "+firstVisibleItem+" to "+visibleItemCount+" of "+totalItemCount+"";
                visiblechild.setText(vischild);

            }
        });

Thanks a lot..


text:
Q: UseEffect not triggered by dependencies? Someone can help me? I'd be really thankful :)
The problem here is that when the width and height changes, the UseEffect doesn't run again.
This is a textarea that is being resized...
const [elem, setElem] = useState<HTMLElement>(document.createElement('textarea'))
const width = window.getComputedStyle(elem, null).getPropertyValue("width");
const height = window.getComputedStyle(elem, null).getPropertyValue("height");

   useEffect(() => {
      setElem(document.getElementById("email") as HTMLElement)
      console.log(width, height)
   },[elem, width, height])

A: set the width and height using the useState.
const [width, setWidth] = useState(undefined);
const [height, setHeight] = useState(undefined);

useEffect(() => {
  const getWidth = () => window.getComputedStyle(elem, null).getPropertyValue("width");

  const getHeight = () => window.getComputedStyle(elem, null).getPropertyValue("height");
  const resizeListener = () => {
      setWidth(getWidth())
      setHeight(getHeight())
    };

  window.addEventListener('resize', resizeListener);

  resizeListener();
  // Don't foget cleanup!
  return () => window.removeEventListener('resize', resizeListener);
  // There's a dependency on the element, so if that changes, re-run the effect
}, [elem])

Attach the resize event listener and update width and height using setWidth and setHeight.

A: @William-wang has the right idea. Your code wouldn't retrigger the effect because the values never change except potentially when the code re-renders for other reasons.
While his method using a resize listener on the window will update the width and height, it only happens when the window's size changes.
I've modified the code to use the newer Resize Observer api. More details in How to detect DIV's dimension changed?.
This way, it's possible to get accurate and up-to-date size changes. The only issue with this approach is that older browsers don't support it. Though it does seem to be supported by all modern main browsers at this point.

const { useState, useEffect, useRef } = React;
function Example() {
  const elemRef = useRef(null);
  const [width, setWidth] = useState(undefined);
  const [height, setHeight] = useState(undefined);

  useEffect(() => {
    if (!elemRef.current) {
      return;
    }
    const resizeListener = () => {
      setWidth(elemRef.current.offsetWidth);
      setHeight(elemRef.current.offsetHeight);
    };
    const observer = new ResizeObserver(resizeListener);
    observer.observe(elemRef.current);
    // Don't foget cleanup!
    return () => observer.disconnect();
  }, []);

  return (

      width: {width}

      height: {height}

      <textarea ref={elemRef} />

  );
}

ReactDOM.render(<Example />, document.getElementById('root'));


text:
Q: facebook login through UIWebview using swfit shows blank I have a simple ios app that displays a website using WebView. The website has the option to login using facebook. If I navigated that website using a web browser and login using FB, it works fine, however, when I login to that website through my IOS app using a webview, all I get is a blank page after login.
I am using Swift as my language (and I am very new to this that is why I only use a webview instead of building the whole app using native app), and I have looked around and couldn't find the current solution, and didn't work, perhaps because the examples I have seen using objective-C instead of swift?
I have installed the facebook SDK and followed the instructions according to their docs, but again, all examples are login through a native app instead of webview. So, after I installed the FDK and added the frameworks, I don't know how to connect it to my code.
Below is my code to load the webpage if anyone knows a simple solution based on the code below that would be awesome!:
@IBOutlet var Webview: UIWebView!

var URLPath = "http://myfactdomain.com"

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    loadAddressURL()
}

func loadAddressURL() {
    let requestURL = NSURL(string: URLPath)
    let request = NSURLRequest(url: requestURL as! URL)
    Webview.loadRequest(request as URLRequest)

}

Thanks in advance

A: You are probably missing this in your info.plist, go to your info.plist and add this, you need this whenever your app needs to load a third party web url.

Code:
    @IBOutlet var fbWebView: UIWebView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let fbURL = NSURL(string: "https://www.facebook.com/")
    let request = NSURLRequest(url: fbURL! as URL)
    fbWebView.loadRequest(request as URLRequest)
}


text:
Q: Mac ports Mysql install I completed my install on Leopard with Mac Ports. I also installed Mysqld via Mac Ports for use with python. I set the password for mysql on mysql start. Everything seemed to be fine except when I invoke mysql-start from the command line now I get this: mysql-start
*****Password:
Starting MySQL
. SUCCESS!
demetrius-fords-macbook-pro-17:~ demet8$
I also get a system que stating:Do you want mysqld to accepting incoming notifications.....
So I kinda think I am activating mysqld, not the actual mysql command interpreter. I can use mysql-stop with no problem to shut the server down. Lastly in the Python interpreter when I run:  import MySQLdb I get this:
/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/MySQLdb/__init__.py:34: DeprecationWarning: the sets module is deprecated
  from sets import ImmutableSet
I don't think this affects mysqld @ all. I don't have the mysql default socket in my path via bash_login. Do I need to do that? thank you....

A: The command for the client is normally mysql (see MySql docs) However in macports they have appended the major version number so try mysql5
The python error is only a depreciation so can be ignored


text:
Q: Merge two Json.NET arrays by concatenating contained elements I have two JToken's that represent JSON arrays of objects and I would like to merge them. JToken has a method Concat but it produces null as result when I try to use it.
Action<JToken> Ok = (x) =>
{
    Debug.WriteLine(x);
    /* outputs
    [
      {
        "id": 1,
      },
      {
        "id": 2,
      }
    ]
    */

    x = (x).Concat<JToken>(x) as JToken;
    Debug.WriteLine(x); // null
};

How can I make it work?

A: JToken.FromObject(x.Concat(x))

A: Use JContainer.Merge() with MergeArrayHandling.Concat.
This is available starting with Json.NET 6 Release 4. So if your arrays are in a JContainer (e.g. a JObject), this is a simple and robust solution.
Example:
JObject o1 = JObject.Parse(@"{
  'FirstName': 'John',
  'LastName': 'Smith',
  'Enabled': false,
  'Roles': [ 'User' ]
}");
JObject o2 = JObject.Parse(@"{
  'Enabled': true,
  'Roles': [ 'Operator', 'Admin' ]
}");

o1.Merge(o2, new JsonMergeSettings { MergeArrayHandling = MergeArrayHandling.Concat });

string json = o1.ToString();
// {
//   "FirstName": "John",
//   "LastName": "Smith",
//   "Enabled": true,
//   "Roles": [
//     "User",
//     "Operator",
//     "Admin"
//   ]
// }

A: I needed same, here's what I came up with
https://github.com/MrAntix/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json/Linq/MergeExtensions.cs
public static void MergeInto(
    this JContainer left, JToken right, MergeOptions options)
{
    foreach (var rightChild in right.Children<JProperty>())
    {
        var rightChildProperty = rightChild;
        var leftPropertyValue = left.SelectToken(rightChildProperty.Name);

        if (leftPropertyValue == null)
        {
            // no matching property, just add
            left.Add(rightChild);
        }
        else
        {
            var leftProperty = (JProperty) leftPropertyValue.Parent;

            var leftArray = leftPropertyValue as JArray;
            var rightArray = rightChildProperty.Value as JArray;
            if (leftArray != null && rightArray != null)
            {
                switch (options.ArrayHandling)
                {
                    case MergeOptionArrayHandling.Concat:

                        foreach (var rightValue in rightArray)
                        {
                            leftArray.Add(rightValue);
                        }

                        break;
                    case MergeOptionArrayHandling.Overwrite:

                        leftProperty.Value = rightChildProperty.Value;
                        break;
                }
            }

            else
            {
                var leftObject = leftPropertyValue as JObject;
                if (leftObject == null)
                {
                    // replace value
                    leftProperty.Value = rightChildProperty.Value;
                }

                else
                    // recurse object
                    MergeInto(leftObject, rightChildProperty.Value, options);
            }
        }
    }
}


text:
Q: flatten an array of objects recursively I have the following array of objects.. How can I flatten a multi-dimensional array of objects into a single dimensional array of objects?
[{
    "name":"Locations",
    "children":[
        {
            "name":"U.S."
        },
        {
            "name":"Canada"
        },
        {
            "name":"London"
        }
    ]
},{
    "name":"Benefits",
    "children":[
        {
            "name":"U.S. Benefits",

            "children":[
                {
                    "name":"U.S. Benefits at a Glance"
                },
                {
                    "name":"U.S. Holiday Calendar"
                }
            ]
        },
        {
            "name":"London Benefits",
            "children":[
                {
                    "name":"London Benefits at a Glance"
                },
                {
                    "name":"London Holiday Calendar"
                }
            ]
        },
        {
            "name":"India Benefits",
            "children":[
                {
                    "name":"India Benefits at a Glance"
                },
                {
                    "name":"India Holiday Calendar"
                }
            ]
        }
    ]
}]

I need all the children to be in the same level as their parents in a single dimensional array.Any help will be appreciated.

A: You can do this without lodash with reduce and spread syntax. You just need to use recursion for children.

const data = [{"name":"Locations","children":[{"name":"U.S."},{"name":"Canada"},{"name":"London"}]},{"name":"Benefits","children":[{"name":"U.S. Benefits","children":[{"name":"U.S. Benefits at a Glance"},{"name":"U.S. Holiday Calendar"}]},{"name":"London Benefits","children":[{"name":"London Benefits at a Glance"},{"name":"London Holiday Calendar"}]},{"name":"India Benefits","children":[{"name":"India Benefits at a Glance"},{"name":"India Holiday Calendar"}]}]}]

const flatten = data => {
  return data.reduce((r, { children, ...rest}) => {
    r.push(rest);
    if (children) r.push(...flatten(children));
    return r;
  }, [])
}

console.log(flatten(data))

A: Modified answer of @nenad-vracar to more reusable style:

const mock = [{"name":"Locations","children":[{"name":"U.S."},{"name":"Canada"},{"name":"London"}]},{"name":"Benefits","children":[{"name":"U.S. Benefits","children":[{"name":"U.S. Benefits at a Glance"},{"name":"U.S. Holiday Calendar"}]},{"name":"London Benefits","children":[{"name":"London Benefits at a Glance"},{"name":"London Holiday Calendar"}]},{"name":"India Benefits","children":[{"name":"India Benefits at a Glance"},{"name":"India Holiday Calendar"}]}]}];

const flatDeepByKey = (data, key) => {
  return data.reduce((prev, el) => {
    prev.push(el);
    if (el[key]) {
      prev.push(...flatDeepByKey(el[key], key))
    };
    return prev;
  }, [])
};

console.log(flatDeepByKey(mock, 'children'));

A: You can perform a recursive loop-through and append to a running list by using a helper-function.
Note: If you want to remove the "root" dummy-node, just slice(1) the array.

var flattened = flattenTree({
  "name" : "root",            // Need a root entry, because the data is an array
  "children" : getData()      // Grab the data at the bottom
}, {
  nameKey : 'name',           // The name key; configurable option
  childrenKey : 'children'    // The children key; configurable option
});

console.log(flattened);       // Flattened data printed to the console

function flattenTree(tree, options) {
  options = options || {};
  var nameKey = options.nameKey || 'name';
  var childrenKey = options.childrenKey || 'children'
  var resultList = [];
  flattenTreeRecurse(tree, resultList, nameKey, childrenKey);
  return resultList;
}

/** @private -- Recursive inner-call */
function flattenTreeRecurse(tree, list, nameKey, childrenKey) {
  var entry = {};
  entry[nameKey] = tree[nameKey];
  list.push(entry);
  if (tree[childrenKey] && tree[childrenKey].length > 0) {
    tree[childrenKey].forEach(child => flattenTreeRecurse(child, list, nameKey, childrenKey));
  }
}

function getData() {
  return [{
    "name": "Locations",
    "children": [{
      "name": "U.S."
    }, {
      "name": "Canada"
    }, {
      "name": "London"
    }]
  }, {
    "name": "Benefits",
    "children": [{
        "name": "U.S. Benefits",

        "children": [{
          "name": "U.S. Benefits at a Glance"
        }, {
          "name": "U.S. Holiday Calendar"
        }]
      },
      {
        "name": "London Benefits",
        "children": [{
          "name": "London Benefits at a Glance"
        }, {
          "name": "London Holiday Calendar"
        }]
      },
      {
        "name": "India Benefits",
        "children": [{
          "name": "India Benefits at a Glance"
        }, {
          "name": "India Holiday Calendar"
        }]
      }
    ]
  }];
}
.as-console-wrapper { top: 0; max-height: 100% !important; }


text:
Q: MediaElement.js - how can I set the default image that is displayed? Is there a way to set the initial player to one of the following:

*

*To a specific image file, then switch to the video when play is selected/fired

*Set the initial image to one of the frames within the video

Thanks

A: *

*Inside the video tag specify an attribute poster="path/to/image".
and assign a value to an image.


text:
Q: Volume of a cylinder: liquid vs solid Apologies if this question is too much high school maths for the site, I'm a refugee from the webmaster stack site, and thought I might find some help here.
The question concerns candle making (in the real world). I'm thinking of purchasing some large pillar candle moulds from a company in Australia (can't find the right size anywhere else) and I need to check that I can melt enough wax to fill a single mould in one go and if not figure out what size boiler I should buy.
Problem is wax is sold in dry weights and the volume is calculated in, well, liquid volume. I don't know how to translate between the two.

*

*Volume is V =
πr2h.

*Mould is 100mm diameter and 241mm tall

*= 7574285.714285708 Cubic millimeters

*= 7.574285714 cubic liters.

So, the problems are these:

*

*Basically the result doesn't make complete sense to me - it shouldn't be that large! Have I done the conversion incorrectly or is there a difference that I'm unaware of between American and British volume calculations (I'm a Brit).

*Candle wax is sold in dry kilograms, I've seen various conversion charts online, but they often seem to be guess work. Is there a simple formula for converting a dry weight of a solid into it's resulting liquid volume.

Apologies if this is too simple or the solution is obvious, and thanks in advance for your help.

A: As pointed out in comments, the computation is off by $4$ due to the diameter being twice the radius. A cylinder of radius $50/1000$ meters and height $241/1000$ meters has volume of about $1.89$ liters. Using the wax density  of $930$ kg/L yields $1.76$ kg.
By the way, "cubic liters" is incorrect since a liter is a measure of volume.


text:
Q: Why the Monte Carlo Control algorithm is written this way? I am having trouble to understand this algorithm, since this is not how I would have written it.
To me, we should first start to fix a policy. Then, we evaluate the Q values associated with this policy by doing exploration and reducing the probability of exploring after each episode. Now we have a good estimate of Q for this policy, we can improve the policy by taking the argmax of Q (it will improve the policy with the policy improvement theorem). And we repeat it again and again.
Here, instead, we are updating Q with a new episode sampled with the current policy. However, this Q we are updating was computed using previous episodes sampled from previous policies. How can you have a good estimate of Q for a specific policy with computations from other policies and only one episode from that policy?
Moreover, the policy improvement theorem states that we actually improve the policy if Q is computed exactly. Here, this is clearly not the case, and it motivates me to follow the first approach that I explained.
Can you tell if my approach has a name, and why the Monte Carlo Control would be more efficient?


text:
Q: Putting Variable with in single quotes? Hi all I am making a request to the Campaign Monitor API and the data has to be held with in single quotes as a string but in JSON format. As it has to be single quotes I am unable to put in any variable values. Below is the code.
response = HTTParty.post(url,
:basic_auth => auth, :body => '{
            "EmailAddress":"js@mike.com",
            "Name":"#{@fname}",
            "CustomFields":[
                  {
                            "Key":"firstName",
                            "Value":"#{@fname}"
                        },
                        {
                          "Key":"country",
                            "Value":"#{@country}"
                        }
                        ],
            "Resubscribe":true,
            "RestartSubscriptionBasedAutoresponders":true
        }')

I have tried a few different methods such as breaking the string up and piecing it back together with the variable with in double quotes but that has failed as well for the request to be successful it has to be exact.

A: Instead of building a JSON structure by hand, you can build a Ruby hash and convert it to JSON:
require 'json'

data = {
  'EmailAddress' => 'js@mike.com',
  'Name' => @fname,
  'CustomFields' => [
    { 'Key' => 'firstName', 'Value' => @fname },
    { 'Key' => 'country', 'Value' => @country }
  ],
  'Resubscribe' => true,
  'RestartSubscriptionBasedAutoresponders' => true
}

response = HTTParty.post(url, basic_auth: auth, body: data.to_json)

Also note that there's a Ruby gem for the Campaign Monitor API: createsend-ruby
Using the gem, the above code translates to:
custom_fields = [
  { 'Key' => 'firstName', 'Value' => @fname },
  { 'Key' => 'country', 'Value' => @country }
]
response = CreateSend::Subscriber.add(auth, list_id, 'js@mike.com', @fname, custom_fields, true, true)

A: you can try with heredoc :
response = HTTParty.post(url,
  :basic_auth => auth, :body => <<-BODY_CONTENT
  {
        "EmailAddress":"js@mike.com",
        "Name":"#{@fname}",
        "CustomFields":[
              {
                        "Key":"firstName",
                        "Value":"#{@fname}"
                    },
                    {
                      "Key":"country",
                        "Value":"#{@country}"
                    }
                    ],
        "Resubscribe":true,
        "RestartSubscriptionBasedAutoresponders":true
  }
BODY_CONTENT
)

A: You can use heredoc as explained here

Double-quoting rules are also followed if you put double quotes around
  the identifier. However, do not put double quotes around the
  terminator.

puts <<"QUIZ"
Student: #{name}

1.\tQuestion: What is 4+5?
\tAnswer: The sum of 4 and 5 is #{4+5}
QUIZ

A: You can use here documents:
name = 'John'
<<EOS
This is #{name}
EOS

Alternatively you can use flexible quotes, they can handle both ' and " characters:
name = 'John'
%{
This is #{name}
}

Flexible quoting works with %() and %!! as well.


text:
Q: What's the solution to this conditional probability problem? Knowing that in the first 3 draws without replacement from a deck of 52 french cards (26 red|26 black) at least one red card has been drawn, what is the probability that the 2nd draw has been a red card?
How would you solve this problem?

A: Hint
First, try to express the probability in terms of conditionals:
$$
\Pr\{\text{2nd Draw being red}|\text{Having at least one red card drawn}\} =
{
\Pr\{\text{2nd Draw being red and having at least one red card drawn}\}\over
\Pr\{\text{Having at least one red card drawn}\}
}
=
{
\Pr\{\text{2nd Draw being red}\}\over
\Pr\{\text{Having at least one red card drawn}\}
}
$$Now, finding the probabilities of the numerator and the denominator should be easy.

A: At the first 3 cards at least one red card has been drawn.
1) 2 black & 1 red cards
2) 1 black & 2 red cards
3) 3 red cards
We don't know it is case 1, 2, or 3.
We have to consider all the possibilities.
Case 1)
First, what is the probability that we are in case 1?  It is important, because case 1 happens much more frequently than the other cases, we have to give a higher weight.
And then calculate the probability the next one is red under the condition of case 1.
Pr(case1) = $ \frac{{26 \choose 2}{26 \choose 1}}{52 \choose 3}$
This is not the probability I want to use. What I want to use is the probability of case 1 under the condition of at least 1 red card drawn.
Therefore Pr(case1|at least 1 red) = Pr(case 1| Case1 or Case 2 or Case3)
$=\frac{\text{Pr(case1)}}{\text{Pr(case 1)+Pr(case 2)+Pr(case 3)}}$
Pr(red|case1) = $\frac{25}{49}  $
where, 25 is the number of red cards remain under the case 1.
And 49 is the number of total cards.
Pr(red & case 1|at least 1 red) = Pr(red|case1)xPr(case1|At least 1 red)
And repeat the calculation for cases 2 and 3.
Pr(red|Case1 or case2 or case3) = Pr(red & case 1|at least 1 red) + Pr(red & case 2|at least 1 red) + Pr(red & case 3| at least 1 red)


text:
Q: Path unspecified in Visual Studio Code? Running
/usr/bin/python "c:\Users\owner\Documents\GitHub\ud120-projects\tools\startup.py"

The system cannot find the path specified.
I can access the .py and edit it and all, but I can't run it?
What is the issue?

A: You are probably using code-runner to run your python script and your path to python is not /usr/bin/python. The 0.9.0 update added support to shebang, which is overriding your executorMap configuration. Fortunatly, the 0.9.1 update added an option to ignore the shebang settings, which you can find in user settings. Change
"code-runner.respectShebang": true
to
"code-runner.respectShebang": false and you should be good to go.

A: It's not that you can't run it, it's that Python cannot find it.
Check:
import os
# Access a particular environment variable
# check based on OS, notes below:
# os.name The name of the operating system dependent module imported.
# The following names have currently been registered:
# 'posix', 'nt', 'mac', 'os2', 'ce', 'java', 'riscos'.
if os.name == 'nt':
    print(os.environ['Path'])
else:
    print(os.environ['HOME'])
print('*----------------------------------*')
print(os.environ['PATH'])
print('*----------------------------------*')


text:
Q: Get specific object from JSON I have this:
'{
"Games": [
    {   "champion": 126,
        "season": 9
    },
    {
        "champion": 126,
        "season": 9
    }, {
        "champion": 126,
        "season": 8
    }`

And i want only to take champion number that's only from season 9. How can i do that?

A: You can use Array.find:
const champion = data.Games.find(({season}) => season === 9)

or ES5
var champion = data.Games.find(function(champion) {
   return champion.season === 9;
});

A: I believe you must iterate over the array with conditional logic to capture and return any values that you are looking for.
Something like:
for (var i = 0; i < Games.length; i++) {
    if (Games[i].season == 9) {
        return(Games[i].champion);
    }
}

A: Use Array.filter()
var season9 = Games.filter(function(elem) {
    return (elem.season === 9);
});

or in Es6
let season9 = Games.filter(elem => elem.season === 9);

then
var champions = season9.map(function(elem) {
   return elem.champion;
})

or in Es6
let champions = season9.map(elem => elem.champion);

console.log(champions) // => [126, 126]


text:
Q: C++ : Initializing base class constant static variable with different value in derived class? I have a base class A with a constant static variable a. I need that instances of class B have a different value for the static variable a. How could this be achieved, preferably with static initialization ?
class A {
public:
    static const int a;
};
const int A::a = 1;

class B : public A {
    // ???
    // How to set *a* to a value specific to instances of class B ?
};

A: You can't. There is one instance of the static variable that is shared by all derived classes.

A: Static members are unique in the application. There is a single A::a constant in your system. What you can do is create a B::a static constant in B that will hide the A::a static (if you don't use the fully qualified name:
class A {
public:
   static const int a = 10;
};
static const int A::a;
class B : public A {
public:
   static const int a = 20;
   static void test();
};
static const int B::a;
void B::test() {
   std::cout << a << std::endl;    // 20: B::a hides A::a
   std::cout << A::a << std::endl; // 10: fully qualified
}

A: You can do this with Curiously recurring template pattern (you'll have to lose the const though).
template <typename T>
class A {
public:
    static int a;
};

template <typename T>
int A<T>::a = 0;

class B : public A<B> {
    struct helper { // change the value for A<B>::a
        helper() { A<B>::a = 42; }
    };
    static helper h;
};
B::helper B::h;

A: May be we can try this way as below ::
The benefit of the below is that you don't have to write the code multiple times, but the actual generated code might be big.
#include <iostream>

using namespace std;
template <int t>
class Fighters {
protected :
    static const double Fattack;
    double Fhealth;
    static const double Fdamage;
    static int count;
public :
    Fighters(double Fh) : Fhealth(Fh) { }
    void FighterAttacked(double damage) {
        Fhealth -= damage;
    }
    double getHealth()
    {
        return Fhealth;
    }

    static int getCount()
    {
        //cout << count << endl;
        return count;
    }
};

const double Fighters<1>::Fdamage = 200.0f;
const double Fighters<1>::Fattack = 0.6f;
int Fighters<1>::count = 0;

class Humans : public Fighters<1> {
public :
    Humans(double Fh = 250) : Fighters<1>(Fh) { count++; }
};

const double Fighters<2>::Fdamage = 40.0f;
const double Fighters<2>::Fattack = 0.4f;
int Fighters<2>::count = 0;

class Skeletons : public Fighters<2> {
public :
    Skeletons(double Fh = 50) : Fighters<2>(Fh) { count++; }
};

int main()
{

    Humans h[100];
    Skeletons s[300];

    cout << Humans::getCount() << endl;
    cout << Skeletons::getCount() << endl;

    return 0;
}

This is part of my other code example .. don't mind many other data but concept can be seen.


text:
Q: Emulator not switching to next activity I am totally new to android programming.
I am doing a simple app in which I show a splash screen and then show the login screen. The problem is the emulator doesn't go beyond the splash screen.
AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sanginfo.loginsample"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="9"
    android:targetSdkVersion="18" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".Splash"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
     <activity
        android:name=".LoginActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="com.example.loginsample.LOGINACTIVITY" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>
</application>

 </manifest>

LoginActivity:
package com.sanginfo.loginsample;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Patterns;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

 public class LoginActivity extends Activity {

CharSequence userName;
String  passWord;
Boolean rememberme;
EditText username, password;
CheckBox tempchkrememberme;
Button login;
private SharedPreferences objSP;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

   /* if(objSP.getString("username", null) != null) {*/

    setContentView(R.layout.activity_login);
    // UI elements gets bind in form of Java Objects
    username = (EditText)findViewById(R.id.username);
    password = (EditText)findViewById(R.id.password);
    login = (Button)findViewById(R.id.login);
    tempchkrememberme = (CheckBox)findViewById(R.id.chkrememberme);

    objSP = this.getSharedPreferences("SharedPreferences", MODE_PRIVATE);
    SharedPreferences.Editor objEditor = objSP.edit();
    rememberme = objSP.getBoolean("rememberme", false);

    if (rememberme == true){
    username.setText(objSP.getString("username", ""));
    tempchkrememberme.setChecked(true);}
    //objEditor.putString("password", password.getText().toString());
    objEditor.commit();

    // now we have got the handle over the UI widgets
    // setting listener on Login Button
    // i.e. OnClick Event
    login.setOnClickListener(loginListener);
}
//}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.login, menu);
    return true;
}

 private OnClickListener loginListener = new OnClickListener() {
    public void onClick(View v) {
        SharedPreferences.Editor objEditor = objSP.edit();
//getting inputs from user and performing data operations
        userName=username.getText().toString();
        String strUsername = username.getText().toString();
        username = (EditText)findViewById(R.id.username);
        password = (EditText)findViewById(R.id.password);
        login = (Button)findViewById(R.id.login);

        tempchkrememberme = (CheckBox)findViewById(R.id.chkrememberme);

        if (userName.length()==0) {
            username.requestFocus();
            username.setError("Email is required.");
            return;
            }

            boolean  isEmailValid = Patterns.EMAIL_ADDRESS.matcher(userName).matches();
            if (isEmailValid==false){
            username.requestFocus();
            username.setError("Email invalid.");
            return;
            }

        if(password.getText().toString().length() == 0 ){
            password.requestFocus();
            password.setError( "Password is required." );
            return;
        }

        if (tempchkrememberme.isChecked()) {
            objEditor.putBoolean("rememberme", true);
            objEditor.putString("username", strUsername);
            //objEditor.putString("password", password);
            objEditor.commit();

        } else {
            objEditor.clear();
            objEditor.commit();

        }

          if(username.getText().toString().equals("aditya@sanginfo.com") &&
                      password.getText().toString().equals("password")){
// responding to the User inputs
                Toast.makeText(getApplicationContext(), "Login Successful!", Toast.LENGTH_LONG).show();

          }else
                Toast.makeText(getApplicationContext(), "Invalid Credentials!",     Toast.LENGTH_LONG).show();
    }
  };
}

Splash Class:
        package com.sanginfo.loginsample;

  import android.app.Activity;
 import android.content.Intent;
 import android.os.Bundle;

 public class Splash extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
         setContentView(R.layout.splash);
         Thread timer = new Thread(){
            public void Run(){
                try{
                    sleep(2000);
                }
                catch (InterruptedException ex){
                    ex.printStackTrace();
                }
                finally{
                    Intent openLoginActivity = new Intent(Splash.this, LoginActivity.class);
                    startActivity(openLoginActivity);
                }
            }
         };
         timer.start();
    }
}

EDIT:
Console:
 [2013-09-24 15:02:58 - LoginSample] Android Launch!
 [2013-09-24 15:02:58 - LoginSample] adb is running normally.
 [2013-09-24 15:02:58 - LoginSample] Performing com.sanginfo.loginsample.Splash activity launch
 [2013-09-24 15:02:58 - LoginSample] Automatic Target Mode: using existing emulator 'emulator-5554' running compatible AVD 'Nexus4'
 [2013-09-24 15:03:00 - LoginSample] Application already deployed. No need to reinstall.
 [2013-09-24 15:03:00 - LoginSample] Starting activity com.sanginfo.loginsample.Splash on device emulator-5554
 [2013-09-24 15:03:01 - LoginSample] ActivityManager: Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.sanginfo.loginsample/.Splash }
[2013-09-24 15:03:01 - LoginSample] ActivityManager: Warning: Activity not started, its current task has been brought to the front

The last two in Red.
LogCat: (All Es in Red)
 .....
 09-24 14:16:37.892: I/System.out(904): Sending WAIT chunk
 09-24 14:16:38.122: I/dalvikvm(904): Debugger is active
09-24 14:16:38.142: I/System.out(904): Debugger has connected
09-24 14:16:38.152: I/System.out(904): waiting for debugger to settle...
09-24 14:16:38.352: I/System.out(904): waiting for debugger to settle...
09-24 14:16:38.552: I/System.out(904): waiting for debugger to settle...
09-24 14:16:38.752: I/System.out(904): waiting for debugger to settle...
09-24 14:16:38.962: I/System.out(904): waiting for debugger to settle...
09-24 14:16:39.162: I/System.out(904): waiting for debugger to settle...
09-24 14:16:39.362: I/System.out(904): waiting for debugger to settle...
09-24 14:16:39.562: I/System.out(904): waiting for debugger to settle...
09-24 14:16:39.762: I/System.out(904): waiting for debugger to settle...
09-24 14:16:39.963: I/System.out(904): waiting for debugger to settle...
09-24 14:16:40.172: I/System.out(904): waiting for debugger to settle...
09-24 14:16:40.373: I/System.out(904): debugger has settled (1416)
09-24 14:16:42.502: D/gralloc_goldfish(904): Emulator without GPU emulation detected.
09-24 14:19:11.183: E/Trace(976): error opening trace file: No such file or directory (2)
09-24 14:19:12.423: D/gralloc_goldfish(976): Emulator without GPU emulation detected.
09-24 14:24:00.873: E/Trace(1024): error opening trace file: No such file or directory (2)
09-24 14:24:02.053: D/gralloc_goldfish(1024): Emulator without GPU emulation detected.
09-24 14:30:40.193: E/Trace(1070): error opening trace file: No such file or directory (2)
09-24 14:30:41.653: D/gralloc_goldfish(1070): Emulator without GPU emulation detected.
09-24 14:35:43.943: E/Trace(1117): error opening trace file: No such file or directory (2)
09-24 14:35:45.383: D/gralloc_goldfish(1117): Emulator without GPU emulation detected.
09-24 14:38:58.883: E/Trace(1191): error opening trace file: No such file or directory (2)
09-24 14:39:00.453: D/gralloc_goldfish(1191): Emulator without GPU emulation detected.
09-24 14:40:25.943: E/Trace(1237): error opening trace file: No such file or directory (2)
09-24 14:40:27.145: D/gralloc_goldfish(1237): Emulator without GPU emulation detected.
09-24 14:43:52.323: E/Trace(1309): error opening trace file: No such file or directory (2)
09-24 14:43:53.143: D/gralloc_goldfish(1309): Emulator without GPU emulation detected.
09-24 14:54:02.202: E/Trace(1358): error opening trace file: No such file or directory (2)
09-24 14:54:03.993: D/gralloc_goldfish(1358): Emulator without GPU emulation detected.

A: I think u have done wrong in intent-filter section
  First remove intent filter code in second activity and check the output and comment about it
Modify this line
 Intent openLoginActivity = new  Intent("com.sanginfo.loginsample.LOGINACTIVITY");

as
 Intent openLoginActivity = new  Intent("Splash.this","LOGINACTIVITY.class");

A: you should pass the intent using below constructor
  Intent it = new Intent(packageContext, cls);//

declare your intent like this
 Intent it = new Intent(splash.this, LOGINACTIVITY.class);//

constructor that you are using is for implicit intent which takes action as parameter and
change
  <action android:name="com.sanginfo.loginsample.LOGINACTIVITY" />

to
   <action android:name="com.sanginfo.loginsample.LoginActivity" />

A: Please have a look at intent,Where you have to set the activity name at which you wants to go.
Thread th = new Thread(){
    public void run()
    {
        try {
            sleep(4000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally
        {
            Intent in = new Intent(getApplicationContext(),your class name here.class);
            startActivity(in);
        }
    }
};th.start();

A: Try removing the following code from your LoginActivity manifest.
    <intent-filter>
        <action android:name="com.sanginfo.loginsample.LOGINACTIVITY" />

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


text:
Q: Resizing images with batch script using ImageMagick I'm trying to write a batch file to resize all the images in a directory to 640 Pixel wide, placing the resized images into a sub-directory called "web-img" and the original pictures should be unchanged.
This was the code I wrote, but it is not working.
rem shu chetluru
@echo off
if not exist "C:\Users\Asus\Desktop\proj.uti.1\websize\web-img\nul" md "C:\Users\Asus\Desktop\proj.uti.1\websize\web-img"
mogrify -path "C:\Desktop\proj\websize*.jpg"  -resize 640@ "C:\Desktop\proj\websize\web-img"

Can someone please help me to complete and make the code work?
Thank you so much in advance.

A: Since the only info you gave us was "it is not working", I'm only guessing at your intent:
mogrify -path "C:\Desktop\proj\"  -resize 640@ *.jpg

Notes:

*

*This will resize ALL jpg images in the current directory.

*The new size will be a total of 640 pixels (width x height).  That seems CRAZY small (smaller than a 32x32 icon!  Are you sure that is what you want?)

*The files will be placed in C:\Desktop\proj\, but you went through the effort of making directory C:\Users\Asus\Desktop\proj.uti.1\websize\web-img Why aren't you using that directory??
You should add a lot more detail to your question.


text:
Q: Make the preprocessing of a dfm in the input column without the need to create the dfm Having a dataframe like this
dataf <- data.frame(id = c(1,2,3,4), text = c("Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s","Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now","There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour","a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum",""))

It is possible to make a text analysis preprocessing using the construction of dfm
myDfm <- myCorpus %>%
     tokens(remove_punct = TRUE, remove_numbers = TRUE, remove_symbols = TRUE)  %>%
     tokens_remove(pattern = c(stopwords(source = "smart"), mystopwords))  %>% tokens_wordstem() %>%
     dfm(verbose = FALSE) %>% dfm_trim(min_docfreq = 3, min_termfreq = 5)

Is there any alternative option to remover the stopwords stopwords(source = "smart"), make the wordstem and make the trim min_docfreq = 3, min_termfreq = 5 in the text column without need to create the dfm?

A: I'll answer this based on the question plus comment, since it seems you need a dgCMatrix class for what you want to do.  (This is what is returned by textmineR::CreateDtm().)  Fortunately, a quanteda dfm is a special type of dgCMatrix already.  So it would probably work as is, but if you want, it's also easy to convert -- just use as().
library("quanteda")
## Package version: 3.0.0
## Unicode version: 10.0
## ICU version: 61.1
## Parallel computing: 12 of 12 threads used.
## See https://quanteda.io for tutorials and examples.
data(nih_sample, package = "textmineR")

dfmat <- nih_sample %>%
  corpus(text_field = "ABSTRACT_TEXT", docid_field = "APPLICATION_ID") %>%
  tokens() %>%
  tokens_ngrams(n = 1:2) %>%
  dfm()
dtm2 <- as(dfmat, "dgCMatrix")

Now, dtm2 should work same as dtm as in the blog post.  (The features/columns are in a different order, but that should not matter for a matrix that will be input to a topic model.)  And: it's a WHOLE lot cleaner process.
Feel free here to insert additional tokens() options or dfm_trim() etc as you need from quanteda.


text:
Q: Application failed to start on shiny web server after a few days I have a running shiny app on a web server that worked fine until I would say last week. Now, on occasion (I guess every two days) the app stops working with the "Application failed to start" message. When I restart the shiny server, as I did just now, everything runs fine again.

https://butterlab.imb-mainz.de/flydev/
The funny thing is, I have other apps on this server as well, and they are not affected and run fine in parallel, even if this app failed.
I can not find any error message in the log files. And I am wondering: how I could debug this, since the app is now running fine?
Looking forward to any advice.
EDIT:
I checked the shiny-server.log file after the error occurred and I found the following message:
[2018-06-14 14:29:20.080] [WARN] shiny-server - RobustSockJS collision: MqU4rgur76RPgjJIPr
[2018-06-15 01:28:18.398] [WARN] shiny-server - Error handling message: Error: Discard position id too big
[2018-06-15 02:00:10.358] [INFO] shiny-server - Error getting worker: Error: The application took too long to respond.
[2018-06-15 02:00:10.364] [INFO] shiny-server - Error getting worker: Error: The application took too long to respond.

The last message gets repeated whenever someone accesses the server.

A: So in the end, it seems this page solved my problem Error: Discard position id too big
I set app_init_timeout and app_idle_timeout both to 1800and since then I have no further problems.
Also the comment with the restart.txt file might be interesting. I thought about testing with a shell script if the page is still working, otherwise touching the txt.
http://docs.rstudio.com/shiny-server/#restarting-an-application
But as I said, in the end it works by adjusting the app_init_timeout and app_idle_timeout.


text:
Q: Entity Framework Cascade Delete I have Table A and Table B on SQL Server.
Table B has an foreign key to Table A.
I want to cascade delete Table B itens when I delete a Table A item.
How to set this on SQL Server and on Entity Data Model?

A: On the SQL server, set the Delete Rule in INSERT and UPDATE specification on the relationship property to Cascade.

A: Set CASCADE on the relationship in the Entity Model Designer...


text:
Q: iOS app crashes randomly in WebCore I have an iPad app that has UIWebview and it loads an URL. Problem is it crashes randomly and doesnt provide much info. I am using ARC.
Any thoughts please?
Thanks
image 1
image 2
image 3