text:
Q: How to override reset and validatePasswordWithDefaults in PasswordBroker Laravel 5 I'm really new to this framework, and it seem so magic to me.
I can't even find where it call the function reset() in route and controller.
but I know it's been call before controller after browsing around the googles for whole day.
Here's the problem,
I've been testing to override function reset and function validatePasswordWithDefaults in PasswordBroker
I do it by extends PasswordBroker, but seem like I have to fully migrate all the function in Illuminate\Auth\Passwords\PasswordBroker into my
App\Services\PasswordBroker else i will hit error:
Target [Illuminate\Contracts\Auth\UserProvider] is not instantiable

My sample code is here:
Custom PasswordServiceProviders that bind my PasswordBroker to Illuminate PasswordBroker:
<?php namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class PasswordResetServiceProvider extends ServiceProvider {

/**
 * Bootstrap the application services.
 *
 * @return void
 */
public function boot()
{
    //
}

/**
 * Register the application services.
 *
 * @return void
 */
public function register()
{
    //
    $this->app->bind(
        'Illuminate\Contracts\Auth\PasswordBroker','App\Services\PasswordBroker'
        );

}

}

Custom PasswordBroker:
<?php
    namespace App\Services;

    use Illuminate\Contracts\Auth\UserProvider;
    use Illuminate\Auth\Passwords\TokenRepositoryInterface;
    use Illuminate\Auth\Passwords\PasswordBroker as BasePasswordBroker;
    use Illuminate\Contracts\Auth\PasswordBroker as ContractPasswordBroker;

    use Closure;

    class PasswordBroker extends BasePasswordBroker
    {

        public function reset(array $credentials, Closure $callback)
        {
            dd($callback);
            $user = $this->validateReset($credentials);

            if ( ! $user instanceof CanResetPasswordContract)
            {
                return $user;
            }

            $pass = $credentials['password'];

            call_user_func($callback, $user, $pass);

            $this->tokens->delete($credentials['token']);

            return PasswordBrokerContract::PASSWORD_RESET;
        }

        protected function validatePasswordWithDefaults(array $credentials)
        {
            list($password, $confirm) = [
                $credentials['password'], $credentials['password_confirmation'],
            ];

            return $password === $confirm && mb_strlen($password) >= 4;
        }
    }
    ?>

A: This is not straightforward, on my opinion the framework shouldn't send an email so deep into the code and provide a way to override it from a controller.
I had to override the email sending because I needed to use Mandrill's api, so I had to send extra headers in the very instant the mail gets sent. This is what I did:

*

*Create a provider class on App\Providers\PasswordResetServiceProvider. I copied the framework's default provider (Illuminate\Auth\Passwords\PasswordResetServiceProvider) but I had to do some slight modifications on the order of the registrations and later on the way you retrieve the tokens service. Also you had to specify where your PasswordBroker is (in my case is on \App\Services\PasswordBroker)

 use Illuminate\Support\ServiceProvider;
 use Illuminate\Auth\Passwords\DatabaseTokenRepository as DbRepository;

 class PasswordResetServiceProvider extends ServiceProvider {

/**
 * Indicates if loading of the provider is deferred.
 *
 * @var bool
 */
protected $defer = true;

/**
 * Register the service provider.
 *
 * @return void
 */
public function register()
{
    $this->registerTokenRepository();
    $this->registerPasswordBroker();
}

/**
 * Register the password broker instance.
 *
 * @return void
 */
protected function registerPasswordBroker()
{
    return $this->app->singleton('auth.password', function($app)
    {
        // The password token repository is responsible for storing the email addresses
        // and password reset tokens. It will be used to verify the tokens are valid
        // for the given e-mail addresses. We will resolve an implementation here.
        $tokens = $app['auth.password.tokens'];

        $users = $app['auth']->driver()->getProvider();

        $view = $app['config']['auth.password.email'];

        // The password broker uses a token repository to validate tokens and send user
        // password e-mails, as well as validating that password reset process as an
        // aggregate service of sorts providing a convenient interface for resets.
        return new \App\Services\PasswordBroker(
            $tokens, $users, $app['mailer'], $view
        );
    });
}

/**
 * Register the token repository implementation.
 *
 * @return void
 */
protected function registerTokenRepository()
{
    $this->app->singleton('auth.password.tokens', function($app)
    {
        $connection = $app['db']->connection();

        // The database token repository is an implementation of the token repository
        // interface, and is responsible for the actual storing of auth tokens and
        // their e-mail addresses. We will inject this table and hash key to it.
        $table = $app['config']['auth.password.table'];

        $key = $app['config']['app.key'];

        $expire = $app['config']->get('auth.password.expire', 60);

        return new DbRepository($connection, $table, $key, $expire);
    });
}

/**
 * Get the services provided by the provider.
 *
 * @return array
 */
public function provides()
{
    return ['auth.password', 'auth.password.tokens'];
}

}

*Create the class \App\Services\PasswordBroker, there you can override emailResetLink(), there is no mystery on that step.

*Register the new provider on the providers array from config\app.php (App\Providers\PasswordResetServiceProvider). Comment out the default one (Illuminate\Auth\Passwords\PasswordResetServiceProvider)


text:
Q: Correct way to split UTF-8 String I want to split a utf-8 string.
I have tried the StringTokenizer but it fails.
The title should be "0" but it shows as "عُدي_صدّام_حُسين".
    String test = "en.m عُدي_صدّام_حُسين 1 0";

    StringTokenizer stringTokenizer = new StringTokenizer(test);
    String code = stringTokenizer.nextToken();
    String title = stringTokenizer.nextToken();

What is the correct way to split a utf-8 string?

A: The problem here is that the Arabic text isn't "at the end" of the string.
For example, if I select the contents of the string literal (in Chrome), moving my mouse from left-to-right, it selects the en.m first, then selects all of the arabic text, then the 0 1. The text just looks "at the end" because that's how it is being rendered.
The string, as specified in your Java source code actually does have the عُدي_صدّام_حُسين as the second token. So, you're splitting it correctly, you're just not splitting what you think you're splitting.

A: Generally, there is not the correct way, but I normally use the method substring() of the String class (see here). You can pass it either the begin index to make it return the substring from that index to the original String's end or two bounds of the substring within the original String. With the method indexOf() of the same class you can locate a character within the original String if you do not know its index.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to make clickable image that open new tab with message I have HTML and CSS page and I need to make one image clickable and have to open new page with message "You order is complete"
The button actually confirm form with several fields over which it is located.
Can you help me do that?

A: Well at the very basic you can wrap your image in a hyperlink.
Adding the attribute target="_blank" tells the browser to open the link in a new tab or window.

A: This code may help you open your desired new page with the contents you mentioned.

and myPage.html will contain the following

You order is complete

</body


text:
Q: CSS: Three boxes such that smaller box is inside the bigger box which is inside the biggest box I am new to CSS and I came across a coding question where I had to create three boxes one inside the other. Below is my code. As of now it only creates two boxes. What changes should I make in my code to include the third box.

#first {
  width: 100px;
  height: 100px;
  background: red;
  overflow: hidden;
}

#first #second {
  position: relative;
  width: 50%;
  height: 50%;
  margin: auto;
  margin-top: 25%;
  background: black;
}

#first #second #third {
  position: relative;
  width: 25%;
  height: 25%;
  margin: auto;
  margin-top: 25%;
  background: orange;
}

A:

#first {
  width: 100px;
  height: 100px;
  background: red;
  overflow: hidden;
}

#second {
  position: relative;
  width: 50px;
  height: 50px;
  margin: auto;
  margin-top: 25px;
  background: black;
  overflow: hidden;
}

#third {
  width: 12.5px;
  height: 12.5px;
  margin-top: 18.75px;
  margin-left: 18.75px;
  background: orange;
}

A: You missed to place the #third div inside #second div. Try placing it inside the second one. Try this one.

A: It's not a matter of css rather html.

In the code above. Third is the child of Second and Second is child of First.


text:
Q: php Length Required error when trying to send request using curl soap I need to form a request under this format:
    POST /CJW/cjws.asmx HTTP/1.1
Host: www.somesite.abc.edu.sg
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://tempuri.org/GetAll"

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <GetAll xmlns="http://tempuri.org/">
      <ErrorMsg>string</ErrorMsg>
    </GetAll>
  </soap:Body>
</soap:Envelope>

So here is what I tried:
<?php
$username = '';
$password = '';
$credentials = $username.":".$password;
//$url = "http://tempuri.org/GetAll";
$url = "http://www.somesite.abc.edu.sg/GetAll";

$soap_request = '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <GetAll xmlns="http://tempuri.org/">
      <ErrorMsg>string</ErrorMsg>
    </GetAll>
  </soap:Body>
</soap:Envelope>';

$header = array(
"POST /CJW/cjws.asmx HTTP/1.1 \n",
"Host: www.somesite.abc.edu.sg \n",
"Content-type: text/xml; charset=\"utf-8\" \n",
"Content-length: ".strlen($soap_request)." \n",
"SOAPAction: ".$url." \n");

$curl = curl_init();

curl_setopt($curl, CURLOPT_PROXY, '127.0.0.1:8888');
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC ) ;
curl_setopt($curl, CURLOPT_USERPWD, $credentials);
curl_setopt($curl, CURLOPT_SSLVERSION,3);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $soap_request );
curl_setopt($curl, CURLOPT_HTTPHEADER,     $header);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
curl_setopt($curl, CURLOPT_URL, $url);

// perform the request

$xml_result = curl_exec($curl);
// check for errors
if ($xml_result === false) {
$error_occurred = true;
}
else {

    echo $xml_result;
}
?>

But I cannot get the response correctly, actually, I do not see the response except this error:
Length Required
HTTP Error 411. The request must be chunked or have a content length.

I tried many way including remove the length part, change it with some fix number, etc. but it changes nothing.
So what I am doing wrong here ? How is the right way ?
Thanks a lot !

A: (You can remove Host: and Content-Length: from the headers you synthesize because curl will add them both itself if you don't set them.)
You should inspect your outgoing request in detail and verify that it looks exactly the way you want it to. Using CURLOPT_VERBOSE is usually enough but you need to be able to get that output somewhere for inspection.
I believe your custom headers all have a trailing space and a newline that you should remove. They will severely screw up the outgoing request. Oh, and the POST part must be removed from your custom headers (it is not a header, it is the "request-line").


text:
Q: inline keyboard handlers in node-telegram-bot-api package I'm currently build a telegram bot and i have one issue.
In my case has had a few inline keyboard. here are

but all inline keyboard has a one handler
bot.on('callback_query',query=>{
    bot.answerCallbackQuery(query.id,{text:query.data,show_alert:false})
    console.log(query)
})

so i will need check with a if else condition for all handler in callback_query event but i don't like this way. Then i will had find one to get rid of 'if else'. In this i will had use a EventEmitter to separate each handler
emitter.on('eventOne',(chatId)=>{
    ... business logic of handler
})
emitter.on('eventTwo',(chatId)=>{
    ... business logic of handler
})
bot.on('callback_query',query=>{
    emitter.emit(query.data,query.message.chat.id)
    bot.answerCallbackQuery(query.id,{text:query.data,show_alert:false})
    console.log(query)
})

is this way right or not, if not i need a right implementation of this issue.
Sorry for grammar mistakes, my native language is Uzbek ;)
I need a right implamentation of inline_keyboards handler


text:
Q: Sum of datetime column in sql 05 I have a column named as "total_hours_worked" in my sql table which is of "datetime" datatype
I want to find out the total of "total hours worked in sql server".
How to do this?
I googled but didn't got a practical solution.

A: Something like this if I understand your data correctly.
declare @T table
(
  total_hours_worked datetime
)

insert into @T values ('05:30:00')
insert into @T values ('10:00:00')
insert into @T values ('15:00:00')

select sum(datediff(minute, 0, total_hours_worked)) / 60.0 as hours_worked
from @T

Result:
hours_worked
---------------------------------------
30.500000

If you only need to store the hours you should consider an integer datatype instead of datetime. It will be more efficient and easier to deal with.

A: Try this.Here I considered seconds also.
declare @T table
(
  total_hours_worked datetime
)

insert into @T values ('05:30:00')
insert into @T values ('10:00:00')
insert into @T values ('15:00:00')
insert into @T values ('05:25:45')

select SUM((DATEPART(hh,total_hours_worked)*60)+DATEPART(mi,total_hours_worked)+(DATEPART(ss,total_hours_worked)/(60.0)))/60.0  as TotalHours from @T


text:
Q: Infopath hanging on "Sending data to the server" even though data was sent. but workflows don't begin My InfoPath form had been working fine but suddenly any new entries after submit hang on "Sending data to the server".
Oddly enough the new data is written BUT the workflows that should begin now do not.
The other clue is that I can still start the approval workflow manually but when I try to approve, after clicking "approve" now it would just be stuck on "Working on it  - please wait while your task is updated."
And lastly when I try to manually approve it through "workflows" on the browser, I get
Sorry, something went wrong
This task is currently locked by a running workflow and cannot be edited.

I have scoured the web for answers, I have tried everything from clearing the browser cache to swapping over a "larger" copy of Core.js and nothing.
I could sure use some good karma back my way. I have a day trying to get this to work.

A: About your first issue:
Which browser did you use?
I suggest you use the IE, if you use the IE11, I suggest you use the IE11 32 bit.
This is a reference about a similar case.
About your second issue:
You can add the UpdateTask activity in your workflow to update properties.
This is similar case for your reference.


text:
Q: What is the maximum number of O.W.L. classes you can take at Hogwarts? Hermione takes twelve classes with a time-turner, and she drops two to get ten O.W.L.'s. You can even take more because Percy (and others) ended up with twelve O.W.L.'s. possibly without a time-turner.
Is twelve the most classes a Hogwarts student can take in their O.W.L. years?

A: There is no clear answer to how many classes the school offers total, 12 seems to be the max owls anyone gets.
So how many classes you can take without needing a time tuner, would depend entirely on the current teachers class schedules.
Hermione needed a time tuner due to her classes being scheduled in the same block, but during other years those classes may have all been staggered enough for someone like Bill or Crouch Jr. to take 12 classes without a Time Tuner.

I've been turning it back so I could do
  hours over again, that's how I've been doing several lessons at
  once, see? - Prisoner of Azkaban

On top of that Bill and Crouch Jr. could have had Time-Tuners anyway, but since their forbidden to tell anyone about it we wouldn't know.

A: I say that the maximum is twelve (12) because of the O.W.L. restriction placed on the question.
The courses offered at Hogwarts are as follows.
Core Classes:

*

*Astronomy

*Charms

*Defense Against Dark Arts

*Herbology

*History of Magic

*Potions

*Transfiguration

Electives:

*Arithmancy

*Care of Magical Creatures

*Divination

*Muggle Studies

*Ancient Runes

Offered based on demand:

*Alchemy (6th and 7th year only)

Since O.W.L.s are given in the fifth year of education, I do not think the exam would be given for Alchemy (or at least there is not information to determine this).
Note: If you prefer WoG statements over the Wikia, please refer to this writing.


text:
Q: Compare date if not null I need to find all the record with create date > X. X is a sql.Timestamp and might be null, in which case I want to just return all the records. So I tried: (createdAfter is Timestamp)
SELECT *
FROM sample AS s
WHERE s.isActive
  AND (:createdAfter ISNULL OR s.insert_time > :createdAfter)

But all I'm getting is
org.postgresql.util.PSQLException: ERROR: could not determine data type of parameter $1

However, if I'll do the same query where I'm checking for an arbitrary int to be null:
SELECT *
FROM trades
WHERE (:sInt ISNULL OR trades.insert_time > :createdAfter )

Then it works. What's wrong?

A: There is no simple solution if you want to stick with native queries like that. The null value is converted to a bytea value. See for example this and this.
That value is quite hard to be casted or compared to a timestamp value.
The problem is not so much with the first comparison it would be handled by using coalesce, like:
COALESCE(:createdAfter) ISNULL

because there is no comparison beteween actual values and the data type does not matter. But the comparison
sometimestamp::timestamp > null::bytea (casts just to show the actual types so not working)
would need more logic behind maybe procedure & exception handling or so, not sure.
So if JPQL or CriteriaQueries are not possible for you have only bad options:

*

*contruct the query by setting params by string concatenation or so (NOT! and not sure if realy works)

*use PreparedStatement queries, more code & effort

*also if using Hibernate,  using session api like in this answer

A: You can try using the pg_typeof function, which returns a text string, and using a CASE statement to force which comparisons are made (otherwise there's no guarantee that postgres will short-circuit the OR in the correct order). You can then force the correct conversion by converting to text and then back to timestamp, which is inelegant but should be effective.
SELECT *
FROM sample AS s
WHERE s.isActive
  AND
    CASE WHEN pg_typeof( :createdAfter ) = 'bytea' THEN TRUE
       WHEN s.insert_time > ( ( :createdAfter )::text)::timestamp THEN TRUE
       ELSE FALSE
    END


text:
Q: how to omit a commit while squashing I have 3 commits and i want to skip a commit -2 while rebasing into 1
say
commit -1
commit -2
commit -3

i did git rebase -i HEAD~3
pick commit -1
pick commit -2
squash commit -3

i tried like this  (removed the pick commit -2) but that deleted the commit -2 itself from git log :(
git rebase -i HEAD~3
pick commit -1
squash commit -3

Someone please help me how can i squash commit 1 and commit 3 using command only.

A: Easy, reorder the lines:
pick 1
squash 3
pick 2

This will rebase the history squashing 3 into 1 and moving commit 2 after.
From the help text:

These lines can be re-ordered; they are executed from top to bottom.

# Rebase 25c328e..a038737 onto 25c328e (2 commands)
#
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
# x, exec = run command (the rest of the line) using shell
# d, drop = remove commit
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out

A: If I'm understanding correctly, just reorder the commits:
pick commit -1
squash commit -3
pick commit -2

This would place commit -2 after -1 and -3; put -2 on top if you want it to come before.  (Commits are evaluated top to bottom.)

A: If you don't care about the history of the branch and the commits; you can start a branch from commit-4; cherry pick 1 and 3, squash them and then cherry pick commit-2. You will be on a new branch but it will have the end result you need. Also, I assumed the commits would not have conflicts.
    commit-1
    commit-2
    commit-3
    commit-4

git checkout commit-4
git checkout -b newbranch name
git cherry-pick commit-3 commit-1
git rebase and do the squash
git cherry-pick commit-2


text:
Q: chrome.hid.getDevices() and chrome.usb.getDevices() not returning any results I've run into what appears to be a basic problem with chrome.hid.getDevices() and chrome.usb.getDevices() not returning results. Positive it's a PEBKAC, not exactly sure where I'm going wrong, hope you guys can help.
I've setup a minimal example according to the Chrome developer documentation. manifest.json setup with correct permissions to access USB and HID. Experimental API flag set in chrome://flags. System information shows full list of attached USB devices.
Tested on Chrome Stable Version 49.0.2623.112 (64-bit) on Mac OS X 10.10.5 and Chrome Stable Version 49.0.2623.111 on Chrome OS.
When the sample is run, I see no devices returned from chrome.hid.getDevices() or chrome.usb.getDevices(). chrome.usb.getUserSelectedDevices() does show the USB dialog box; on Mac OS X it is populated correctly, on Chrome OS there are no devices.
Hoping someone can lart me in the right direction. Thanks heaps.

A: There are a few minor issues with the example in your repo. Firstly according to the chrome.usb API documentation you must include vendorId and productId pairs for each device you want to use under the permissions in the manifest:
https://developer.chrome.com/apps/app_usb#manifest
for example:
"permissions": ["usb",
    {
        "usbDevices": [
            {
                "vendorId": 1626,
                "productId": 40961
            }
        ]
    }
]

You can get the IDs using your chrome.usb.getUserSelectedDevices example output.
Secondly your chrome.usb.getDevices() example is attempting to use chrome.hid.getDevices()


text:
Q: How interface works with generics subtyping in java? Consider the following classes.
class Shape {}
class Circle extends Shape {}
class Rectangle extends Shape {}

class Node <T> {}

// In main method
Node<Circle> circleNode = new Node<>();
Node<Shape> shapeNode = circleNode; // ERROR

Following code will not compile because even though Circle is a subtype of Shape. Because of generics subtyping.
But now consider the new Node class.
class Node<T> implements Comparable<T> {
    public int compareTo(T obj) { /* ... */ }
    // ...
}

// In main method
Node<String> stringNode = new Node<>();
Comparable<String> comparable = stringNode;

Following code successfully compile. But there is no explanation on Java Docs. How implementing an interface make it compile successfully. And I didn't understand what happened exactly.

A: You're comparing apples and oranges.
In your example, Node<Shape> is to Node<Circle> as List<Animal> is to List<Dog>.
However, Comparable<String> is to Node<String> as List<Animal> is to ArrayList<Animal>.
If you can have this parallelism clear in mind, all you need to remember is that a List<Dog> is not a List<Animal> and you have your answer.
stringNode is a Node<String>, and that means assigning that variable to a Comparable<String>-typed variable only requires the base type's relationship. That's because the declaration Node<T> implements Comparable<T> makes Node a Comparable subtype. With the type parameter being exactly the same, that makes Comparable<String> assignable from Node<String> (just as List<String> is assignable from ArrayList<String>)
In other words, the difference is not due to "implementing an interface make it compile successfully"... it's due to the fact that Node<Shape> is not assignable from Node<Circle> (which you seem to understand), whether node is an interface or not.

A: In 2nd example you're saying that for a given T a Node<T> is a Comparable<T>. Thus, for T = String you have Node<String> is a Comparable<String>.
However in 1st example you have 2 different types T and U where T is a U but there is nothing that says that Node<T> is a Node<U>.
You might want to look for covariance and contravariance to learn more on this topic.


text:
Q: Ruby - How do I sort one array with another array using sort_by? I'd like to sort the first array:
 filenames = ["z.pdf", "z.txt", "a.pdf", "z.rf", "a.rf","a.txt", "z.html", "a.html"]

by the following file's extensions array:
 extensions = ["html", "txt", "pdf", "rf"]

using sort_by.  But when I try:
 filenames.sort_by { |x| extensions.index x.split('.')[1] }

I get:
 ["a.html", "z.html", "z.txt", "a.txt", "a.pdf", "z.pdf", "z.rf", "a.rf"]

The filenames with extensions "txt" and "rf" are not sorted.  I've tried to figure out how sort_by sorts by using a tuple but haven't been able to find the source code for sort_by.
How can I sort one array by another array using sort_by?

Edit:
The result should look like:
["a.html", "z.html", "a.txt", "z.txt", "a.pdf", "z.pdf", "a.rf", "z.rf"]

A: sorted = filenames.sort_by do |filename|
  extension = File.extname(filename).gsub(/^\./, '')
  [
    extensions.index(extension) || -1,
    filename,
 ]
end
p sorted
# => ["a.html", "z.html", "a.txt", "z.txt", "a.pdf", "z.pdf", "a.rf", "z.rf"]

This uses the fact that the sort order of arrays is determined by the sort order of their elements, in the order they are defined.  That means that if sort_by returns an array, the first element of the array is the primary sort order, the second element is the secondary sort order, and so on.  We exploit that to sort by extension major, filename minor.
If an extension is not in the list, this code puts it first by virtue of ||= -1.  To put an unknown extension last, replace -1 with extensions.size.

A: How about:
>> filenames.sort.group_by{ |s| File.extname(s)[1..-1] }.values_at(*extensions).flatten
[
    [0] "a.html",
    [1] "z.html",
    [2] "a.txt",
    [3] "z.txt",
    [4] "a.pdf",
    [5] "z.pdf",
    [6] "a.rf",
    [7] "z.rf"
]

group_by comes from Enumerable, and is a nice tool in our collection toolbox, letting us group things by "like" attributes. In this case, it's grouping on the file's extension, retrieved using File.extname, minus its leading '.'.
It's important to understand why File.extname is important. A file can have multiple sections delimited by '.', for various reasons. Simply using split('.') is a recipe for disaster at that point, because code following the split will have to deal with more than two strings. Other files don't contain a delimiting '.' at all. File.extname makes a reasonable attempt to retrieve the last extension found in the name, so it is a bit more sane way of dealing with file names and extensions. From the documentation:
File.extname("test.rb")         #=> ".rb"
File.extname("a/b/d/test.rb")   #=> ".rb"
File.extname("foo.")            #=> ""
File.extname("test")            #=> ""
File.extname(".profile")        #=> ""
File.extname(".profile.sh")     #=> ".sh"

values_at comes from Hash, and extracts the values from a hash, in the order of the keys/parameters passed in. It's great for this sort of situation because we can force the order of the values to match the order of keys. When you have a huge hash and want to cherry-pick certain values from it in one action, values_at is the tool to grab. If you need your "by-extensions" order to be different, change extensions and the output will automagically reflect that as a result of values_at.

A: Sort by the index of the extensions array, then the filename:
filenames = ["z.pdf", "z.txt", "a.pdf", "z.rf", "a.rf","a.txt", "z.html", "a.html"]
extensions = ["html", "txt", "pdf", "rf"]

p sorted = filenames.sort_by{|fn| [extensions.index(File.extname(fn)[1..-1]), fn]} #[1..-1] chops off the dot
#=> ["a.html", "z.html", "a.txt", "z.txt", "a.pdf", "z.pdf", "a.rf", "z.rf"]

A: filenames.sort_by{|f| f.split(".").map{|base, ext|
  [extensions.index(ext), base]
}}

A: filenames = ["z.pdf", "z.txt", "a.pdf", "z.rf", "a.rf","a.txt", "z.html", "a.html"]
extensions = ["html", "txt", "pdf", "rf"]
extensions.each_with_object([]){|k,ob| ob << filenames.find_all {|i| File.extname(i)[1..-1] == k }.sort}.flatten
#=> ["a.html", "z.html", "a.txt", "z.txt", "a.pdf", "z.pdf", "a.rf", "z.rf"]

A: extensions = [".html", ".txt", ".pdf", ".rf"]
filenames.sort_by { |file_name_string|
  [ extensions.index( File.extname file_name_string ), file_name_string ]
}

A: There is no need to use the File class. Just the light and simple regex.
filenames.sort_by{|i| i.scan(/\..+$/)[0]}


text:
Q: Optimal way to format 20TB partition with XFS in linux? I have a 20TB RAID5 array (LSI 9265-8i / 8 x 3TB 7200rpm drives) configured with a 1MB stripe size.
What's the optimal way to partition, and format, this partition in Linux to maximize performance for a single ~20TB share?
I'm a linux newbie, so concrete examples are appreciated.

A: First of all, I would suggest using RAID6 instead of RAID5. With such a big volume, an URE during the rebuild is likely enough to be worried about it, which would lead to a failed rebuild and lost data.
Then you will need a GPT partition table for a single volume of this size and if performance is the most important factor, I wouldn't use LVM or something similar, but this means you can't easily extend the volume later on.
After that, just use mkfs.xfs to create the FS.

A: If what you're wondering about is stripe alignment, read the man page for "mkfs.xfs" and search for "sunit" and "swidth" (also called su and sw).  From the man page:
sunit=value: This is used to specify the stripe unit for a RAID device or a logical volume. The value has to be  specified  in
                      512-byte  block units. Use the su suboption to specify the stripe unit size in bytes. This suboption ensures that
                      data allocations will be stripe unit aligned when the current end of file is being extended and the file size  is
                      larger than 512KiB. Also inode allocations and the internal log will be stripe unit aligned.

swidth=value
                      This is used to specify the stripe width for a RAID device or a striped logical volume. The value has to be spec-
                      ified in 512-byte block units. Use the sw suboption to specify the stripe width size in bytes.  This suboption is
                      required if -d sunit has been specified and it has to be a multiple of the -d sunit suboption.

Quick recap:
  sunit : stripe unit in 512 byte blocks
swidth : stripe width = sunit * $num_data_disks
Since you have an 8 disk RAID5 (distributed parity)
$num_data_disks = 8
Stripe size = 1M = 1024kB
So, to format
    mkfs.xfs -d su=1024k,sw=8 /dev/sd{X}
This can also be found on the XFS.org FAQ.


text:
Q: Change NSOpenPanel button text I am using NSOpenPanel to select the folder by the user where I can copy some files programatically.
NSOpenPanel *panelOpen = [NSOpenPanel openPanel];
        [panelOpen setMessage:@"Please select a location to save file(s)."];
        [panelOpen setCanChooseDirectories:YES];
        [panelOpen setCanCreateDirectories:YES];

This opens the Open dialog with the button "Open". I want to change the button text to "Choose" or "Select" instead of "Open".
Is this possible?

A: You are looking for setPrompt: provided by NSOpenPanel's superclass NSSavePanel.

A: As clearly visible from the documentation - note look into NSSavePanel which NSOpenPanel inherits from.
You can use setPrompt:for what you want to achieve.


text:
Q: function returning pointer vs function returning array in C func1 is giving warning & junk value while func2 is giving the right output. What's the difference between the two?
//func 1
unsigned char *CreateData()
{
unsigned char data[]="Thanks";
return data;
}

/* func 2
unsigned char *CreateData()
{
unsigned char *data=malloc(6);
strncpy(data,"Thanks",strlen("Thanks"));
return data;
}

int main()
{
unsigned char *a;
a=CreateData();
printf("%s",a);
return 0;
}

Thanks :)

A: Using the first implementation of CreateData, you return a pointer to a variable with automatic storage duration and then use it past its lifetime, which is undefined behavior.
Less formally, what's actually happening is that data is allocated on the stack, and once you get around to using it as a, CreateData has ended and that stack space is now available for other functions to use, like main or printf, and those other functions are trampling over the space that was previously reserved for data.
When you use malloc, though, the memory is said to be allocated on the heap, not on the stack, and memory on the heap is only released when you tell it to be released (using free). Unlike with variables with automatic storage duration, the memory will not be released when CreateData has returned, so you can continue to use that memory in main.

A: The static array ( ex. unsigned char data[]="Thanks"; ) will be destroyed as soon as you leave the current stack frame (basically, when the function you're in returns).
The dynamic array ( ex. unsigned char *data=malloc(6); ) sticks around forever until you free() it. It's lives on the heap.

A: Function 1 returns a pointer to the local variable (allocated on stack). This is an undefined behaviour.
In Function 2, the data block is allocated on the heap, hence its value persists out of the scope of the function.


text:
Q: How can I create List of rectangles in TypeScript? How can I declare a list of rectangle type?
I have tried this way without list but didn't work:
in TypeScript file:
var i = 0;
var j = 0;
var index = 0;
class Rectangles {
    x: number;
    y: number;
    height: number;
    width: number;
}
let rects: Array<Rectangles>;
function Load()
{
    for (i = 0; i < 5; i++) {
        for (j = 0; j < 10; j++) {
            rects[index].x = 25 + (j * 25);
            rects[index].y = 25 + (i * 25);
            rects[index].width = 25;
            rects[index].height = 25;
            index++;
        }
    }

}

function myClick() {
    var canvas = <HTMLCanvasElement>document.getElementById("canvas");
    let context: CanvasRenderingContext2D = canvas.getContext("2d");
    i = 0;
    j = 0;
    index = 0;
    for (i = 0; i < 5; i++)
    {
        for (j = 0; j < 10; j++)
        {
            context.beginPath();
            context.rect(rects[index].x, rects[index].y, rects[index].width, rects[index].height);
            context.fillStyle = "White";
            context.fill();
            context.lineWidth = 2;
            context.strokeStyle = "Black";
            context.stroke();
            index++;
        }
    }
}

I called the function un the HTML page.
So I need to know how to declare as a list.
in c# we will do this:
List<Rectangle> rects = new List<Rectangle>();

How can I do this in TypeScript?

A: function Load()
 {
  for (i = 0; i < 5; i++) {
    for (j = 0; j < 10; j++) {
       let rect = new Rectangle();
        rect.x = 25 + (j * 25);
        rect.y = 25 + (i * 25);
        rect.width = 25;
        rect.height = 25;
        rects[index++;] = rect;
    }
    }
  }

You are almost right in creating array of rectangles. Think of this array like container and to fill container you need type of rectangle. So you have to first create rectangle then add into container which is rects in this case. Before this you need to initialize container first like rects = [].

A: You dont need to explicitly use the Array class, try this:
interface Rectangle {
    x: number;
    y: number;
    height: number;
    width: number;
}

let rects: Rectangle[] = [];

function Load()
{
    for (i = 0; i < 5; i++) {
        for (j = 0; j < 10; j++) {
            const rect: Rectangle = {
              x: 25 + (j * 25);
              y: 25 + (i * 25);
              width: 25;
              height: 25;
            }
            rects.push(rect)
            index++;
        }
    }

}


text:
Q: send string data from Activity to fragment I want to send a string from Activity (MainActivity.java) to the to the Fragment (Tozihat.java) and set to the a TextView but it gives an error.
I have checked other topics but I can't find solution of my problem.
code From Database Methode I write id + 1 because the first item position from listView is 0 but the first id is 1 :
    public String Tozihat(int id) {
    int id2 = id + 1;
    String query = "SELECT Tozihat FROM tbl_mive WHERE ID ="+id2;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(query , null);
    String t;
    cursor.moveToFirst();
    t = cursor.getString(0);

    return t;
}

code from my MainActivity.Java
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            Intent intent = new Intent(MainActivity.this , ClickActivity.class);

            String t = myDbHelper.Tozihat(position);
            Bundle bundle=new Bundle();
            Tozihat tozihat = new Tozihat();
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.textViewTozihat , tozihat, null);
            bundle.putString("Tozihat", t );
            tozihat.setArguments(bundle);
            fragmentTransaction.commit();

            startActivity(intent);

        }
    });

code from my Faragment (Tozihat.java)
public class Tozihat extends Fragment{

TextView textViewTozihat;
DataBaseHelper myDbHelper;
String Tozihat;

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

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view =  inflater.inflate(R.layout.fragment_tozihat, container, false);

    myDbHelper = new DataBaseHelper(getActivity());

    textViewTozihat = (TextView) view.findViewById(R.id.textViewTozihat);

    Tozihat = getArguments().getString("Tozihat");

    textViewTozihat.setText(Tozihat);

    return view;

}

please help me!

A: Add below code inside listview itemclick listner in activity:
 Tozihat gTozihat  = new Tozihat().newInstance("Data");
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.textViewTozihat, gTozihat).commit();

Inside your Fragment :
 private static final String TYPE = "DATA_KEY";
public static  Tozihat newInstance(String type) {
         Tozihat fragment = new  Tozihat();
        Bundle args = new Bundle();
        args.putString(TYPE, type);

        fragment.setArguments(args);
        return fragment;
    }


text:
Q: Rotate marker(arrow) as per user navigation on mapbox maps android I am working on an application in which I have to rotate an arrow according to the user navigation.
I am using the latest Mapbox SDK.
I have tried with a barrier (calculating using lat & long) but couldn't get success.
I don't have any clue that how can I achieve it.
It(Arrow marker) should be navigated on a predefined polygon path.

A: I got success in calculate bearing using the below method and rotate the arrow as per user navigation:
float bearingBetweenLocations(LatLng latLng1, LatLng latLng2) {
        double PI = 3.14159;
        double lat1 = latLng1.getLatitude() * PI / 180;
        double long1 = latLng1.getLongitude() * PI / 180;
        double lat2 = latLng2.getLatitude() * PI / 180;
        double long2 = latLng2.getLongitude() * PI / 180;
        double dLon = (long2 - long1);
        double y = Math.sin(dLon) * Math.cos(lat2);
        double x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1)
                * Math.cos(lat2) * Math.cos(dLon);
        double brng = Math.atan2(y, x);
        brng = Math.toDegrees(brng);
        brng = (brng + 360) % 360;

        return (float) brng;
    }

Note: Arrow's head should be pointed towards the up direction like the below image.
If it is not then you have to set bearing +/- as per the arrow's direction.

A: 1- first you need the input  - you need to get the getBearing() from the location object.
2- you need the correct output - you can do it in 2 ways -
a. if you use png icons , you can create an arrow for every 10 degrees, (36 arrows) and updated the marker with correct icon, if current bearing is different from the old bearing.
b. Better option but i don't know if this works: the marker of mapbox has options.rotation option. But in android, Mapbx moved to Mapbox annotation plugin, see also here
the SymbolManager has a function setIconRotationAlignment. so if you can use this class, i believe you can set the rotation of the icon by the bearing.
you can also see in this demo that one of the options is "set icon rotation to 45"

3- One more thing - you may want to get also input of getBearingAccuracyDegrees to know when you don't have a good enough Accuracy of the Bearing, and give indication to the user.

A: If you prefer to use a library instead of the method you suggested then I suggest to use Turf .
"Turf android" is a library created by the mapbox guys ,which have many useful methods including this one .
/*
Takes two {@link Point}s and finds the geographic bearing between them.
*/
TurfMeasurement.bearing(@NonNull Point point1, @NonNull Point point2)

library homepage :
https://docs.mapbox.com/android/java/guides/turf/


text:
Q: Knot location using quantile knots I have implemented regression splines and penalised splines, with different algorithms to choose optimal lambda.
But I am still not satisfied with it as I am not able to choose the location of knots as required.
I have been using uniform knots till now, but some one suggested that quantile knots may work.
I tried to find, but could not find a good book for that.
Can you please suggest me some good books or articles for quantile knots.
Please also share if you have any valuable information regarding it.

A:
I am not able to choose the location of knots

For regression splines, if you want to choose the location of the knots, you can specify them anywhere you want.
If you want knots placed at some set of quantiles, calculate the quantiles you want and place knots there (you're unlikely to find more than a couple of sentences on putting knots at quantiles in a book; there's nothing to it).
For example, in R, quantile(x,ppoints(k)) :

$\hspace{1.25cm}$
(here k=10) would be one way to spread knots fairly uniformly across the points of x, but exactly what you do will depend on what you want to end up with; you may want to modify this if you place knots at the boundary points.
You can get approximately what you seek by just placing knots every n/k points; the quantile(x,ppoints... trick above does almost that, except for the first and last segment (which has slightly fewer points out the ends, though it's really only noticeable in small samples)
If you want something else than this, you're going to have to clarify the question further.


text:
Q: Calculating the PMF of roll-and-keep dice (XdZkY) I've been trying to use the PMF shown in an older question, found here, and sourced from here, but I've run into a problem. When attempting to calculate N, I'm finding that B (using s+i+j-x-ry = B) rapidly becomes negative when keeping more than 1 die (y>1). This, in turn, results in attempting to distribute a negative number of "balls". This is a bit out of my depth, since I'm not very experienced with combinatorics, but as far as I know I understand all the operations I'm trying to perform. What am I missing in using this?
I'm not sure what to make of the modifications from the original Physics Forum version to the version in the question. I've been using the original Physics Forum one, where they differ, but at the moment my problem lies in a part that seems to be identical.


text:
Q: perl pass through tab via Getopt::Long I have a simple script where I want the user to be able to specify the separator:
#!/usr/bin/perl
use strict;
use warnings;
use Getopt::Long;
my $sep = "&";
GetOptions('sep:s' => \$sep);
my @list = ('a','b','c');
print join($sep,@list);
print "\n";

But if I don't seem to find the way to pass "\t" and be evaluated as a tab in the script:
perl ~/perl_tests/sep.pl -sep \t
perl ~/perl_tests/sep.pl -sep \\t
perl ~/perl_tests/sep.pl -sep '\t'
perl ~/perl_tests/sep.pl -sep '\\t'
perl ~/perl_tests/sep.pl -sep "\t"
perl ~/perl_tests/sep.pl -sep "\\t"

Neither produces my desired output, which is the values separated by tabs in the command-line result.

A: this is really a shell question as you are calling the perl script from a shell
In bash, this works
perl sep.py -sep $'\t'

Also using ctrl v followed by pressing tab and putting that in double quotes works


text:
Q: How do I use JavaScript to detect the name of the network my computer is connected to? I want to write some JavaScript that is able to detect/read the name of the network I am connected to; for example, when I move between two different wireless networks with different SSIDs.
Preferably a for loop or a case/switch so that depending on the name of the network, I am able to redirect my browser accordingly.
Thank you.

A: The comments to your question are correct. JavaScript code, like any other code is bound by the constraints of the environment it runs within. There are two potential answers...
The most likely answer is that you are trying to do the described logic within a browser. If that is the case, then you're dependant on the environment the browser gives you. And no browsers that I know of give you access to machine resources like the network adapter. This would be a security hole in the browser. Therefore you can't determine the SSID from javascript running within a browser. A better question you could pose, might be "how do I redirect traffic to another server based on the wireless network you're currently connected to"...
The other answer is that you're running the javascript code in a standalone interpreter. If that interpretter gives you access to the network resources, then you can determine the SSID... after that you could possible muck with the host file to redirect network traffic. However, I expect this is not what you're attempting to do.


text:
Q: ¿Como se reserva espacio con malloc para un struct? No se si estoy haciendo bien la reserva de memoria para mi struct, este es mi código:
 datos_entrada = (pmanager_t *)malloc(sizeof(pmanager_t)*(n_max_cintas));

Me da problemas al intentar escribir en una pipe según valgrind y no
entiendo porque:
fprintf(des_pipe, "%i", datos_entrada[i].id_cinta);

Mi código entero sería éste. He comentado el exec, porque no es el problema y así solo paso este documento.
/*
 *
 * factory_manager.c
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <stddef.h>
#include <semaphore.h>
#include <sys/stat.h>
#include <string.h>
#include "queue.h"

int n_max_cintas;/*Numero maximo de process_manager y por tanto de colas*/
int n_real_cintas = 0;

int l_id_cinta = 0;
int l_tam_cinta = 0;
int l_n_elementos = 0;
int tuberia[2];

char id_cinta_c[4];
char semaforo_c[4];
char tam_cinta_c[4];
char n_elementos_c[4];

char buffer;
char *buffer_w;

sem_t *semaforo;
char* nombre_semaforo = "/semaforo_cinta759";

typedef struct process_manager {

    int id_cinta;/*Id de la cinta*/
    int tam_cinta;/*Numero maximo de elementos que puede tener una cinta*/
    int n_elementos;/*Numero de elementos que se debe generar en la cinta*/
} pmanager_t;

pmanager_t *datos_entrada; /*Definimos un datos: de tipo pmanager_t para almacenar cada uno de los datos necesarios para cada hijo*/

void parser (const char * argv);/**/

int main (int argc, const char * argv[] ){

    semaforo = sem_open(nombre_semaforo, O_CREAT, 0644, 0);

    parser(argv[1]);/*Lo metemos en el parser*/

    pipe(tuberia);

    int pid [n_max_cintas];

    for (int i = 0; i < n_real_cintas; i++) {

        pid[i] = fork();

        if(pid[i] == 0){
            close(0);
            dup(tuberia[0]);
            close(tuberia[0]);
            close (tuberia[1]);

            sprintf(id_cinta_c, "%d", datos_entrada[i].id_cinta);
            sprintf(tam_cinta_c,"%d",datos_entrada[i].tam_cinta);
            sprintf(n_elementos_c,"%d", datos_entrada[i].n_elementos);

            printf("[OK][factory_manager] Process_manager with id %i has been created.\n", datos_entrada[i].id_cinta);

            /*execlp("./process", id_cinta_c, nombre_semaforo, tam_cinta_c, n_elementos_c,NULL);
            perror("[ERROR]Exec no ejecutado.\n");*/

            printf("adios\n");
            exit (-1);
        }
    }

    printf("hola");

    close (tuberia[0]);

    FILE *des_pipe = fdopen( dup(tuberia[1]), "a+" );

    for (int i = 0; i < n_real_cintas; i++){

        fprintf(des_pipe, "%i", datos_entrada[i].id_cinta);
        int a;
        sem_post(semaforo);
        if( (a = wait(&pid[i]) == 0)){

            printf("[OK][factory_manager] Process_manager with id %i has finished.\n", datos_entrada[i].id_cinta);
        }

        else{

            printf("%i\n", a);
            printf("[ERROR][factory_manager] Process_manager with id %i has finished with errors.\n", datos_entrada[i].id_cinta);
        }
    }

    printf("[OK][factory_manager] Finishing.\n");
    return 0;

}

void parser (const char * argv){
    FILE* desc_fichero;
    int leido;

    /*-------------------------------------ABRO EL FICHERO-------------------------------------------*/
    desc_fichero = fopen(argv, "r");

    if (desc_fichero == NULL) {

        perror("[ERROR][factory_manager] Invalid file1.");
        exit(-1);
    }

    /*-------------------------------------LEO EL FICHERO-------------------------------------*/

    if((fscanf(desc_fichero, "%d", &n_max_cintas)) == EOF || n_max_cintas <= 0){/*Le el primer valor y lo guarda en n_max_cintas */

        fprintf(stderr, "[ERROR][factory_manager] Invalid file2.");

        if(fclose(desc_fichero) != 0) {

            perror("[ERROR][factory_manager] Invalid file3.");
            exit(-1);
        }
    }
    datos_entrada = (pmanager_t *)malloc(sizeof(pmanager_t)*(n_max_cintas));

    while(leido != EOF){

        leido=fscanf(desc_fichero, "%i %i %i", &l_id_cinta, &l_tam_cinta, &l_n_elementos);

        if(leido != 3 && leido != EOF){

            fprintf(stderr, "[ERROR][factory_manager] Invalid file.4\n"); /*Mostramos el mensaje por la salida de error estándar*/
            fclose(desc_fichero);
            exit (-1);
        }

        if(l_id_cinta <= 0 || l_tam_cinta <= 0 || l_n_elementos <= 0){

            perror("[ERROR][factory_manager] Invalid file5.\n");
            exit(-1);
        }

        else{

            if(leido != EOF){

                pmanager_t cinta;

                cinta.id_cinta = l_id_cinta;
                cinta.tam_cinta = l_tam_cinta;
                cinta.n_elementos = l_n_elementos;

                datos_entrada[n_real_cintas] = cinta;

                n_real_cintas++;
            }
        }
    }

    /*-------------------------------------CIERRO EL FICHERO-------------------------------------*/
    if(fclose(desc_fichero) != 0) {

        perror("[ERROR][factory_manager] Invalid file6.");
        exit(-1);
    }

    if(n_real_cintas > n_max_cintas){

        perror("[ERROR][factory_manager] Invalid file7.");
        exit(-1);
    }
}

Lo que me devuelve el valgrind es esto:
> goh@goh:~/Escritorio/practica$ valgrind --leak-check=full ./factory
> p.txt
> ==9563== Memcheck, a memory error detector
> ==9563== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
> ==9563== Using Valgrind-3.12.0.SVN and LibVEX; rerun with -h for copyright info
> ==9563== Command: ./factory p.txt
> ==9563==
> ==9563== Conditional jump or move depends on uninitialised value(s)
> ==9563==    at 0x109177: parser (factory_manager.c:140)
> ==9563==    by 0x108C59: main (factory_manager.c:53)
> ==9563==  [OK][factory_manager] Process_manager with id 1 has been created.
> ==9563== Invalid read of size 4
> ==9563==    at 0x50A48F4: vfprintf (vfprintf.c:1275)
> ==9563==    by 0x50AD546: fprintf (fprintf.c:32)
> ==9563==    by 0x108EAD: main (factory_manager.c:92)
> ==9563==  Address 0xc0 is not stack'd, malloc'd or (recently) free'd
> ==9563==
> ==9563==
> ==9563== Process terminating with default action of signal 11 (SIGSEGV)
> ==9563==  Access not within mapped region at address 0xC0
> ==9563==    at 0x50A48F4: vfprintf (vfprintf.c:1275)
> ==9563==    by 0x50AD546: fprintf (fprintf.c:32)
> ==9563==    by 0x108EAD: main (factory_manager.c:92)
> ==9563==  If you believe this happened as a result of a stack
> ==9563==  overflow in your program's main thread (unlikely but
> ==9563==  possible), you can try to increase the size of the
> ==9563==  main thread stack using the --main-stacksize= flag.
> ==9563==  The main thread stack size used in this run was 8388608.

A: if((fscanf(desc_fichero, "%d", &n_max_cintas)) == EOF || n_max_cintas <= 0){

    fprintf(stderr, "[ERROR][factory_manager] Invalid file2.");

    if(fclose(desc_fichero) != 0) {

        perror("[ERROR][factory_manager] Invalid file3.");
        exit(-1);
    }
}
datos_entrada = (pmanager_t *)malloc(sizeof(pmanager_t)*(n_max_cintas));

En ese fragmento lees un entero de un fichero y después utilizas ese valor para realizar una reserva de memoria... ¿Qué sucede si el escaneo da EOF y al cerrar el fichero obtienes un 0? Que exit no se ejecuta y realizas una reserva de memoria basada en un valor de n_max_cintas sucio (recuerda que la lectura ha fallado).
Deberías probar algo tal que:
if((fscanf(desc_fichero, "%d", &n_max_cintas)) == EOF || n_max_cintas <= 0){

    fprintf(stderr, "[ERROR][factory_manager] Invalid file2.");

    if(fclose(desc_fichero) != 0) {

        perror("[ERROR][factory_manager] Invalid file3.");
        exit(-1);
    }
    else
    {
      // Aqui deberias hacer algo
    }
}
else
{
  datos_entrada = (pmanager_t *)malloc(sizeof(pmanager_t)*(n_max_cintas));
  // ...
}


text:
Q: How to set two or more paragraphs to use the same amount of vertical space? Given several paragraphs in ConTeXt or plain TeX, how can I ensure that all paragraphs use the same amount of vertical space, by adding white space to the end, as the longest paragraph in the set? E.g.:
    This is a paragraph
with only two lines.
    This paragraph is a
little bit longer and it
has three lines.
    This is the longest
paragraph, as it has
a second, third, and
fourth line.

The above paragraphs would get added white space afterward, such that they all occupy the same amount of vertical space as the last paragraph, because it is longest, e.g.:
    This is a paragraph
with only two lines.

    This paragraph is a
little bit longer and it
has three lines.

    This is the longest
paragraph, as it has
a second, third, and
fourth line.

A: you can use
\vbox to 5cm{stuff.......\vfill}

To force a box of the right vertical size, padded with space at the end.
instead of 5cm you can measure one of the boxes first so
 \setbox0\vbox{longest stuff....}

then for each paragraph you can do
\vbox to \ht0{stuff.......\vfill}

A: Here I provide a more ConTeXtish solution based on the same idea as Davids solution. It incorporates the now two-pass data mechanism.
\defineframedtext [normalparagraph]
  [
      frame=off,
     offset=overlay,
      width=\textwidth,
     height=\datasetvariable{lastparagraph}{last}{height},
  ]

\definedataset [lastparagraph]
\newbox\mylastbox

\definestartstop [lastparagraph]
  [
    before=\setups{last:before},
     after=\setups{last:after},
  ]

\startsetups last:before
  \setbox\mylastbox\vbox\bgroup
\stopsetups

\startsetups last:after
  \egroup
  \setdataset [lastparagraph] [last] [height=\the\ht\mylastbox]
  \box\mylastbox
\stopsetups

\starttext

  \startnormalparagraph
    \framed[align=normal]{\input knuth\par}
  \stopnormalparagraph

  \startnormalparagraph
    \framed[align=normal]{\input ward\par}
  \stopnormalparagraph

  \startlastparagraph
    \input knuth
  \stoplastparagraph

\stoptext

Result:

The normalparagraphs are simple vboxes with the height of the last paragraph. The height value is picked up from the two-pass data set. The lastparagraph is also a vbox, which height is measured and saved in the .tuc file. The \framed after \starttext are just added for illustration. Fill it with your content.

A: Another ConTeXt based solution, but this one works in a single pass. It requires you to store the content in buffers, then measures all the buffers and sets the height to maximum height (not necessarily the height of the last paragraph).
\newdimen\maxbufferheight

\def\placebuffertomaximumheight[#1]%
    {\maxbufferheight\zeropoint
     \processcommalist[#1]\domeasurebuffermaxheight
     \processcommalist[#1]\doplacebuffertomaxheight}

\def\domeasurebuffermaxheight#1%
    {\setbox\scratchbox\vbox{\getbuffer[#1]}%
     \scratchdimen\ht\scratchbox
     \ifdim\scratchdimen>\maxbufferheight
        \maxbufferheight=\scratchdimen
     \fi}

\def\doplacebuffertomaxheight#1%
     {\ruledvbox to \maxbufferheight
        {\getbuffer[#1]}%
        \blank[none]} %change \blank[..] to \par to get regular inter-para space

\starttext
\startbuffer[one]
Single line
\stopbuffer

\startbuffer[two]
\input tufte
\stopbuffer

\startbuffer[three]
\input ward
\stopbuffer

\placebuffertomaximumheight[one,two,three]

\stoptext

Once you have the basic mechanism, it is straight-forward to wrap this around a macro.
\newcount\nofmeasuredparagraphs

\def\startparagraph
    {\increment\nofmeasuredparagraphs
     \grabbufferdata[measuredparagraph-\nofmeasuredparagraphs][startparagraph][stopparagraph]}

\def\stopparagraph{}

\def\startmeasuredparagraph
    {\nofmeasuredparagraphs\zeropoint}

\def\stopmeasuredparagraph
    {\maxbufferheight\zeropoint
    \dorecurse\nofmeasuredparagraphs
        {\domeasurebuffermaxheight{measuredparagraph-\recurselevel}}%
    \dorecurse\nofmeasuredparagraphs
        {\doplacebuffertomaxheight{measuredparagraph-\recurselevel}}}

\starttext
\startmeasuredparagraph
\startparagraph
Single line
\stopparagraph

\startparagraph
\input tufte
\stopparagraph

\startparagraph
\input ward
\stopparagraph
\stopmeasuredparagraph

\stoptext

This gives

I am using \ruledvbox so that you can see the box. Change that to \vbox if you don't want to see the box.


text:
Q: How to free one of the index of an array pointer? Suppose I have pointer array;
int *x;

when I free one of the index of x, other indices are unavailable also.
free(x[4]);
int k = x[3]; // gives segmentation error. If do not free no error.

Is there any way to free one of the specified index of an pointer array?

A: In this code example, you are trying to free something that is not a pointer type. You can only do free(x) and that is only after you malloc'd it. Basically, you are doing something like:
 int a;
 free(a);

If you want to be able to free array elements, then your array has to be of int** type. Be careful to malloc them again or set them properly after that, too.


text:
Q: Double Hashing Using MD5 with SHA-1 The following code creates an MD5 hash and then hashes it again with SHA-1 – is this secure?
$user = $_POST['username'];
$username = mysqli_real_escape_string($mysqli, $user);
$pass = md5($_POST['password']);
$password = sha1($pass);

Does this increase collision possibilities?
Are there any other ways in order to hash and be very fast in processing the password?

A: There is no practical advantage over single hashing.
Note that MD5 is now considered broken as it is vulnerable to many practical attacks, and algorithms such as SHA1 are not recommended for password hashing.
There are algorithms designed specifically for password hashing, such as PBKDF2. You should use PBKDF2 as your hash - see this question on security.stackexchange.com..

A: Use sha2
https://dev.mysql.com/doc/refman/5.5/en/encryption-functions.html#function_sha2
mysql> SELECT SHA2('abc', 224);

SHA2() can be considered cryptographically more secure than MD5() or
  SHA1().
SHA2() was added in MySQL 5.5.5.


text:
Q: Moq with Unity Container unit testing below is an example of production code that I am trying to unit test. I am struggling to resolve a dependency to a concrete class that is being used.
public MyClass(IUnityContainer container)
{
    this.unityContainer = container;
}

public string DoWork()
{
     var sender = unityContainer.Resolve<IInterface>();  // how to setup this object
     var json = sender.Send("something");
     var value = serializer.Deserialize<SomeModel>(json);
     return value.url;
}

I want to mock out the IInterface used by this method. How do I set that up in my unit test code? I feel like there is something missing here. this has a smell of an anti-pattern.....

A: I agree with CodeCaster.  The typical pattern would be to accept a parameter of type IInterface in the constructor and assign it to a class-level variable.
public MyClass(IInterface sender)
{
    this.sender = sender;
}

When testing, simply pass in your moq.
That said, there are times when I dislike passing in a dependency through the constructor.  Such as:

*

*I may need multiple instances of a class

*The object is only needed conditionally.

*The class's constructor may depend on additional values that are not determined until run time.

In those cases, passing the container as a parameter is the only solution I've come across. Just be sure to register your initial instance of the container with itself.  Otherwise, the DI will provide your constructor with a new (empty) container. If anyone has a better pattern, particularly one that works with Unity, I'd love to see it.

A: This is the "service locator" antipattern, where you inject your dependency injection container / inversion of control into your logic.
You should pass the IInterface that it depends on instead, so that you control what instances it can otain. See Dependency Injection container in constructor.
If you can't refactor the class, you have to injecting the container in your unit test. Set up the container to return an instance (or rather, a mock) of IInterface. Like this:
public void MyUnitTest()
{
    IUnityContainer myContainer = new UnityContainer();
    myContainer.RegisterType<IInterface, YourInstance>();

    MyClass classUnderTest = new MyClass(myContainer);
    classUnderTest.DoWork();

    Assert...
}

See How to use Unity.RegisterType with Moq? to mock the YourInstance.


text:
Q: Excel - autofill formula horizontally with cell number increment I have the following problem. I want to copy this formula =SUMPRODUCT(--($C3:$Q3=C4:Q4)) ,which is in cell C13, to the adjacent cells (D13, E13, F13 etc.), but I want $C3:$Q3 to become $C4:$Q4. (basically =SUMPRODUCT(--($C3:$Q3=C4:Q4)) ====> =SUMPRODUCT(--($C4:$Q4=C4:Q4)) and so on). Dragging horizontally doesn't help, since autofill increments the rows and not the column number.
I tried with OFFSET, but as far as I understand, it references the data and not the formulas. Any help would be appreciated. Thanks in advance.

A: In C13 put
=SUMPRODUCT(--(OFFSET($C$3:$Q$3,SUM(COLUMN(C13)-COLUMN($C$13)),,,)=$C$4:$Q$4))

Then drag this across columns.
Note:
1) This assumes $C$4:$Q$4 is a fixed range to compare against as it remains the same in your given example
2) That you don't mind the fact that the formula in column D will self reference for comparison
You could also just enclose in Index instead.
=SUMPRODUCT(--(INDEX(OFFSET($C$3:$Q$3,COLUMN(C13)-COLUMN($C$13),,,),0,0)=$C$4:$Q$4))

Example:

Edit:
Based on share workbook where need to drag across columns and down rows to compare 64 * 64 matrix element wise (where each element is a row in the source array)
In C71 put the following and drag down and across to BM133:
=SUMPRODUCT(--(INDEX($C$2:$W$64,MATCH($B71,$B$2:$B$64,0),0)=INDEX($C$2:$W$64,MATCH(C$70,$B$2:$B$64,0),0)))

Result:

With column R test on gender being different added in C71 put the following and drag down and across to BM133:
=IF(INDEX($C$2:$W$64,MATCH($B71,$B$2:$B$64,0),16)<>INDEX($C$2:$W$64,MATCH(C$70,$B$2:$B$64,0),16),SUMPRODUCT(--(INDEX($C$2:$W$64,MATCH($B71,$B$2:$B$64,0),0)=INDEX($C$2:$W$64,MATCH(C$70,$B$2:$B$64,0),0))),"")

A: Converting the formulas to text should work.

*

*Copy your =SUMPRODUCT formula down as many rows as you need columns filled.

*Convert the formulas to text.  Highlight the rows you copied down and find and replace all = with '=

*Copy those rows.

*Select the cell in the column where you want the formulas and paste special with values and transpose selected.

*Highlight the pasted cells and find and replace all = with =
Unfortunately the last step is necessary to make it work even though it seems redundant.


text:
Q: Are there any statistical metrics that satisfy this kind of condition? Let $f=N(\mu,\sigma^2)$ be a univariate normal distribution with mean $\mu$ and variance $\sigma^2$ and let $f_1 = N(\mu+\epsilon,\sigma^2)$ and $f_2=N(\mu,(\sigma+\epsilon)^2)$ be some small perturbations to $f$.  Are there any statistical metrics $D(\cdot,\cdot)$ (e.g. Kolmogorov-Smirnov, Wasserstein, Prokhorov, etc.) for which we can say something about the derivative $$\frac{d}{d\epsilon} D(f,f_1)$$ or $$\frac{d}{d\epsilon} D(f,f_2)$$ evaluated at $\epsilon=0$?  How about if $f$ were, say, an exponential distribution instead?

A: According to Proposition 7 on p. 236 of Givens and Shortt, the $L^2$ Wasserstein distance between $N(\mu_1,\sigma_1^2)$ and $N(\mu_2,\sigma_2^2)$ is the Euclidean distance between the points $(\mu_1,\sigma_1)$ and $(\mu_2,\sigma_2)$. So, the derivative of this Wasserstein distance is straightforward.


text:
Q: Trouble with inheritance: Separate table implementation for disjoint entities and common ID I currently have four disjoint entity types (competition, talk, award, publication) that are to be converted to tables. In order to manage certain other data for each, i.e. documents related to each entity (many documents per entry), should I create a separate table to get a common ID and then assign them resulting in costly joins or is there another method? My database course faculty taught me to make separate tables for disjoint relationships but I don't know what is the best choice here.
I understand this is a common question but I unfortunately am unable to find a proper solution or advice anywhere.

I apologize if this is a duplicate. Thank you for taking your time to answer.


text:
Q: Swift project with Travis CI I'm trying to set my Swift project up with Travis CI, but i keep getting this error.

Here is my YAML file.
language: objective-c  #1
xcode_project: Tjenesto.xcodeproj #3
xcode_scheme: Tjenesto #4
xcode_sdk: iphonesimulator8.4 #5

I'm using this tutorial: https://www.raywenderlich.com/109418/travis-ci-tutorial

A: Non ASCII characters?
Error seems to be at line 1 column 1, i.e. the very first character of your script
Specify an Xcode image
Not directly related, but you are leaving Xcode open to Travis CI interpretation:
osx_image: xcode8.3

And when using Xcode 8, you may need to visit this Stack Overflow quesion.


text:
Q: i have a turned off computer with wol activated and i know its MAC , is there a way to check if the computer is plugged in to network? I am thinking of a security system for my small company, i would like to know if there is a way to know even when the computer is turned off when the computer gets disconnected (Knowing the mac an ip)
Imagine this, i have 20 laptops in my office , some may be on , some off, but i know everyones mac an ips , all of then have WOL capabilities activated, what i am thinking is a script that could be sending this kind of ping to the computer lets say every 30 secs to know if they are still connected to the network.
If a computer does not answer in the 30 sec check i would immediately send an automatic email to security office in the building with the information of the machine missing, indicating exact position since i have a previous inventory of the physical location of every address and laptop, thank you in advanced for your responses..

A: For handling your requirement, it will be better to go for a .net application rather than sticking with a script. .Net has libraries such as System.Net which provides functions for pinging a system by providing its IP. Moreover there are library collections such as System.Net.Mail which provides e-mail facilities.


text:
Q: Google api серверная авторизация Добрый день. Уже какой день бьюсь с google api.
Подключил google-api-php-client, создал и подключил JWT(json-файл) для использования service-account доступа к API (без oauth2). Но, видать, где-то не досмотрел, так как доступа к данным календаря так и не получил.
Вот что имеем:
require_once 'google-api-php-client/vendor/autoload.php';
$credentials_file = 'calendar-91713b63060f.json';
$client = new Google_Client();
$client->setApplicationName("calendar");
$client->setScopes(['https://www.googleapis.com/auth/calendar']);
$client->setAuthConfig($credentials_file);

$service = new Google_Service_Calendar($client);
$optParams = array(
  'maxResults' => 10
);
$results = $service->events->listEvents('primary', $optParams);
var_dump($results);

Код даже выполняется, но возвращает странные значения:
object(Google_Service_Calendar_CalendarList)#67 (10) {
["collection_key":protected]=> string(5) "items"
["etag"]=> string(18) ""p32sf76fmi6css0g""
["itemsType":protected]=> string(41) "Google_Service_Calendar_CalendarListEntry"
["itemsDataType":protected]=> string(5) "array"
["kind"]=> string(21) "calendar#calendarList"
["nextPageToken"]=> NULL
["nextSyncToken"]=> string(84) "CLjzmfaRmc4CEjRjYWxlbmRhckBtYWNyby1tZW5kZXItMTM3ODIzLmlhbS5nc2VydmljZWFjY291bnQuY29t"
["internal_gapi_mappings":protected]=> array(0) { }
["modelData":protected]=> array(1) {
//В этом поле не должно быть пустого массива..
    ["items"]=> array(0) { } }
["processed":protected]=> array(0) { } }

Если кто сталкивался с Google Calendar API и Service account буду рад услышать совет))

A: А что, если дополнить и выполнить код прямо из документации? Что вы на выходе вообще хотите получить?
if (count($results->getItems()) == 0) {
  print "No upcoming events found.\n";
} else {
  print "Upcoming events:\n";
  foreach ($results->getItems() as $event) {
    $start = $event->start->dateTime;
    if (empty($start)) {
      $start = $event->start->date;
    }
    printf("%s (%s)\n", $event->getSummary(), $start);
  }
}


text:
Q: Sending laravel mail containing contents related to the recipient How can I send the mail which contains the product details related to a specific company please refer to the code below for further elaboration:
Here is my Controller.php code:
    foreach ($order->products as $product){
      foreach ([$product->company_email] as $recipient) {
        Mail::to($recipient)->send(new SendCompanyEmail($order));
      }
    }

Here is my SendCompanyEmail.php code:
public function __construct(Order $order)
{
    $this->order = $order;
}

public function build()
{
    return $this->markdown('emails.company-email')
                ->subject('New Order Placed');
}

Here is my company-email.blade.php code:
@foreach($order->products as $product)
    Name: {{ $product->name }}
    Price: {{ $product->price }} USD
    Company Email: {{ $product->company_email }}
@endforeach

I ordered 2 products from 2 different companies and I want an email to be sent to each company with its own product details.
The issue is that when the email is sending, it sends to both companies but with all the products I ordered.
Here is the output email:
To: company1@company1.com
Name:   Product 1
Price:  10.00 USD
Company Email:  company1@company1.com

Name:   Product 2
Price:  12.00 USD
Company Email:  company2@company2.com

To: company2@company2.com
Name:   Product 1
Price:  10.00 USD
Company Email:  company1@company1.com

Name:   Product 2
Price:  12.00 USD
Company Email:  company2@company2.com

What I actually want is to send the email to both companies but with its respective product details.
Here is the output email I want:
To: company1@company1.com
Name:   Product 1
Price:  10.00 USD
Company Email:  company1@company1.com

To: company2@company2.com
Name:   Product 2
Price:  12.00 USD
Company Email:  company2@company2.com

A: You should group your products by each company.
In your controller, do the grouping logic and send for each email an array of products:
$companiesProducts = [];

foreach ($order->products as $product) {
    $companiesProducts[$product->company_email][] = $product;
}

foreach ($companiesProducts as $email => $products) {
    Mail::to($email)->send(new SendCompanyEmail($products));
}

In your email class:
public function __construct($products)
{
    $this->products = $products;
}

public function build()
{
    // pass $this->products to your email view
    return $this->markdown('emails.company-email')
                ->subject('New Order Placed');
}

And in your view file change $order->products to the products parameter you've passed.


text:
Q: Deleting an entire line and line breaks i'm relatively new to Python, and i'm currently having some trouble running a script. I need a script that deletes every line that starts with an specific character (in this case is ">") and deletes all line breaks, joining the text file in one single line, except for the first line starting with ">" in the file, that must remain intact. what i've got so far is this
import sys
import os
import fileinput

x = open('seq.fasta','r')
y = open('seq.fasta.tmp', 'w')
text = ''
for line in x:
    if '>' in line:
        text += line
    else:
    text += line.replace("\n","")
y.write(text)
x.close()
y.close()

It reads the document, skips the line with the ">" (so it does not delete the linebreak on the first line), and deletes all line breaks. What i'm missing is the line delete part.
Thanks for your help in advance!

A: Both parts of your if statement add the line into text; you need to determine when the line should not be added, and then don't.


text:
Q: Working with a corrupted GIF I'm trying to manipulate an image generated by the MapQuest traffic API. Here's an example. The image file that page generates appears to be corrupted (but not consistently). I can never edit it with ImageMagick, GIFLIB, PIL, or Photoshop. But sometimes the same file displays just fine in Chrome and Firefox.
(1) Is it possible to fix the corrupted file? The fact that a browser can display it suggests that it's salvageable.
(2) Why would a browser recognize the image when ImageMagick, etc. can't?

A: It seems like this image was not saved properly and some visual info was lost. Fortunately it's always possible to solve such problem with non-standard approach :) I just placed this image into Adobe Illustrator and saved it as PNG. You can download it here:
http://www.mediafire.com/download/oschyb4jfzlaw7a/flow2.png
That's it :) Hope this helps.
-- Alex


text:
Q: How to import a C++ function with int** and double** parameters I am trying to import a C++ function in my C# code.
This function is defined as:
int SetPointers(int* ID, int* BufferID, int** Pointer, double** Time, int NumberOfPointers);

with ID an array of int,
BufferId an array of int,
Pointer an array of int,
Time an array of double, and
NumberOfPointers an int.
I have tried to use IntPtr without success.
Here is the latest code I tried:
[DllImport("open.dll", SetLastError = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl)]
public unsafe static extern int SetPointers(int* ID, int* BufferID, ref IntPtr Pointer, ref IntPtr Time, int NumberOfPointers);
public unsafe int _SetPointers(int[] ID, int[] BufferID, ref int[] Pointer, ref double[] Time, int NumberOfPointers)
{
    IntPtr fQueue = IntPtr.Zero;
    IntPtr fTime = IntPtr.Zero;
    int breturn = -1;
    fixed (int* fId = ID)
    fixed (int* fBufferID = BufferID)
    fQueue = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(int)) * Pointer.Length);
    fTime = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(double)) * Timestamp.Length);
    breturn = SetPointers(fId, fBufferID, ref fQueue, ref fTime, NumberOfPointers);
    return breturn;
}

How can I do this?

A: First all, you might want to use IntPtr for your parameters rather than int[].
After this, I haven't tried it but to marshal pointers on pointers a "ref IntPtr" or "out IntPtr" would work.
public unsafe int _SetPointers(IntPtr ID, IntPtr BufferID, ref IntPtr Pointer, ref IntPtr Time, int NumberOfPointers);

Also have a look to this other question: How do I marshall a pointer to a pointer of an array of structures?


text:
Q: The word for a two story apartment In portuguese we have the word "duplex". This makes you think of a  luxurious/semi-luxurious place. Is there a word for that in AE or in BE? Does it have the same connotation?

A: Duplex house is used in English, too.

A house having separate apartments for two families, especially a two-storey house having a complete apartment on each floor and two separate entrances.

It doesn't automatically mean a luxurious house. Read more on Wikipedia


text:
Q: integrating google login to website with php Please accept my apology if my question has a simple answer. I'm trying to add a functionality to login through google account with PHP and OAuth 2.0. I tried this on a simple login page and its working fine.
Now, I have a page of recipe where user can give their comment. Page URL is something like this mysite.com/recipe-123-recipename. I changed URL through .htaccess. Original link is mysite.com/single_recipe.php?id=123&title=recipename.
There is a option of redirect URL in google API console and it is optional so I left it blank. Every time I try to use script i get redirect URL mismatched error.
I just need to know how can I set redirect URL like single_recipe.php?id=123&title=recipename so user get back to this page? or I need to change the script? I have added facebook login in same page and it is working great.
Please guide me I tried everything but no luck so far.


text:
Q: convert a key value pair into 2 different objects Let me explain here
let obj = {manager:XYZ}
//output:[{position:"manager",name:"XYZ"}]

you can also use lodash to find the solution

A: Use Object.entries() to get each key/value pair from the object, and map() to iterate over each key:

let obj = {manager:'XYZ'}

let arr = Object.entries(obj).map(([key, val]) => ({position: key, name: val}))

console.log(arr)

A: Another option is to use a for-loop:

let obj = {manager:'XYZ'}

let output = [];
for (var key in obj) {
  output.push({ position: key, name: obj[key] });
}

console.log(output);

A: Using Object.entries, map and some destructuring you can come to a simple solution:

let obj = { manager: "XYZ" };

console.log(
  Object.entries(obj).map(([position, name]) => ({ position, name }))
);


text:
Q: I dont understand how to use action bar sherlock with tabs I am trying to add tabs to action bar sherlock, but it keeps on crashing and won't start. What am I supposed to put in the xml files, I can't find what to put in them
MainActivity.java
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.ActionBar.TabListener;
import com.actionbarsherlock.app.*;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;

public class MainActivity extends SherlockFragmentActivity{

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       // setContentView(R.layout.activity_main);

        final ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        ActionBar.Tab tabData = actionBar.newTab();
        tabData.setText("Match Data");
        tabData.setTabListener(new MyTabListener());
        actionBar.addTab(tabData);

      //  tabRed.setTabListener(new TabListener<TabFragment>(this, "tab1", TabFragment.class));
       /* Tab tabComp = actionBar.newTab();
        tabComp.setText("New Competition");
        tabComp.setTabListener(new TabListener<ScoreRedActivity>(this, "B", ScoreRedActivity.class));
        actionBar.addTab(tabComp);*/
       // tabBlue.setTabListener(new TabListener<TabFragment>(this, tabBlue, TabFragment.class));

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu){
        MenuInflater inflater = getSupportMenuInflater();
        inflater.inflate(R.menu.activity_main, menu);
        return true;
    }

    private class MyTabListener implements ActionBar.TabListener{
        @Override
        public void onTabSelected(Tab tab, FragmentTransaction ft){
            if(tab.getPosition() == 0)
            {
                ScoreRedActivity frag = new ScoreRedActivity();
                ft.replace(R.id.textView1, frag);

            }
        }

        @Override
        public void onTabUnselected(Tab tab, FragmentTransaction ft){

        }

        @Override
        public void onTabReselected(Tab tab, FragmentTransaction ft){
        }

    }

}

My ScoreRedActivity.java which is a fragment
import com.actionbarsherlock.app.SherlockFragment;

import android.os.Bundle;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

public class ScoreRedActivity extends SherlockFragment {

    EditText t;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.activity_score_red, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState){
        t = (EditText) getActivity().findViewById(R.id.weightedRed);
    }

}

activity_score_red.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ScoreRedActivity" >

    <TextView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="You are presently in Fragment A"
        android:id="@+id/textView1"/>

    <Button
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Click me for toast"
        android:id="@+id/button1"/>

</LinearLayout>

here's the logcat
12-22 13:21:38.076: E/AndroidRuntime(394): FATAL EXCEPTION: main
12-22 13:21:38.076: E/AndroidRuntime(394): java.lang.RuntimeException: Unable to start activity ComponentInfo{org.say.upscorer/org.say.upscorer.MainActivity}: android.support.v4.app.SuperNotCalledException: Fragment ScoreRedActivity{45f8b1c8 #0 id=0x1020002} did not call through to super.onActivityCreated()
12-22 13:21:38.076: E/AndroidRuntime(394):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
12-22 13:21:38.076: E/AndroidRuntime(394):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
12-22 13:21:38.076: E/AndroidRuntime(394):  at android.app.ActivityThread.access$2300(ActivityThread.java:125)
12-22 13:21:38.076: E/AndroidRuntime(394):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
12-22 13:21:38.076: E/AndroidRuntime(394):  at android.os.Handler.dispatchMessage(Handler.java:99)
12-22 13:21:38.076: E/AndroidRuntime(394):  at android.os.Looper.loop(Looper.java:123)
12-22 13:21:38.076: E/AndroidRuntime(394):  at android.app.ActivityThread.main(ActivityThread.java:4627)
12-22 13:21:38.076: E/AndroidRuntime(394):  at java.lang.reflect.Method.invokeNative(Native Method)
12-22 13:21:38.076: E/AndroidRuntime(394):  at java.lang.reflect.Method.invoke(Method.java:521)
12-22 13:21:38.076: E/AndroidRuntime(394):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
12-22 13:21:38.076: E/AndroidRuntime(394):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
12-22 13:21:38.076: E/AndroidRuntime(394):  at dalvik.system.NativeStart.main(Native Method)
12-22 13:21:38.076: E/AndroidRuntime(394): Caused by: android.support.v4.app.SuperNotCalledException: Fragment ScoreRedActivity{45f8b1c8 #0 id=0x1020002} did not call through to super.onActivityCreated()
12-22 13:21:38.076: E/AndroidRuntime(394):  at android.support.v4.app.Fragment.performActivityCreated(Fragment.java:1470)
12-22 13:21:38.076: E/AndroidRuntime(394):  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:931)
12-22 13:21:38.076: E/AndroidRuntime(394):  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
12-22 13:21:38.076: E/AndroidRuntime(394):  at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
12-22 13:21:38.076: E/AndroidRuntime(394):  at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444)
12-22 13:21:38.076: E/AndroidRuntime(394):  at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:551)
12-22 13:21:38.076: E/AndroidRuntime(394):  at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1129)
12-22 13:21:38.076: E/AndroidRuntime(394):  at android.app.Activity.performStart(Activity.java:3781)
12-22 13:21:38.076: E/AndroidRuntime(394):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2636)
12-22 13:21:38.076: E/AndroidRuntime(394):  ... 11 more

A: You needed to add
super.onActivityCreated(savedInstanceState)

after
t = (EditText) getActivity().findViewById(R.id.weightedRed);

This is because, as your LogCat says
did not call through to super.onActivityCreated()

Some methods, namely the ones that have to do with initializing and the lifecycle of Activities and Fragments need to have a call to the superclass method they override because there are things done higher up the chain that you are not overriding.Be aware though, that not all overriden methods need a call to super, Activity and Fragment lifecycle methods are a special case just because they're so complicated and you can't be expected to rewritethe whole Activity/Fragment class every single time you make an application.


text:
Q: Laravel 5 Query Builder Left Join I want to execute following mysql command in laravel
SELECT stars.*, SUM(points.amount) AS total_points
FROM stars
LEFT JOIN points ON stars.id = points.star_id
GROUP BY stars.id

So I wrote:
\DB::table('stars')
            ->leftJoin('points', 'stars.id', '=', 'points.star_id')
            ->select(\DB::raw("stars.*, SUM('points.amount') AS total_points"))
            ->groupBY('stars.id')
            ->get();

when I dump and die the result, I see total_points is 0.0. What's Wrong?

A: Perhaps the problem in quotation marks?
->select(\DB::raw("stars.*, SUM('points.amount') AS total_points"))

Correctly:
->select(\DB::raw("stars.*, SUM(points.amount) AS total_points"))

Simple variant:
->selectRaw('stars.*, SUM(points.amount) AS total_points')


text:
Q: jQuery script crashing web page I have a page with a carousel on using the infinite-carousel plugin.
When I run the page it crashes my browser and asks if I want to stop the unresponsive script.
In my JS file to call the action I have...
$(document).ready(function(){
    $('#viewport').carousel('#simplePrevious', '#simpleNext');
    $('.gallery-viewport-ext').carousel('.gallery-viewport-ext #simplePrevious', '.gallery-viewport-ext #simpleNext');
    $('.gallery-viewport-int').carousel('.gallery-viewport-int #simplePrevious', '.gallery-viewport-int #simpleNext');
    $('.gallery-viewport-gw').carousel('.gallery-viewport-gw #simplePrevious', '.gallery-viewport-gw #simpleNext');
    $('.gallery-viewport-theroofterrace').carousel('.gallery-viewport-theroofterrace #simplePrevious', '.gallery-viewport-theroofterrace #simpleNext');
    $('.gallery-viewport-photos').carousel('.gallery-viewport-photos #simplePrevious', '.gallery-viewport-photos #simpleNext');
    $('.gallery-viewport-onebedroomapartment').carousel('.gallery-viewport-onebedroomapartment #simplePrevious', '.gallery-viewport-onebedroomapartment #simpleNext');
    $('.gallery-viewport-twobedroomapartment').carousel('.gallery-viewport-twobedroomapartment #simplePrevious', '.gallery-viewport-twobedroomapartment #simpleNext');
    $('.gallery-viewport-externals').carousel('.gallery-viewport-externals #simplePrevious', '.gallery-viewport-externals #simpleNext');

    $('#slider-stage').carousel('#previous', '#next');
    $('#tab-container').easytabs();

                //Examples of how to assign the ColorBox event to elements
                $(".group1").colorbox({rel:'group1'});
                $(".group2").colorbox({rel:'group2', transition:"fade"});
                $(".group3").colorbox({rel:'group3', transition:"none", width:"75%", height:"75%"});

    // Dropdown, show more text
    $('.useful-links ul li a').on('click', function () {
        $(this).next('p').toggle();
        return false;
    });
});

If I remove the
$('.gallery-viewport-int').carousel('.gallery-viewport-int #simplePrevious', '.gallery-viewport-int #simpleNext');

which starts the action for that page the page then loads.
Has anybody an idea on what could be going wrong? or how I can debug it?


text:
Q: Parse positions of dictionary values into a list Let's say you have a dictionary with the following type of data:
{'abc':'AGCTAC', 'def': 'AGGTAC', 'ghi':'AGGTAG'}

I want to be able to run a function that shows the values at each position, e.g.
(('A','A','A'),('G','G','G'),('C','G','G'))

And then be able to run a counter such as people have suggested with collections Counter.

A: >>> d = {'abc':'AGCTAC', 'def': 'AGGTAC', 'ghi':'AGGTAG'}
>>> zip(*d.values())
[('A', 'A', 'A'), ('G', 'G', 'G'), ('C', 'G', 'G'), ('T', 'T', 'T'), ('A', 'A', 'A'), ('C', 'G', 'C')]

Remember that dicts are unordered, so the elements in the tuples may occur in a different order. However the order will be the same for all the tuples
In Python3, zip returns a "zip object" so you need to wrap tuple() around it
>>> tuple(zip(*d.values()))
(('A', 'A', 'A'), ('G', 'G', 'G'), ('C', 'G', 'G'), ('T', 'T', 'T'), ('A', 'A', 'A'), ('C', 'G', 'C'))

If you don't need the intermediate tuple, just pass to Counter
>>> from collections import Counter
>>> Counter(zip(*d.values()))
Counter({('A', 'A', 'A'): 2, ('C', 'G', 'G'): 1, ('G', 'G', 'G'): 1, ('T', 'T', 'T'): 1, ('C', 'G', 'C'): 1})


text:
Q: Playing videos from terminal I am trying to play videos from terminal using this command
vlc my_video.avi

The error that I am getting when I try to run the command--
VLC media player 2.1.4 Rincewind (revision 2.1.4-0-g2a072be)
[0x8663910] main libvlc: Running vlc with the default interface. Use 'cvlc' to use    vlc without interface.
[0xaafddf80] filesystem access error:cannot open file the_file_path (no such file or directory)
[0xb040a990] main input error:open of 'file://the_file_path' failed

Then I tried to use 'cvlc' but again same error!

A: Try install mplayer
sudo apt-get install mplayer

and run
mplayer -vo caca <movie_file

and check whether you are able to play the video

A: There must be something wrong with your filename. I tried two things.

*

*vlc wrongfileName.mp4 and it gave me the error you described.

*vlc correctFileName.mp4 this one gave different error output, but the file did open, so I suspect you made a typo or need to quote the path if it has spaces or special characters

second error for reference:
navjeet@navjeet-Lenovo-G50-80:~/Videos/Game Of Thrones GOT/Season 2$
vlc Game.of.Thrones.S02E08.HDTV.x264-ASAP.mp4 VLC media player 2.2.2
Weatherwax (revision 2.2.2-0-g6259d80) [000000000141a148] core libvlc:
Running vlc with the default interface. Use 'cvlc' to use vlc without interface.
Failed to open VDPAU backend libvdpau_va_gl.so: cannot open shared object file: No such file or directory Failed to open VDPAU backend libvdpau_va_gl.so: cannot open shared object file: No such file or directory [00007f6b74000ee8] http access error: error:
HTTP/1.1 522 Origin Connection Time-out [00007f6b840019d8] http access error: error: HTTP/1.1 522 Origin Connection Time-out [00007f6b74000ee8] core access error: connection failed: Network is unreachable [00007f6b74000ee8] core access error: connection failed:
Network is unreachable [00007f6b74000ee8] http access error: cannot connect to services.tvrage.com:80

A: why did no one suggest totem, which is preinstalled? ^^
cd /path/to/location/of/video
totem video.mp4

A: This is easy :
playername video_or_audio_file_name

And you should not be under root.


text:
Q: NSOutputStream flushing I'm working on an iPhone App and wanted to use:
CFStreamCreatePairWithSocketToHost(NULL, url, port, &serverReadStream, &serverWriteStream);

And after that use the:
[serverWriteStream write:[sendData bytes] maxLength:[sendData length]];

I want to send small Packages of 5 Bytes to get realtime updates.
My problem is now, that the stream only sends data when the buffer is full. So I need some kind of a flush method or tell the stream to immediately send the data.
Searching for this problem ended in finding 'TCP_NODELAY' which seems to belong to the undocumented API ( which I mustn't use for AppStore, correct me if im wrong pls ) and even if I might be allowed to use it, I would have to change the creation of the streams, right?

A: Cocoa NSOutputStream send to a connection
Just add an "end of line" ( "\n" ) to your string. work for me.


text:
Q: Java toString error I'm trying write a class for this program and this class creates a board for which an object moves in. the Board is supposed to look like a box with "+" on the four corners and "-" going vertically and "|" going horizontally with an empty center:
+-----+
|     |
|     |
|     |
|     |
+-----+

I, on the other hand, get brackets going horzontally around the edges, and commas filling the middle, I do not know why:
[ , , , , ]
[ , , , , ]
[ , , , , ]
[ , , , , ]
[ , , , , ]

My program is right, but I need help with my class.
import java.util.Arrays;
import java.util.Random;

public class Board {

    private char [][] theBoard;

    public Board() {
        this(10, 25);
    }

    public Board (int rows, int cols) {
        if (rows < 1 || rows>80) {
            rows = 1;
        }
        if (cols<1 || cols > 80) {
            cols = 1;
        }
        theBoard = new char [rows][cols];
        for (int row = 0; row < theBoard.length; row++) {
            for (int col = 0; col < theBoard[row].length; col++)
                theBoard[row][col] = ' ';
    }
    }

        public void clearBoard() {
        for (int row = 0; row < theBoard.length; row++ ) {
        for (int col = 0; col < theBoard[row].length; col++) {
      if (theBoard[row][col] < '0' || theBoard[row][col] > '9') {
      theBoard[row][col] = ' ';
    }
    }
    }
    }

            public void setRowColumn(int row, int col, char character) {
           theBoard[row][col] = character;
        }

            public char getRowColumn(int row, int col) {
            return theBoard[row][col];
        }

        public String toString() {
    StringBuilder strb = new StringBuilder();
    for (char[] chars : theBoard) {
        strb.append(Arrays.toString(chars) + "\n");
    }
    return strb.toString();
    }
    public static void main(String [] args)
   {
      Board aBoard, anotherBoard;

      System.out.println("Testing default Constructor\n");
      System.out.println("10 x 25 empty board:");

      aBoard = new Board();
      System.out.println(aBoard.toString());

      System.out.println();

      // And, do it again
      System.out.println("Testing default Constructor again\n");
      System.out.println("10 x 25 empty board:");

      anotherBoard = new Board();
      System.out.println(anotherBoard.toString());

   } // end of method main
} // end of class

A: The default constructor fills the array with empty spaces: ' '.
When you call the Arrays.toString() method, it prints an open bracket, followed the contents of the array (separated by commas), followed by a closed bracket.
For example, if you had an array:
i  a[i]
0   1
1   2
3   5
4   8

Calling Arrays.toString(a) prints out:
[1, 2, 5, 8]

As another example, if you had an array filled with empty spaces, you'd get:
[ ,  ,  ,  ,  , ]

(see the spaces?)
This is why you're receiving that output.