text:
Q: disable tab-scrolling in Chrome/Chromium Is there a chrome/chromium build that addresses the anti-feature discussed here, where making the mistake of scrolling while the cursor is over the tab bar has the effect of scrolling to random tabs? Specifically I'm interested in a build that reverts this behavior.

A: Works on ubuntu 20, chromium 93:

*

*go to chrome://flags/#scrollable

*to enable scrolling, set to defaults: "Tab Scrolling" and "Tab Scrolling Buttons"

*to disable scrolling, enable: "Tab Scrolling" and "Tab Scrolling Buttons"

*Restart chrome/chromium

Update 2022.02.25
It seems like they've renamed things (in chromium at least). Here are the new steps:

*

*Navigate to chrome://flags/

*In the search bar, search for "Scroll switches tab"

*In the dropdown select, "Never"

*Restart chromium

A: You'll need to place your vote by starring an issue to fix this bug at https://bugs.chromium.org/p/chromium/issues/detail?id=680499. It wouldn't hurt if you found several more (or several hundred more) people to do the same. Once enough people star the issue, developers will get to work and get the option added so you can easily disable (or enable if you like) this functionality.


text:
Q: Ruby gems with C extensions not building in Ubuntu I'm trying to base a Dockerfile off of Heroku's new heroku/heroku:18 image (which uses Ubuntu 18.04) and running into some issues that I didn't have in their very old heroku/cedar:14 base image, I believe due to them having different preinstalled packages. (I updated the base image to heroku/heroku:18 because I want to use the webpacker gem and in Cedar-14 I was getting: Webpacker requires Node.js >= 6.0.0 and you are using 0.10.25. If there's an easy way to install a newer Node in the older base image I'd love to hear it!)
My problem is that no gems with C extensions (like puma, pg, msgpack, etc. etc.) install successfully with this new base Docker image. The error messages vary slightly from gem to gem but all generally say:
The compiler failed to generate an executable file. (RuntimeError)
You have to install development tools first.

Various GitHub issues with similar problems have had me try:

*

*apt-get installing:

*

*build-essential

*libpq-dev

*libssl-dev

*openssl

*libssl1.0-dev

*gcc

*gcc-5

*automake

*make

*Using heroku/heroku:18-build instead of heroku/heroku:18
None of these solutions solves the issue.
For reference, here are the relevant parts of my Dockerfile:
FROM heroku/heroku:18

RUN apt-get update && apt-get install -y nodejs --no-recommends

RUN (mkdir -p /ruby && cd /ruby && curl https://s3-external-1.amazonaws.com/heroku-buildpack-ruby/heroku-18/ruby-2.5.0.tgz -s -o - | tar xzf - --no-same-owner)

ENV GEM_HOME=/ruby/gems GEM_PATH=/ruby/gems

RUN gem install bundler

RUN bundle install

redpajama_set_name: RedPajamaStackExchange


text:
Q: Any way help to revert part of a histroy commit in git? suppose i have below commits history in a git repository (all changes are made on one single file)

*

*remove function foo() and bar(), modify function baz()

*change something else

Now i want to re-add the function foo() back. What I desired is a interact manually way to do this. For example, an editor is opened in side-by-side diff mode. On one side is the version before the commit #1 (which include function foo()), on the other side is my local working copy. So that I can copy anything I want from the history side to working copy side.
Is there any git commands can help me to do this?
Thanks

A: Here is one solution, which is what I'd probably do:
# Stash any current modifications to be safe.
git stash

# Make a new commit that re-adds foo, bar and maz
git revert <sha of the commit with your function>

# Remove the commit you just created, but leave the file changes.
git reset HEAD^

# Interactively decide which chunks of code you actually want.
# Just follow the instructions, type '?' for help.
git add -p

# Commit all of the changes that you staged.
git commit

# Discard all the other stuff you didn't accept.
git checkout .


text:
Q: Permutation count of "AEIOUBCDF" where vowels are ascending and consonants are descending Say we have the string "AEIOUBCDF". How many ways can this string be permuted such that the vowels remain in ascending order, and the consonants remain in descending order (e.g. "AFDEICOUB" is a valid permutation)?

A: Hint:
You have $9$ slots to fill.  Choose $5$ slots for the vowels.  Everything else is determined.

A: A slightly different approach is this:
Consider all 9! possible permutations.
But only one permutation of the vowels is valid -> divide by 5!
and only one permutation of the consonants is valid -> divide by 4!
That gives you 9! / (4! 5!) which is exactly the formula for C(9,5) = C(9,4).


text:
Q: Mime multipart NoSuchMethodError exception in android I'm trying to use Mime to transfer files between 2 Android devices.
I have a sendFile() method which (surprisingly) sends the requested file.
Here's the code:
public void sendFile(File f) throws IOException {
    BufferedOutputStream out = new BufferedOutputStream(s.getOutputStream());
    String filename =
        f.getAbsolutePath().substring(f.getAbsolutePath().lastIndexOf("/") + 1);

    MultipartEntity multipartContent = new MultipartEntity();

    // send the file thorugh inputstream
    InputStreamBody isb =
        new InputStreamBody(new FileInputStream(f), filename);

    multipartContent.addPart("sentFile", isb);

    multipartContent.writeTo(out);
    out.flush();
    out.close();
}

Now, I'm using the apache-mime4j-0.5.jar & httpmime-4.0-alpha3.jar files to support the "MultipartEntity" usage.
Now, the jars are located in "libs" file in my android (app) project, and there are no importing issues (the project compiles...).
Still, I'm getting this runtime error:
06-17 14:06:29.900: E/AndroidRuntime(22251): FATAL EXCEPTION: Thread-11
06-17 14:06:29.900: E/AndroidRuntime(22251): java.lang.NoSuchMethodError: org.apache.james.mime4j.message.Multipart.<init>
06-17 14:06:29.900: E/AndroidRuntime(22251): at org.apache.http.entity.mime.HttpMultipart.<init>  (HttpMultipart.java:64)
06-17 14:06:29.900: E/AndroidRuntime(22251): at org.apache.http.entity.mime.MultipartEntity.<init>(MultipartEntity.java:76)
06-17 14:06:29.900: E/AndroidRuntime(22251): at org.apache.http.entity.mime.MultipartEntity.<init>(MultipartEntity.java:99)
06-17 14:06:29.900: E/AndroidRuntime(22251): at com.cdp.controller.Connection.sendFile(Connection.java:71)
06-17 14:06:29.900: E/AndroidRuntime(22251): at com.cdp.controller.Controller.handleRequest(Controller.java:41)
06-17 14:06:29.900: E/AndroidRuntime(22251): at com.cdp.service.ServerService$SenderThread.run(ServerService.java:109)

What could be the origin to this problem? How can I solve it?
The app crashes while trying to instantiate the new MultipartEntity() object as seen in the code.
I've gone trough many posts and nothing I tried works. I'll appreciate your help!
Thanks.


text:
Q: How to use curl and an array of URLs together I found this code that does what I'm looking for on a single domain check. But I have a list of URLs that I would like to check.
Can you and how would you create an array with curl?
$url = 'http://www.example.com';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, true);    // we want headers
curl_setopt($ch, CURLOPT_NOBODY, true);    // we don't need body
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT,10);
$output = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

echo 'HTTP code: ' . $httpcode;

A: If all you want are headers, then instead of curl try:
$urls = array('http://www.example.com','http://www.example.com2','http://www.example.com3','http://www.example4.com');

$httpCodes = [];
foreach($urls as $url)
{
    $httpCodes[$url] = get_headers($url)[0];
}

var_dump($httpCodes);

This uses get_headers() to get the header data from a URL's response.
Edit: Or if you really want to use curl. you can use the following code with curl_multi instead:
$urls = array('http://www.example.com','http://www.example.com2','http://www.example.com3','http://www.example4.com');

$curlMultiReq = curl_multi_init();
$ch = [];
foreach($urls as $key => $url)
{
    $ch[$key] = curl_init($url);
    curl_setopt($ch[$key], CURLOPT_HEADER, true);    // we want headers
    curl_setopt($ch[$key], CURLOPT_NOBODY, true);    // we don't need body
    curl_setopt($ch[$key], CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch[$key], CURLOPT_TIMEOUT,10);
    curl_multi_add_handle($curlMultiReq, $ch[$key]);
}
$running = '';

do {
  curl_multi_exec($curlMultiReq, $running);
  curl_multi_select($curlMultiReq);
} while ($running > 0);

foreach(array_keys($ch) as $key){
  echo curl_getinfo($ch[$key], CURLINFO_HTTP_CODE);
  echo "\n";
  curl_multi_remove_handle($curlMultiReq, $ch[$key]);
}
curl_multi_close($curlMultiReq);


text:
Q: passing data between view controllers using combine framework in Swift I am trying out combine using swift and UIKit. I have a table view with list of data and while I select a row i need to pass the data to detail page. However the data is missing at times when i click same/different row very fast.
class GitHubLinkDetails: UIViewController {

 var githubDetails = PassthroughSubject<GitHubModel,Never>()

    override func viewDidLoad() {
        super.viewDidLoad()
        getDetails()
        // Do any additional setup after loading the view.
    }

 func getDetails() {

 githubDetails
         .sink { [weak self] githubData in

                self?.username.text = githubData.builtBy[0].username
            }
            .store(in: &cancellables)
    }
}

And in table view didselect method i push to the class GitHubLinkDetails along with data
class GitHubListing: UIViewController {

    var viewModel = GitHubListingViewModel()
    private var cancellables = Set<AnyCancellable>()
    let reuseIdentifier = "Cell"
    @IBOutlet weak var gitHubListingTable: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()

        gitHubListingTable.dataSource = self
        gitHubListingTable.delegate = self

        self.gitHubListingTable.register(UINib(nibName: "GitHubListCell", bundle: nil), forCellReuseIdentifier: reuseIdentifier)

        viewModel.getGitHubListing()

        viewModel.$trendingGitHubList
            .receive(on: RunLoop.main)
            .sink { [weak self] _ in
                self?.gitHubListingTable.reloadData()

            }
            .store(in: &cancellables)

    }

}
extension GitHubListing: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.getListCount()
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = gitHubListingTable.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as! GitHubListCell

        viewModel.$trendingGitHubList
            .receive(on: RunLoop.main)
            .sink { gitHubModel in
                if let gitHubModel = gitHubModel {
                    cell.configureCell(with: gitHubModel[indexPath.row])
                }
            }
            .store(in: &cancellables)

        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let gitHubDetails = GitHubLinkDetails()
        tableView.deselectRow(at: indexPath, animated: true)
        viewModel.$trendingGitHubList
            .receive(on: RunLoop.main)
            .sink { githublist in
                if let githublist = githublist {
                    gitHubDetails.githubDetails.send(githublist[indexPath.row])
                }
            }
            .store(in: &cancellables)
        navigationController?.pushViewController(gitHubDetails, animated: true)
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        75
    }

}

I would appreciate any help. thank you so much


text:
Q: Pandas: How to create row-based boolean mask similar to Excel's OFFSET function based on a value in another column The larger scope of this question is that I have time series stock data that is collected hourly, and I want to track the data over several timeframes (1 hour, 1 day, 1 week, 1 month, etc.).
Certain functions require me to selectively pick out certain rows (for example, a single record at the end of each month, for the sake of determining true standard deviation). Therefore there are a given # of 'bars' (rows) that each of those timeframes encompasses. I've already made a column in my dataframe that tracks that # of rows per period. Due to holidays, as well as the simple fact that a month's time period varies based on the month, the # of rows per period also varies over time; otherwise it would just be a simple shift of a static value (like 7 for the daily timeframe on hourly data (6.5 hours in a trading day)).
I need to create a boolean mask for the entire dataframe every time a new row of data comes in to maintain accuracy in my lookbacks. How would I go about doing this by avoiding having to manually loop over the entire dataframe every time I get new data? Keep in mind that you need to work backwards from the latest entry towards the earliest.
Here's a much simpler dataframe example to work with:
df = pd.DataFrame({'state': np.arange(1, 11), 'bars': [1, 2, 3, 3, 3, 4, 5, 5, 4, 3]})

# Results in:

    state   bars
0   1       1
1   2       2
2   3       3
3   4       3
4   5       3
5   6       4
6   7       5
7   8       5
8   9       4
9   10      3

# I would expect `boolean_mask` to look like this:

0   False
1   True
2   False
3   False
4   False
5   False
6   True
7   False
8   False
9   True

# Therefore `df[boolean_mask].loc['state']` becomes:

0   2
1   7
2   10

# If row #9 did not exist, the resulting mask would be different.

A: Figured it out; it was simpler than I imagined. The solution is to reverse the dataframe, apply a function that decrements until there are no more bars to ignore, then assigns True and repeats the process; finally, reverse that list and we have our boolean mask.
def OnPeriod(bars, r):
  if r['bars'] == 0:
      r['bars'] = bars - 1
      return True

  r['bars'] -= 1
  return False

mask = df['bars'][::-1].apply(OnPeriod, args=[{'bars': 0}])[::-1].values


text:
Q: "should be accessed in a static way" I have a class with a probably unnecessarily cumbersome name, that contains a lot of static methods I use elsewhere.
Rather than fill my code with a lot of
VeryUnnecessarilyLongCumbersomeName.doThingFoo();
VeryUnnecessarilyLongCumbersomeName.doThingBar();
VeryUnnecessarilyLongCumbersomeName.doThingEgg();
VeryUnnecessarilyLongCumbersomeName.doThingSpam();

I would rather have
VeryUnnecessarilyLongCumbersomeName thing = new VeryUnnecessarilyLongCumbersomeName();
thing.doThingFoo();
thing.doThingBar();
thing.doThingEgg();
thing.doThingSpam();

However, this gets the warning
"the static method doThingFoo() should be accessed in a static way."

I know there are multiple solutions here.  Use better class names.  Make it not static.  Ignore it because it's just a warning.
But I don't actually think it should be a warning.  What harm does doing it this way cause?  Is there a more elegant/correct way to make my code less clunky that isn't one of the above solutions?
NOTE: I suspect this might warrant the coding-style tag and therefore be considered off-topic and get rejected.  I was thinking there's room here for a question like this, however, so I leave it up to y'all.

A: Although it is not technically harmful because it technically works, the problem with this is it is misleading, and any values that the instance thing contains, do not actually matter at all for the results of the methods.
Typical Java Convention:
When accessing a method through an instance, one would expect the result to be dependent on the values of the instance.
When accessing a method through a Class name, one would expect the result to be independent of the values of any instance.
Your way:
You are accessing a method through an instance and expecting it to be independent of any instance.
So why use an instance for an instance independent method?  That is why it is misleading.  I would suggest attempting to shorten the class name rather than accessing static methods through an instance.

A: How about changing the VeryUnnecessarilyLongCumbersomeName class?
Static methods are there to be used without instances. They are meant to be used if you want to invoke the method without first initializing a class. The downside of using static methods is that you lose all kinds of OOP benefits; You lose virtual dispatch and subsequently polymorphism. You can never override that method in a derived class. Of course you can declare a new (static) method in a derived class, but any code that accesses it has to be aware of the entire class hierarchy and do explicit checking and casting, which is precisely what OO is supposed to avoid.
Also, it is confusing. When another programmer sees your code, he/she will think upon seeing a static he/she will assume that it will not require a valid instance to invoke the method.
TLDR; don't do it and stick with the best practices =)


text:
Q: Can IntelliJ IDEA open more than one editor window for files from the same project? I can split editor panes horizontally or vertically, but it does not seem possible to view code in two separate physical windows.  I am aware that Idea can open multiple projects in separate windows, but I'd like to be able to do this for two files in a single project.
One answer suggested unpinning the tab, but I haven't been able to make that work (I'm on Mac OSX if that matters.)
This seems like a basic feature in today's world of multi-headed workstations.  Before moving to an IDE I used to do this regularly with good old Emacs.  Is there some trick I am not aware of to make this happen?

A: This is now possible in IDEA X. Hopefully you're still an IDEA user and can take advantage of this :)

A: Unfortunately there is no way (as of IDEA 8.0.1) to do what you're asking for. As you pointed out, you can split the editor pane but there is always exactly one editor per IDEA project.
UPDATE: As of IDEA 10 (currently the latest is 10.5), the answer is yes, you can :-)

A: I work around the limitation by opening one source file in vi, on a second head monitor.
Then work main file within Idea (actually Pycharm).
Update: even with the feature built into pycharm, I still use vi.  Works better.

A: As per @9000's comment, an editor tab can be turned into a new window by dragging the tab outside of IDEA.

A: Yes- with IDEA X, it is finally possible to open multiple editor windows.


text:
Q: back page and next page again with values still intact in edittext Im wondering is there any method where i can use to have the same values display on the edittext after the application goes to previous page and back to the orignal page?
e.g in Page 1, the user pressed next page button and it goes to page 2, users key in some values in edittext. From page 2, i implemented onBackPressed(), therefore when the user goes back to page 1 the values on edittext is on where they are suppose to be.
here comes my question, when the user goes back to page 2 the values that will previously enter in the edittext are gone.
This the method i implemented on page 1 that enables users to goes to page 2
public void nextPage(View view) {
        variables vb = new variables();
        Intent intent_next = new Intent(this,
                Display_form_personal_details2.class);
        startActivity(intent_next);

This the method i implemented on page 2 that enables users to goes to page page 1
public void previousPage (View view){
        Intent intent_previous = new Intent (this, Display_form_personal_details.class);
        onBackPressed();

    }

A: use putExtras() method to get the value:
public void previousPage (View view){
    Intent intent_previous = new Intent (this, Display_form_personal_details.class);
    intent_previous.putExtra(<String name>, <String value>);
    onBackPressed();

}


text:
Q: Como inserir dados em uma tabela que tem várias foreign key e se relaciona com outras 4 tabelas usando Laravel com Eloquent? Eu tenho uma tabela que possui 4 Foreign keys e se relaciona com outras 4 tabelas.
Eu gostaria de saber como eu inseriria todos os registros, vindos no Request, nessa tabela, incluindo suas foreign key.
Estou meio perdido no método store() da model e com o uso do Eloquent para essa situação.
Os dados, inclusive os valores das foreign key, viriam no Request.
OBS: Estou usando Relacionamento OneToMany em todas essas tabelas.
Vou deixar um print da tabela (task_lists) no banco de dados.

*

*Vou deixar alguns links do meu código para não poluir aqui e a pergunta não ficar muito extensa.

Migration
Rotas
Model:
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Models\Recurrence; //Chamando a model Recurrence (inserido)
use App\Models\User; //Chamando a model User (inserido)
use App\Models\TaskType; //Chamando a model TaskType (inserido)
use App\Models\Status; //Chamando a model Status (inserido)

class TaskList extends Model
{
   //Dados que podem ser inseridos em massa na tabela
    protected $fillable = [
        'number_of_process',
        'expire_day',
        'expire_date',
        'start_date',
        'end_date',
        'details',
    ];

    //Dados que não podem ser inseridos em massa
    protected $guarded = [
        'recurrence_id',
        'concluding_user_id',
        'task_type_id',
        'status_id',
    ];

    public function rules()
    {
        //As regras de cada campo
        return [
            'recurrence_id' => 'required',
            'concluding_user_id' => 'required',
            'task_type_id' => 'required',
            'status_id' => 'required',
            'number_of_process' => 'required',
            'expire_day' => 'required',
            'expire_date' => 'required',
        ];
    }

    //Criando o relacionamento com a model(tabela) Recurrence (Muitos para 1)
    public function recurrence()
    {
        return $this->belongsTo(Recurrence::class);
    }

    //Criando o relacionamento com a model(tabela) User (Muitos para 1)
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    //Criando o relacionamento com a model(tabela) TaskType (Muitos para 1)
    public function taskType()
    {
        return $this->belongsTo(TaskType::class);
    }

    //Criando o relacionamento com a model(tabela) Status (Muitos para 1)
    public function status()
    {
        return $this->belongsTo(Status::class);
    }
}

?>

Controller
<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
use App\Models\Recurrence;
use App\Models\User;
use App\Models\TaskType;
use App\Models\Status;
use App\Models\TaskList;

class TaskListController extends BaseController
{
    protected $request;
    protected $recurrence;
    protected $user;
    protected $taskType;
    protected $status;
    protected $model;

    //Injeção de Dependência
    public function __construct(Request $request, Recurrence $recurrence, User $user, TaskType $taskType, Status $status, TaskList $TaskList)
    {

        $this->request = $request;
        $this->recurrence = $recurrence;
        $this->user = $user;
        $this->taskType = $taskType;
        $this->status = $status;
        $this->model = $taskList;

    }

     //use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    //Mostra todos os dados de uma determinada Tabela
    public function index()
    {
         $data = $this->model->all();
         return response()->json($data);
    }

    //Grava dados em uma determinada Tabela
    public function store(Request $request)
    {

        $request->validate($this->model->rules());
        $dataForm = $request->all(); //Dados que vem da requisição

        $recurrence = $this->recurrence->find($dataForm['recurrence_id']);
        $user = $this->user->find($dataForm['user_id']);
        $taskType = $this->taskType->find($dataForm['task_type_id']);
        $status = $this->status->find($dataForm['status_id']);

        $data = [
            'task_name' => $dataForm['task_name'],
            'details' => $dataForm['details'],
        ];

        $recurrence->recurrence()->create($data);
        $user->user()->create($data);
        $taskType->taskType()->create($data);
        $status->status()->create($data);

        return response()->json($dataForm, 201);

    }

}

?>

Resumindo: Eu gostaria de inserir todos os registros nessa tabela só que não estou encontrando a forma correta por causa das quatro foreign key. Geralmente consigo fazer quando a tabela se relaciona com somente mais uma outra tabela.

A: public function store(Request $request)
{
    $request->validate($this->model->rules());
    $dataForm = $request->all();

    $taskList = new TaskList ;

    $recurrence = $this->recurrence->find($dataForm['recurrence_id']);

    $user = $this->user->find($dataForm['user_id']);

    $taskType = $this->taskType->find($dataForm['task_type_id']);

    $status = $this->status->find($dataForm['status_id']);

    $taskList->task_name = $dataForm['task_name'];
    $taskList->details = $dataForm['details'];

    $taskList->recurrence()->associate($recurrence);
    $taskList->user()->associate($user);
    $taskList->taskType()->associate($taskType);
    $taskList->status()->associate($status);

    $taskList->save();

    return response()->json($dataForm, 201);

}


text:
Q: EndpointNotFoundException 'Could not connect' because 'the target machine actively refused it' Connecting through Fiddler I am encountering an issue trying to route my WCF client requests through Fiddler. I have searched the web high and low, and found only two references to Fiddler having problems when WCF services are configured to listen on IPv4, but IPv6 is enabled. However, while my issue is similar, it does not seem to be my problem.
I am encountering issues connecting to services hosted on IPv4 ports. The following exception is thrown by my WCF clients when my bindings are configured to use the fiddler proxy. I have disabled IPv6 support in Fiddler's options, and made sure my bindings are properly configured to use the proxy.
Exception report:

System.ServiceModel.EndpointNotFoundException:
  Could not connect to
  http://campus.services.ecollege-labs.com/Entity/Foundation/v1.0/EducationalPartnerSvc.
  TCP error code 10061: No connection
  could be made because the target
  machine actively refused it
  10.181.3.23:8888.  ---> System.Net.WebException: Unable to
  connect to the remote server --->
  System.Net.Sockets.SocketException: No
  connection could be made because the
  target machine actively refused it
  10.181.3.23:8888    at System.Net.Sockets.Socket.DoConnect(EndPoint
  endPointSnapshot, SocketAddress
  socketAddress)    at
  System.Net.ServicePoint.ConnectSocketInternal(Boolean
  connectFailure, Socket s4, Socket s6,
  Socket& socket, IPAddress& address,
  ConnectSocketState state, IAsyncResult
  asyncResult, Int32 timeout, Exception&
  exception)    --- End of inner
  exception stack trace ---    at
  System.Net.HttpWebRequest.GetRequestStream(TransportContext&
  context)    at
  System.Net.HttpWebRequest.GetRequestStream()
  at
  System.ServiceModel.Channels.HttpOutput.WebRequestHttpOutput.GetOutputStream()
  --- End of inner exception stack trace ---
Server stack trace:     at
  System.ServiceModel.Channels.HttpOutput.WebRequestHttpOutput.GetOutputStream()
  at
  System.ServiceModel.Channels.HttpOutput.Send(TimeSpan
  timeout)    at
  System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.SendRequest(Message
  message, TimeSpan timeout)    at
  System.ServiceModel.Channels.RequestChannel.Request(Message
  message, TimeSpan timeout)    at
  System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message
  message, TimeSpan timeout)    at
  System.ServiceModel.Channels.ServiceChannel.Call(String
  action, Boolean oneway,
  ProxyOperationRuntime operation,
  Object[] ins, Object[] outs, TimeSpan
  timeout)    at
  System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage
  methodCall, ProxyOperationRuntime
  operation)    at
  System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage
  message)
Exception rethrown at [0]:     at
  System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage
  reqMsg, IMessage retMsg)    at
  System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData&
  msgData, Int32 type)    at
  IMS.EnterpriseServices.Facades.Campus.EducationalPartner.EducationalPartnerSvc.FindByClientString(String
  clientString)    at
  IMS.EnterpriseServices.Facades.Campus.EducationalPartner.EducationalPartnerSvcClient.FindByClientString(String
  clientString) in
  C:\P4\HEDI\AS2-dev-dotnext-campus-dev\AS\HEI\Src\CAS\IMS.EnterpriseServices.Facades.Campus\Service
  References\EducationalPartner\Reference.cs:line
  428    at
  IMS.EnterpriseServices.Facades.Campus.CampusEntityFacade.GetEPID(String
  clientString) in
  C:\P4\HEDI\AS2-dev-dotnext-campus-dev\AS\HEI\Src\CAS\IMS.EnterpriseServices.Facades.Campus\CampusEntityFacade.cs:line
  37    at
  IMS.EnterpriseServices.Transformation.Domain.TransformationSvc.TransformCreateGroupRequest(createGroupRequestMessage
  message) in
  C:\P4\HEDI\AS2-dev-dotnext-campus-dev\AS\HEI\Src\CAS\IMS.EnterpriseServices.Transformation.Domain\TransformationSvc.cs:line
  106    at
  IMS.EnterpriseServices.Facades.IMSFacade.TransformCreateGroupRequest(createGroupRequestMessage
  imsMessage) in
  C:\P4\HEDI\AS2-dev-dotnext-campus-dev\AS\HEI\Src\CAS\IMS.EnterpriseServices.Facades\IMSFacade.cs:line
  113    at
  IMS.EnterpriseServices.Domain.TransformationAndEnrichmentCoordinator.ProcessCreateGroupRequestMessage(createGroupRequestMessage
  message) in
  C:\P4\HEDI\AS2-dev-dotnext-campus-dev\AS\HEI\Src\CAS\IMS.EnterpriseServices.Domain\TransformationAndEnrichmentCoordinator.cs:line
  140    at
  IMS.EnterpriseServices.Facades.IMSFacade.<>c__DisplayClass1.b__0(Object
  o) in
  C:\P4\HEDI\AS2-dev-dotnext-campus-dev\AS\HEI\Src\CAS\IMS.EnterpriseServices.Facades\IMSFacade.cs:line
  135

Binding Configuration:
<customBinding>
  <!-- Secured, WS-Security message signing and encryption, custom binding for IMS endpoints -->
  <binding name="customHttpSecuredNoWSA">
    <security
      defaultAlgorithmSuite="Basic128Rsa15"
      authenticationMode="MutualCertificate"
      securityHeaderLayout="Lax"
      includeTimestamp="false"
      keyEntropyMode="CombinedEntropy"
      messageProtectionOrder="SignBeforeEncrypt"
      messageSecurityVersion="WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10"
      requireSignatureConfirmation="false"
      requireSecurityContextCancellation="false"
      allowSerializedSigningTokenOnReply="true">
      <localServiceSettings detectReplays="false" />
    </security>
    <textMessageEncoding
      messageVersion="Soap11"
      writeEncoding="utf-8">
      <readerQuotas
        maxArrayLength="1048576"
        maxStringContentLength="4194304"
        maxBytesPerRead="4194304"
        maxNameTableCharCount="4194304"
      />
    </textMessageEncoding>
    <httpTransport
      maxBufferPoolSize="4194304"
      maxBufferSize="1048576"
      maxReceivedMessageSize="1048576"
      proxyAddress="http://my.host.name:8888"
      useDefaultWebProxy="false"
    />
  </binding>
</customBinding>

A: Thanks to comments from Jon Skeet and Paolo, I was able to resolve this issue. It appears that something (possibly a firewall) is interfering with connections to my host name/ip. Using 127.0.0.1 works, however it must be specified as follows in WCF configuration:
proxyAddress="http://127.0.0.1.:8888"
Note the extra period at the end of the 127.0.0.1 loopback address. Without the period, WCF has some kind of hard-coded check to prevent the use of a proxy server at your local loopback. (Why Microsoft would explicitly build in a hard-coded exclusion of the local loopback from proxy server usage is beyond me, but at least this trick works.)


text:
Q: Strange python dictionary keys I encounter a strange dictionary. Let's call it cp_dict. When I type:
 cp_dict['ZnS-Zn']

it returns:
 {Element Zn: -1.159460605, Element S: -4.384479766249999}

The child key looks like a string but without quotation marks. How I can access the child keys (for example: Element Zn) and modify the values? I tried cp_dict['Zn3P2-Zn'][Element Zn], and the error is
SyntaxError: invalid syntax. Perhaps you forgot a comma?

The cp_dict['Zn3P2-Zn']['Element Zn'] leads to:
KeyError: 'Element Zn'

I checked type(cp_dict['ZnS-Zn']) . It returns <class 'dict'>.

A: It is quite easy to make a custom class which represents itself in that way ("looking like a string but without quotation marks"). The result returned by a __repr__ method is what gets used when representing instances inside collections such as dicts and lists:
>>> class Element:
...     def __init__(self, symbol):
...         self.symbol = symbol
...     def __repr__(self):
...         return f"Element {self.symbol}"
...
>>> d = {Element("Zn"): -1.159460605, Element("S"): -4.384479766249999}
>>> d
{Element Zn: -1.159460605, Element S: -4.384479766249999}

So, my guess is the keys of the dict are the strange items, not the dict itself. Check the type of a key, and look up it's __repr__ method. You can get the type of the first key with:
k = next(iter(cp_dict["ZnS-Zn"]))
Element = type(k)

To index the dict you will need an instance which compares equal with one of those keys. Again, look up type(k).__eq__ for that. If the __eq__ method is not customized, then you will need to use the identical key to index this dict, since the equality method will just be the default identity-based implementation which is inherited from object.


text:
Q: OpenGl with http://www.arcsynthesis.org/gltut/ tutorials I have downloaded tutorial 0.3.8 from http://www.arcsynthesis.org/gltut/ then according to instruction I have build visual studio 2010 files by premake4.exe. But when I'm trying to debug project console shows for a second and in output shows:
'Tut 01 MainD.exe': Loaded 'C:\Users\Bartek\Desktop\andagain\Tutorial 0.3.8\Tut 01 Hello Triangle\Tut 01 MainD.exe', Symbols loaded.
'Tut 01 MainD.exe': Loaded 'C:\Windows\SysWOW64\ntdll.dll', Cannot find or open the PDB file
'Tut 01 MainD.exe': Loaded 'C:\Windows\SysWOW64\kernel32.dll', Cannot find or open the PDB file
'Tut 01 MainD.exe': Loaded 'C:\Windows\SysWOW64\KernelBase.dll', Cannot find or open the PDB file
'Tut 01 MainD.exe': Loaded 'C:\Windows\SysWOW64\opengl32.dll', Cannot find or open the PDB file
'Tut 01 MainD.exe': Loaded 'C:\Windows\SysWOW64\gdi32.dll', Cannot find or open the PDB file
'Tut 01 MainD.exe': Loaded 'C:\Windows\SysWOW64\winmm.dll', Cannot find or open the PDB file
'Tut 01 MainD.exe': Loaded 'C:\Windows\SysWOW64\user32.dll', Cannot find or open the PDB file
'Tut 01 MainD.exe': Loaded 'C:\Windows\SysWOW64\advapi32.dll', Cannot find or open the PDB file
'Tut 01 MainD.exe': Loaded 'C:\Windows\SysWOW64\msvcp100d.dll', Symbols loaded.
'Tut 01 MainD.exe': Loaded 'C:\Windows\SysWOW64\msvcr100d.dll', Symbols loaded.
'Tut 01 MainD.exe': Loaded 'C:\Windows\SysWOW64\msvcrt.dll', Cannot find or open the PDB file
'Tut 01 MainD.exe': Loaded 'C:\Windows\SysWOW64\glu32.dll', Cannot find or open the PDB file
'Tut 01 MainD.exe': Loaded 'C:\Windows\SysWOW64\ddraw.dll', Cannot find or open the PDB file
'Tut 01 MainD.exe': Loaded 'C:\Windows\SysWOW64\winmmbase.dll', Cannot find or open the PDB file
'Tut 01 MainD.exe': Loaded 'C:\Windows\SysWOW64\sechost.dll', Cannot find or open the PDB file
'Tut 01 MainD.exe': Loaded 'C:\Windows\SysWOW64\rpcrt4.dll', Cannot find or open the PDB file
'Tut 01 MainD.exe': Loaded 'C:\Windows\SysWOW64\dciman32.dll', Cannot find or open the PDB file
'Tut 01 MainD.exe': Loaded 'C:\Windows\SysWOW64\sspicli.dll', Cannot find or open the PDB file
'Tut 01 MainD.exe': Loaded 'C:\Windows\SysWOW64\cryptbase.dll', Cannot find or open the PDB file
'Tut 01 MainD.exe': Loaded 'C:\Windows\SysWOW64\bcryptprimitives.dll', Cannot find or open the PDB file
'Tut 01 MainD.exe': Loaded 'C:\Windows\SysWOW64\imm32.dll', Cannot find or open the PDB file
'Tut 01 MainD.exe': Loaded 'C:\Windows\SysWOW64\msctf.dll', Cannot find or open the PDB file
'Tut 01 MainD.exe': Loaded 'C:\Windows\SysWOW64\nvinit.dll', Cannot find or open the PDB file
'Tut 01 MainD.exe': Loaded 'C:\Windows\SysWOW64\uxtheme.dll', Cannot find or open the PDB file
'Tut 01 MainD.exe': Loaded 'C:\Windows\SysWOW64\dwmapi.dll', Cannot find or open the PDB file
'Tut 01 MainD.exe': Loaded 'C:\Windows\SysWOW64\ig4icd32.dll', Cannot find or open the PDB file
'Tut 01 MainD.exe': Loaded 'C:\Windows\SysWOW64\version.dll', Cannot find or open the PDB file
'Tut 01 MainD.exe': Unloaded 'C:\Windows\SysWOW64\version.dll'
The program '[7932] Tut 01 MainD.exe: Native' has exited with code 1 (0x1).

@edit: I have windows 8 64-bit if it mean something to that.

A: So I run visual studio on GeForce not on Intel and project is building without any problem.. sorry tor taking time.


text:
Q: Assigning UserId to Foreign Key = null I'm using Entity Framework 5 and MVC 4, with .NET 4.5 using Code First migrations. I have foreign keys between two entities in a 1 to zero-or-1 relationship. When I try to create the record for Jogger everything blows up. I get error messages that are either:

*

*Foreign Key is a null reference

*dbo.Jogger does not exist

*Unhandled exception ... no metadata.

When I run the EF Viewer the navigation relationships are perfect. No Fluent API code is used at the moment.
User Class
     [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string UserName { get; set; }

    // Other properties

    public int? JoggerId { get; set; }
    public virtual Jogger Jogger { get; set; }

Jogger Class
    [ForeignKey("UserId")]
    public int JoggerId { get; set; }

    public virtual UserProfile UserId { get; set; }

When the JoggerController is generated it produces this code for the Get and Post Methods:
// GET: /Jogger/Create

    public ActionResult Create()
    {
        ViewBag.JoggerId = new SelectList(db.UserProfiles, "UserId", "UserName");
        return View();
    }

    //
    // POST: /Jogger/Create

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(Jogger jogger)
    {

        if (ModelState.IsValid)
        {
            db.Jogger.Add(jogger);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.JoggerId = new SelectList(db.UserProfiles, "UserId", "UserName", jogger.JoggerId);
        return View(jogger);
    }

In the Jogger/Create view there are no fields for JoggerId or UserId according to the generated code.
Typically it fails on the (ModelState.IsValid) portion of code where the Output shows JoggerId = 0 and UserId = null.
I have not seen this behaviour on the Contoso University tutorial on asp.net's website and I have looked at the MSDN Learn EF site as well. I can't seem to solve this problem. Your advice is appreciated.

A: After much trial and error I found a way that works to assign the Foreign Key a value.
Firstly, my relationships were setup incorrectly: UserProfile Class did not need the    public int? GolferId to represent a navigation property. Final classes looked as follows:
UserProfile
  [Key]
  [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
  public int UserId { get; set; }
  public string UserName { get; set; }

  // Navigation properties
  public virtual Jogger Jogger { get; set; }

Jogger Class
[Key]
[ForeignKey("UserId")]
public int JoggerId { get; set; }

public string Pronation {get; set;}

public virtual UserProfile UserId { get; set; }

This setup the correct relationship without needing any Fluent API code.
To assign the ForeignKey value was a little trickier and I'm sure there are MUCH better ways of doing it than this.

*

*Instead of the other scaffolding method of defining (id = 0), I used a FormCollection. You can also use the [Bind(Include = "field1, field2, field3")] to ensure that the correct fields are being posted.

*There's a long way of getting to the logged-in User's UserId which takes advantage of User.Identity.Name

*The FormCollection allows me to reference and save the other fields e.g. Pronation
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(FormCollection values)
{

    var jogger = new Jogger();
    TryUpdateModel(jogger);

    var context = new TestContext();
    var userqq = User.Identity.Name;
    var user = context.UserProfiles.SingleOrDefault(u => u.UserName == userqq);

    if (ModelState.IsValid)
    {

            jogger.JoggerId = user.UserId;
            jogger.Pronation = values["Pronation"];

            db.Joggers.Add(jogger);
            db.SaveChanges();
           return View();

    }
        ViewBag.JoggerId = new SelectList(db.UserProfiles, "UserId", "UserName", jogger.JoggerId);
        return View(jogger);

}

This wasn't pretty at all but it does work. Thanks to @Moeri for pointing me in the right direction.

A: The error is in the data base model.
Entity Framework Code First will always require configuration for one-to-one relationships. Code First can't determine which class is the dependent in these situations.
1- In your Jogger class add the property:
public virtual User User { get; set; }

2 - In your OnModelCreating method add:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
      // One to One relationship
      modelBuilder.Entity<User>()
                        .HasOptional(t => t.Jogger)
                        .WithOptionalDependent(m => m.User);
}

A: Here is your error:
public virtual UserProfile UserId { get; set; }

Entity Framework Code First works with conventions, one of them being name-based conventions. That means that if you have a property "UserId", it will look for a table "User" and configure it as a foreign key to that table.
I think it's blowing up because you gave your navigation property a name that is conventionally used for a foreign key property.
The correct way of working would be:
public virtual int? UserId { get; set; }
public virtual User User { get; set; }

If you want your property to be called "UserProfileId", you will have to use the "ForeignKey" attribute or the fluent configuration syntax to let Entity Framework know this is a foreign key:
public virtual int? UserProfileId{ get; set; }

[ForeignKey("UserProfileId")
public virtual User User { get; set; }

or with fluent syntax (you write this in the OnModelCreating method of your Context, or in a separate class that inherits from EntityTypeConfiguration):
HasRequired(j => j.User).WithMany().HasForeignKey(i => i.UserProfileId)

Edit: I've just noticed your User table is actually called UserProfile, which sort of renders the latter half of my response moot. Nevertheless I'll leave it as it is as it can be educational.


text:
Q: Posix headers for cross compiling on Windows (specifically for boost) I'm trying to cross-compile Boost on Windows to a Linux target using Clang. The compiler is invoking correctly, it seems, but I'm stuck on a missing header file:
#include <pthread.h>
Clang/LLVM doesn't seem to come with its own copies of these posix headers, what's the recommend way for obtaining/setting up these headers for cross compilation?


text:
Q: Cordova on Android; getResponseHeader("Set-Cookie") returns only the last cookie not the rest. in our Android platform in a Cordova project getResponseHeader("Set-Cookie") only returns the last cookie from the response and not all the cookies as it does in the iOS platform.
$.ajax({
type: "POST",
cache:false,
url: url,
contentType: "application/json; charset=utf-8",

data: dotJSON,
success: function( data, textStatus, req ) {
    $.mobile.loading( 'hide', {
        textVisible: false,
        theme: 'a',
        html: ""
    });

    var header = req.getAllResponseHeaders();

    //console.log(header);
    console.log(req.getResponseHeader("Set-Cookie")); // this only prints the following
   // 'Set-Cookie: DIdN=[...]; path=/'

   [...]
});

In the iOS platform console.log(req.getResponseHeader("Set-Cookie")); also prints an ASPXAUTH-cookie which we need to keep the session going with the server.
I've search both on SO, the PhoneGap Google group and the Cordova Issue Tracker and found people with the same issue as me but they are all unanswered.
Anyone got any ideas on what might go wrong on the Android-platform but not on the iOS-platform?

A: I solved this issue by sending the cookies in the response body as a string and then stored it in local storage as such:
window.localStorage.setItem("Cookies", data);
and then i set them in all my ajax-requests using
beforeSend:setHeader
function setHeader(xhr){
    xhr.setRequestHeader('Set-Cookie', window.localStorage.getItem("Cookies"));
}

Hope this will help anyone else out there with the same problem.


text:
Q: Volley library ignoring format=feed&type=rss Params I need to get rss feed using Volley library but Volley keeps ignoring my format=feed&type=rss Params.
I tried every thing but i couldn't get it work.
Here is my URL: http://almesryoon.com/%D8%AF%D9%81%D8%AA%D8%B1-%D8%A3%D8%AD%D9%88%D8%A7%D9%84-%D8%A7%D9%84%D9%88%D8%B7%D9%86?format=feed&type=rss
Note: this URL is working on Google PostMan
My SimpleXmlRequest Class:
public class SimpleXmlRequest<T> extends Request<T> {

    private static final Serializer serializer = new Persister();
    private final Class<T> clazz;
    private final Map<String, String> headers;
    private final Listener<T> listener;

    /**
     * Make HTTP request and return a parsed object from Response
     * Invokes the other constructor.
     *
     * @see SimpleXmlRequest#SimpleXmlRequest(int, String, Class, Map, Listener, ErrorListener)
     */
    public SimpleXmlRequest(int method, String url, Class<T> clazz,
                            Listener<T> listener, ErrorListener errorListener) {
        this(method, url, clazz, null, listener, errorListener);
    }

    /**
     * Make HTTP request and return a parsed object from XML Response
     *
     * @param url URL of the request to make
     * @param clazz Relevant class object
     * @param headers Map of request headers
     * @param listener
     * @param errorListener
     *
     */
    public SimpleXmlRequest(int method, String url, Class<T> clazz, Map<String, String> headers,
                            Listener<T> listener, ErrorListener errorListener) {
        super(method, url, errorListener);
        this.clazz = clazz;
        this.headers = headers;
        this.listener = listener;
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        return headers != null ? headers : super.getHeaders();
    }

    @Override
    protected void deliverResponse(T response) {
        listener.onResponse(response);
    }

    @Override
    public String getBodyContentType() {
        return "application/xml";
    }

    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response)
    {
        try {

            String data = new String(response.data, HttpHeaderParser.parseCharset(response.headers));// The problem here this data is not XML

            return Response.success(serializer.read(clazz, data),
                    HttpHeaderParser.parseCacheHeaders(response));
        }
        catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        }
        catch (Exception e) {
            return Response.error(new VolleyError(e.getMessage()));
        }
    }
}

Also i tried to make it using METHOD.POST with getParams() method
Target rss:
<?xml version="1.0" encoding="utf-8"?>
<!-- generator="Joomla! - Open Source Content Management" -->
<rss version="2.0"
    xmlns:atom="http://www.w3.org/2005/Atom">
    <channel>
        <title>Title</title>
        <description>Description</description>
        <link>http://google.com</link>
        <lastBuildDate>Thu, 31 Mar 2016 01:27:12 +0200</lastBuildDate>
        <generator>Joomla! - Open Source Content Management</generator>
        <atom:link rel="self" type="application/rss+xml" href="http://example.com/example?format=feed&type=rss"/>
        <language>ar-aa</language>
        <item>
            <title>Item1</title>
            <link>http://example.com/example1</link>
            <guid isPermaLink="true">http://example.com/example1</guid>
            <description>Description1</description>
            <author>admin</author>
            <category>Category1</category>
            <pubDate>Wed, 30 Mar 2016 18:49:37 +0200</pubDate>
        </item>
        <item>
            <title>Item2</title>
            <link>http://example.com/example2</link>
            <guid isPermaLink="true">http://example.com/example2</guid>
            <description>Description2</description>
            <author>admin</author>
            <category>Category1</category>
            <pubDate>Wed, 30 Mar 2016 18:49:37 +0200</pubDate>
        </item>
    </channel>
</rss>

I was using this code and it was working perfectly but HttpParams, BasicHttpParams, HttpConnectionParams, DefaultHttpClient, HttpGet, HttpResponse and HttpEntity are deprecated now.
My working code:
StringBuilder chaine = new StringBuilder("");

        try {

            HttpParams httpParameters = new BasicHttpParams();
            // Set the timeout in milliseconds until a connection is established.
            // The default value is zero, that means the timeout is not used.
            int timeoutConnection = AppConstants.CONNECTION_TIMEOUT_SEC * 1000;
            HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
            // Set the default socket timeout (SO_TIMEOUT)
            // in milliseconds which is the timeout for waiting for data.
            int timeoutSocket = AppConstants.SOCKET_TIMEOUT_SEC * 1000;
            HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();

            InputStream inputStream = httpEntity.getContent();

            BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));

            String line;

            while ((line = rd.readLine()) != null) {

                chaine.append(line);

            }

            rd.close();

        } catch (IOException e) {
            // writing exception to log
            e.printStackTrace();
        }

A: If you have tried encoding your URL and it didn't work, the problem is with volley . Unfortunately , I have encountered the same situation only with POST requests made with volley. They worked flawless with the HTTP implementation but returned 400 with volley.My solution at that time was to stick with the old HTTP implementation.

A: Please use the following url to get your required RSS
https://m.almesryoon.com/%d8%af%d9%81%d8%aa%d8%b1-%d8%a3%d8%ad%d9%88%d8%a7%d9%84-%d8%a7%d9%84%d9%88%d8%b7%d9%86?format=feed&type=rss&template=mobile

Here is the log:
...
D/dalvikvm: GC_FOR_ALLOC freed 27K, 12% free 6432K/7303K, paused 20ms, total 20ms
I/onResponse: <?xml version="1.0" encoding="utf-8"?>
              <!-- generator="Joomla! - Open Source Content Management" -->
              <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
                <channel>
                    <title>دفتر أحوال الوطن - المصريون</title>
                    <description>المصريون صحيفة يومية مستقلة تنشر آخر وأهم أخبار مصر والوطن العربى والعالم</description>
                    <link>https://m.almesryoon.com/دفتر-أحوال-الوطن</link>
                    <lastBuildDate>Thu, 23 Feb 2017 04:36:51 +0200</lastBuildDate>
                    <generator>Joomla! - Open Source Content Management</generator>
                    <atom:link rel="self" type="application/rss+xml" href="https://m.almesryoon.com/دفتر-أحوال-الوطن?format=feed&type=rss&template=mobile"/>
                    <language>ar-aa</language>
                    <item>
                    ...

After testing some sample code with your server url, I have found that it got 301 response. From your first url, the second url will be (https)
https://almesryoon.com/%D8%AF%D9%81%D8%AA%D8%B1-%D8%A3%D8%AD%D9%88%D8%A7%D9%84-%D8%A7%D9%84%D9%88%D8%B7%D9%86?format=feed&type=rss

The 3rd url will be:
http://m.almesryoon.com/%d8%af%d9%81%d8%aa%d8%b1-%d8%a3%d8%ad%d9%88%d8%a7%d9%84-%d8%a7%d9%84%d9%88%d8%b7%d9%86?template=mobile

And the final url will be (https):
https://m.almesryoon.com/%d8%af%d9%81%d8%aa%d8%b1-%d8%a3%d8%ad%d9%88%d8%a7%d9%84-%d8%a7%d9%84%d9%88%d8%b7%d9%86?template=mobile

With this final url and the sample code below, you will get 200 response code. I think you can try your code with the final url I mentioned above.
RequestQueue queue = Volley.newRequestQueue(this);
String url = "https://m.almesryoon.com/%d8%af%d9%81%d8%aa%d8%b1-%d8%a3%d8%ad%d9%88%d8%a7%d9%84-%d8%a7%d9%84%d9%88%d8%b7%d9%86?template=mobile";
StringRequest request = new StringRequest(url, new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        Log.i("onResponse", response);
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Log.e("onErrorResponse", error.toString());
    }
});

queue.add(request);

About handling 301 response in Volley, I have not tried, however, you can read the following question for more information
Android volley to handle redirect


text:
Q: How to write a object into a file in java? I want to convert the following c code to java. I did that somehow but, after writing to the files I compared both of the content in beyond compare and there is a lot of different.
Please suggest me how to write the same as c in java
C code:
const struct bin_header bin_header = {
 .magic = "VVN",
 .header_size = 0x10,
 .version = (0x01 << 24) | 0x010000,
 .core = (0x02 << 24) | 0x000501,
};
FILE* ofp = fopen(outfilename, "wb");
fwrite(&bin_header, sizeof(bin_header), 1, ofp)

Java code:
/* class because there is no struct in java */
class bin_header implements Serializable      {
    String magic;
    long header_size;
    long version;
    long core;

    bin_header () {
        magic = "VVN";
        header_size = 0x10;
        version = (0x01 << 24) | 0x010000;
        core = (0x02 << 24) | 0x000501;
      }

  };

/* function  for writing */
writeByVVN() {
    bin_header bin_header = new bin_header();
    Fout = new FileOutputStream(outFile);
    ObjectOutputStream oos = new ObjectOutputStream(Fout);
    oos.writeObject(bin_header);
}

A: I found a way to write the object members to a file with endianness also.
 I used ByteBuffer for it
   int write(FileOutputStream fout) throws IOException {
            int bytes;
            FileChannel fChan = fout.getChannel();
        ByteBuffer str = ByteBuffer.wrap(magic.getBytes());
        bytes = fChan.write(str);

        ByteBuffer buf = ByteBuffer.allocate(4);
        buf.order(ByteOrder.LITTLE_ENDIAN);

        buf.putInt(header_size);
        buf.rewind();
        bytes  += fChan.write(buf);
        buf.clear();
        ...

        return bytes;
   }

int read(FileInputStream fIn)  throws IOException {
    int bytes = 0;
    FileChannel fChan = fIn.getChannel();

    ByteBuffer buf = ByteBuffer.allocate(4);
    buf.order(ByteOrder.LITTLE_ENDIAN);

    bytes = fChan.read(buf);
    buf.rewind();
    magic = new String(buf.array());
    buf.clear();

    ...

    return bytes;
}


text:
Q: How handle multiple completely dynamic routes in angular? I have multiple routes which haven't any static parameter that I can add a corresponding component for that route, so I can easily navigate. My routes config is like:
app-routing.module.ts:

const routes = {
  {path: '', component: MainPageComponent},
  {path: ':category', component: ListPageComponent},
  {path: ':productInfo', component: ProductComponent},
  {path: '404', component: PageNotFoundComponent},
  {path: '**', redirectTo: '404'}
};

At the beginning, I decided to use a resolver to first send the requested url to api and find out if the url is ok as being a category and if it wasn't I made another request to api to find out if it was OK as being a product. But I think it isn't efficient until I pass the info that the api sent to me, to the component, so the component wouldn't need to make another request and that was why I choose to use resolver.
I also wanted to handle incorrect routes, so if those 2 requests to api were respond to incorrect, I wanted to navigate the user to 404 page. But I couldn't handle to connect the corresponding component for a route, in the resolver.
Any advice or solution how to do this?
UPDATE:
@Abhijeet Raj, thanks for your answer. Currently we changed the way we defien our routes and it ends up sth like this:
{path: ':category/:slug', component: ProductComponent}, {path: ':category/:brand1/:brand2/:brand3/...', component: ListPageComponent}
In this situation, when I have: '':category/brand1" it would go to the ProductComponent, instead of ListPageComponent, how I can resolve this issue?
But when I have sth like: ':category/:brand1/:brand2', because of having more than two param in url, I can use a urlMatcher.

A: As far as I understood your problem,
:category and :productInfo are no different here actually, both will open same component.
If you pass any dynamic category or product info in the route it will only go to the first route listed in the routes array i.e. :category. You will need to differentiate your routes in someway like :-
category/:categoryId

and
product/:productId

So both can refer to different components.


text:
Q: Method to detect intersection between a rectangle and a polygon? What is the best method to detect whether the red rectangle overlaps the black polygon? Please refer to this image:

A: There are four cases.

*

*Rect is outside of Poly

*Rect intersects Poly

*Rect is inside of Poly

*Poly is inside of Rect

First: check an arbitrary point in your Rect against the Poly (see Point in Polygon). If it's inside you are done, because it's either case 3 or 2.
If it's outside case 3 is ruled out.
Second: check an arbitrary point of your Poly against the Rect to validate/rule out case 4.
Third: check the lines of your Rect against the Poly for intersection to validate/rule out case 2.
This should also work for Polygon vs. Polygon (convex and concave) but this way it's more readable.

A: If your polygon is not convex, you can use tessellation to subdivide it into convex subparts. Since you are looking for methods to detect a possible collision, I think you could have a look at the GJK algorithm too. Even if you do not need something that powerful (it provides information on the minimum distance between two convex shapes and the associated witness points), it could prove to be useful if you decide to handle more different convex shapes.
Christer Ericson made a nice Powerpoint presentation if you want to know more about this algorithm. You could also take a look at his book, Real-Time Collision Detection, which is both complete and accessible for anyone discovering collision detection algorithms.

A: If you know for a fact that the red rectangle is always axis-aligned and that the black region consists of several axis-aligned rectangles (I'm not sure if this is just a coincidence or if it's inherent to the problem), then you can use the rectangle-on-rectangle intersection algorithm to very efficiently compute whether the two shapes overlap and, if so, where they overlap.

A: If you use axis-aligned rectangles and polygons consist of rectangles only, templatetypedef's answer is what you need.
If you use arbitrary polygons, it's a much more complex problem.
First, you need to subdivide polygons into convex parts, then perform collision detection using, for example, the SAT algorithm

A: Simply to find whether there is an intersection, I think you may be able to combine two algorithms.
1) The ray casting algorithm. Using the vertices of each polygon, determine if one of the vertices is in the other. Assuming you aren't worried about the actual intersection region, but just the existence of it.  http://en.wikipedia.org/wiki/Point_in_polygon
2) Line intersection. If step 1 produces nothing, check line intersection.
I'm not certain this is 100% correct or optimal.
If you actually need to determine the region of the intersection, that is more complex, see previous SO answer:
A simple algorithm for polygon intersection


text:
Q: Can friends order from my Nooklings' catalog? I've upgraded to T&T Mart, so the Nooklings' store now has a catalog where I can order many of the items I've previously found or purchased.
If my friends visit my town and use my catalog, will they see their items or my items? Can my friends visit to order items I have (but they don't) then have them delivered to their town?

A: No. Upon entering the T&T Mart, the visiting player is informed that the kiosk is for local residents only.  They cannot access it at all.


text:
Q: OpenCV / Python Bundle adjustment I have an application where I am attempting structure from motion for multiple views from the same camera using OpenCV in Python. (OpenCV isn't a hard requirement but Python is right now).  Example: I have 16 camera images to work with with small motions between each frame.  In the frames (200x200) I can track ~50 features and I'd like to estimate camera pose and 3D point locations for the features as accurately as possible.
I'm at the point where I'd like to use a stream of frames (from video) to refine the estimates of camera pose and 3D point positions since estimating pose and triangulating 3D points from two frames produces a lot of noise.  I believe Bundle Adjustment is the next obvious direction to go in, but I'm not finding any obvious Python implementation of bundle adjustment to use.  Many options (such as LevMarqSparse::bundleAdjust()) appear to be only partially completed or not fully adopted.
What is a good place to start?  I guess I'm looking for a relatively simple Python bundle adjustment to prototype with and see if that is a direction I want to invest more time into.

A: Assuming you have a calibrated camera and an initial estimate of intrinsics and extrinsic parameters, you could at first perform a simple bundle adjustment directly in Python.
For instance, you could use stacks of three images, compute 3D points from the feature points via the homogeneous triangulation method. A simple bundle adjustment as a first prototype can be build for instance via scipy.least_squares and the Trusted Region Reflective non-linear optimization technique. Check out this tutorial.
Afterwards you can decide, whether you want to implement or use a Levenberg-Marquardt optimization technique which is able to handle sparse Jacobians or even determine the Jacobian analytically to hypothetically increase the convergence if desired.
So far, I think there is no adequate library in Python which provides a potent and high performant implementation of bundle adjustment.


text:
Q: How to secure PHP Source Code? is there any way to secure your whole code ? or some important files. which is not changeable to other even it is deployed to other servers like client's server.
or we can create any DLL file(which is not changeable) which can be run by Apache server and authenticate the requirements.


text:
Q: Overloading of insertion operator Versus using setter function In this code I am overloading >> operator to input data members of the object of the class.It can also be done using getter functions. What are the advantages of overloading >> operator compared to using setter function?
#include<bits/stdc++.h>
using namespace std;

class point {
int x ,y ,z;
public:
void show(){
cout << x << y << z;
}

}

friend istream& operator >> (istream & i,point &);
};

istream& operator >> (istream & i,point &p){
i >> p.x >> p.y >> p.z;
return i;
}

int main(){
point p1,p2,p3;
cin >> p1 >> p2;//Cascading using friend function
return 0;
}

A: It's not an either/or situation. Setters/Getters are a fairly useful global design feature, but you don't have to scrap them to introduce the <</>> notation.
The <</>> notation is (ime) mostly used with things that can be seen as streams - in particular, the standard library streams, but also with custom classes that represent some sort of flow of data.
Advantages of <</>>
When the objects you're using are likely to be used in this sort of context (streams of data), then overriding those operators can make a huge difference to the readability and ease of understanding of your code compared to normal getters/setters.
Also, as you show in your code, the "cascading" functionality can be a really concise way of expressing what's happening.
Advantages of get/set
Getters/Setters are (again ime) far more common, so it's more likely someone else reading/using your code will immediately understand the point of it.
They also allow finer-grained control over what is being read/written. Maybe you don't want to write the entire object, but just a single member of it.
Conclusion
Both have their uses, I'd say it's mostly contextual as to which you use. I rarely override those operators but very frequently use get/set methods - but then the code I usually write doesn't involve much input/output.


text:
Q: Using type vector>::iterator& in function call I have written the following piece of test code. The functionality of this code segment is to find the longest continuous sequence from a given set of digits. I am using a recursive lambda (std::function) implementation in the part of the processing logic related to sorting the vector<pair<int,int>>.
#include <iostream>
#include <vector>
#include <functional>
#include <utility>
#include <string>
using std::vector;
using std::function;
using std::swap;
using std::pair;
using std::make_pair;
using std::string;
using std::cout;
using std::endl;

int main (void){

auto func_obj1 = [&](const string& r, int buffer)->int{

  function<void(vector<pair<int,int>>::iterator&, vector<pair<int,int>>::iterator&)> func_obj3 = [&](auto begin, auto end){
    if(begin == end){
      return;
    }
    auto tempb = begin;
    auto tempe = end - 1;
    while(tempb != end){
      if((*tempb).second > (*tempe).second){
        swap(*tempb, *tempe);
      }
    }
    end = tempe;

    func_obj3(begin, end);
  };
  auto func_obj2 = [&](vector<pair<int,int>>& r)->int{
    func_obj3(r.begin(), r.end());

    auto iter = r.begin();
    auto count = 0;
    auto max_count = 0;

    while(iter != r.end()){
      auto temp = iter + 1;
      if((*iter).second + 1 == (*temp).second){
        ++count;
        if(count > max_count){
          max_count = count;
        }
      }
      else{
        count = 0;
      }
      ++iter;
    }
    return max_count;
  };

  vector<pair<int,int>> v;
  auto sws = ' ';
  auto iter = r.begin();
  auto count = 0;

  while(iter != r.end()){
    if(*iter == sws){
      continue;
    }
    else{
      v.push_back(make_pair(count, *iter));
      ++count;
    }
    ++iter;
  }
  auto result = func_obj2(v);

  return result;
};

string s = "1 9 2 7 3 8 4 ";

auto result = func_obj1(s, s.size());

cout << result << endl;

  return 0;
}

The code fails to compile:
g++ -ggdb -std=c++14 -Wall code.cpp

code.cpp:35:5: error: no matching function for call to object of type 'function<void (vector<pair<int, int> >::iterator &, vector<pair<int, int> >::iterator &)>' (aka 'function<void (__wrap_iter<std::__1::pair<int, int> *> &, __wrap_iter<std::__1::pair<int, int> *> &)>')
    func_obj3(r.begin(), r.end());
    ^~~~~~~~~
/Library/Developer/CommandLineTools/usr/include/c++/v1/functional:1677:9: note: candidate function not viable: expects an l-value for 1st argument
    _Rp operator()(_ArgTypes...) const;
        ^
1 error generated.

Can someone advise about how to rectify this?
TIA
Vinod

A: Guess, the error was related to the second line in the compiler output:
code.cpp:39:5: error: no matching function for call to object of type 'function<void (vector<pair<int, int> >::iterator &, vector<pair<int, int> >::iterator &)>' (aka 'function<void (__wrap_iter<std::__1::pair<int, int> *> &, __wrap_iter<std::__1::pair<int, int> *> &)>')
    func_obj3(r.begin(), r.end());
    ^~~~~~~~~
/Library/Developer/CommandLineTools/usr/include/c++/v1/functional:1677:9: note: **candidate function not viable: expects an l-value for 1st argument**
    _Rp operator()(_ArgTypes...) const;
        ^
1 error generated.

Changed the invocation arguments to l-values to get rid of the error.

A: based on the error message code.cpp:35:5: error: no matching function for call to object of type 'function<void (vector<pair<int, int> >::iterator &, vector<pair<int, int> >::iterator &)>' (aka 'function<void (__wrap_iter<std::__1::pair<int, int> *> &, __wrap_iter<std::__1::pair<int, int> *> &)>')
You could try to change the lambda func_obj2 to:
auto func_obj2 = [&](vector<pair<int,int>>& r)->int{
    using vpitor = std::vector<pair<int,int>>::iterator;
    vpitor it_begin = r.begin();
    vpitor it_end = r.end();
    func_obj3(it_begin, it_end);
...
}

A: function<void(vector<pair<int,int>>::iterator&, vector<pair<int,int>>::iterator&)>
    func_obj3 = /*...*/;

should be
function<void(vector<pair<int,int>>::iterator, vector<pair<int,int>>::iterator&)>
    func_obj3 = /*...*/;

Or even should simply be:
auto func_obj3 = [&](auto begin, auto end){/*...*/};

Issue is that in func_obj3(r.begin(), r.end()), r.begin() and  r.end() are both rvalues and cannot bind to non-const lvalue references (vector<pair<int,int>>::iterator&) that you impose in function signature.


text:
Q: Setting status code of response has no effect on web api core AspNetCore 3.1.3
I'm trying to write a custom error result to return them consistently to the users whenever necessary.
I started by inheriting from StatusCodeResult and overriding the ExecuteResult method, like this:
public override void ExecuteResult(ActionContext context)
{
    base.ExecuteResult(context);
    var bytes = Encoding.UTF8.GetBytes(ErrorMessage);
    context.HttpContext.Response.Body.Write(bytes, 0, bytes.Length);
}

Then I realized that the response body I was writing was completely ignored, and the response was
status: 422
title: "Unprocessable Entity"
traceId: "|5c53f94f-4826199e14151b80."
type: "https://tools.ietf.org/html/rfc4918#section-11.2"

Tried everything I could think of to change the body, but the framework just overwrites this automagically and I couldn't find information on where or how.
Then I proceeded to extend IClientErrorActionResult, imeplementing the interface like this:
public async Task ExecuteResultAsync(ActionContext context)
{
    var bytes = Encoding.UTF8.GetBytes(ErrorMessage);
    context.HttpContext.Response.StatusCode = 422;
    await context.HttpContext.Response.Body.WriteAsync(bytes, 0, bytes.Length);
    await context.HttpContext.Response.CompleteAsync();
}

This time the body of the response matched whatever I wrote, but the StatusCode was always automagically changed to 200, even though I'm setting it to 422 before writing the response.
My question is: how can I change the body returned from StatusCodeResult or make the framework respect the StatusCode I'm setting inside my 'ExecuteResultAsync' method from IActionResult.
Also, if anyone could point me to any kind of documentation of what is going on here, where these overwrites are happening and why, I would appreciate it.


text:
Q: How can I manipulate docx at runtime My task is to take docx file, manipulate it, fill placeholders and return it to a user. I have C# project that consists of several webservices that makes it work.
By now I have done it following way:

*

*Take docx file

*Open it via OpenXML SDK

*Apply some algorithms

*Fill placeholders

*Return

All of this is happening in C# code. Now I have an idea to move all alghortims to database. The reason is when something change there will be no need to deploy application to webserver. I would like to take docx template, take some script from database and apply to it.
Do you know how can I accomplish this? One way is to use XSLT but I don't like this idea.

A: There is SC-Script and IronPython which can be used to accomplish the "runtime" part. Both are well integrated with .net environment.


text:
Q: Capture active windows and save with title as filename I would like to save screenshots of an app, and looking for a tool which automatically saves screenshots.
Picasa 3 saves the screenshots when running, and it gives the filename according to the title of captured window, but it saves to bmp, which are huge, and if I make several schreenshots, it drops, if working on the saving. So if I am speedy, half of my pictures are dropped.
So do you know a schreenshot saving tool which gives the filename according to the captured windows's title?

A: ZScreen does that.
In the "File Naming Configurator" (Menu "Configure" -> "File Naming...") you can use various variables to construct the resulting file names. Among them "Title of Active Window".
It takes a couple of minutes to configure all the various options but once that's done it gets out of your way and lets you do your job.


text:
Q: Typescript: Syntax error. Unexpected token I am trying to launch .ts file as console app.
After converting .ts files to .js (through tsc) there was no error, but I can't launch .ts file with ts-node because of issue:

"SyntaxError: Unexpected token ..."

My tsconfig.json file is
{
"compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "strict": true,
    "esModuleInterpop": rue
    }
}

Typescript code is
constructor(... pieces : IPiece[]){
super();
for (let i = 0; i < pieces.length; i++) {
    this.add(pieces[i]);
}}

So I guess that tsc and ts-node compile .ts files differently. Any ideas? Thanks.

A: your tsconfig.json file code something spell mistake,
{
"compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "strict": true,
    "esModuleInterpop": rue // here change to true.
    }
}

Edit:-
... pieces : IPiece[]

remove and add private or public type to this one.
constructor(public pieces : IPiece[]){ } //use public or private

let try this once and let me know.


text:
Q: OneLogin php saml - Issues with SAML response I have integrated OneLogin using php-saml to connect to our idp service. In our staging environment, everything works fine with the setup we are using.
I am running into an issue using those same files on our production environment however.
The problem is that the SAML response isn't correctly being validated with the saml-schema-protocol-2.0.xsd schema and is throwing errors about it.
$settingsInfo = array(
    'strict' => true,
    'debug' => false,
    'sp' => array(
        'entityId' => 'website',
        'assertionConsumerService' => array(
            'url' => "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'],
            'binding' => 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST',
        ) ,
        'NameIDFormat' => 'urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified',
        'x509cert' => file_get_contents('tool-sso.pem', FILE_USE_INCLUDE_PATH) ,
        'privateKey' => file_get_contents('tool-sso.key', FILE_USE_INCLUDE_PATH) ,
    ) ,
    'idp' => array(
        'entityId' => 'https://sso.example.com',
        'singleSignOnService' => array(
            'url' => 'https://sso.example.com/idp/SSO.saml2',
            'binding' => 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect',
        ) ,
        'singleLogoutService' => array(
            'url' => 'https://sso.example.com/idp/SSO.saml2',
            'binding' => 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect',
        ) ,
        'x509cert' => file_get_contents('sso.pem', FILE_USE_INCLUDE_PATH)
    ) ,
    'compress' => array(
        'requests' => true,
        'responses' => true
    ) ,
    'security' => array(
        'authnRequestsSigned' => true,
        'signatureAlgorithm' => 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256',
    )
);

However, if I add the following line to the security settings, it works just fine:
'wantXMLValidation' => false
This makes me think that the SAML response we are getting back from idp is somehow not in the expected format as defined by the xsd.
Any thoughts as to what might cause the wantXMLValidation=true to fail? Is it due to missing/additional/incorrect data in the SAML response or could the issue be with how we are sending data?
I am trying to rule out idp as being the issue here but in order to keep our staging and production environments in sync, I want to get that wantXMLValidation flag set back to true.
I have tried running the response against the Validate XML with the XSD schema tool and it comes back as valid xml.
The specific error I am getting when XML Validation is on is as follows:
    Warning: DOMDocument::schemaValidate(): Invalid Schema in \\fileshare\root\resources\Classes\OneLogin\src\Saml2\Utils.php on line 135 failed to load external entity "/fileshare/root/resources/Classes/OneLogin/src/Saml2/schemas/xmldsig-core-schema.xsd" Element '{http://www.w3.org/2001/XMLSchema}import': Failed to locate a schema at location '/fileshare/root/resources/Classes/OneLogin/src/Saml2/schemas/xmldsig-core-schema.xsd'. Skipping the import. failed to load external entity "/fileshare/root/resources/Classes/OneLogin/src/Saml2/schemas/xenc-schema.xsd" Element '{http://www.w3.org/2001/XMLSchema}import': Failed to locate a schema at location '/fileshare/root/resources/Classes/OneLogin/src/Saml2/schemas/xenc-schema.xsd'. Skipping the import. Element '{http://www.w3.org/2001/XMLSchema}element', attribute 'ref': The QName value '{http://www.w3.org/2001/04/xmlenc#}EncryptedData' does not resolve to a(n) element declaration. Element '{http://www.w3.org/2001/XMLSchema}element', attribute 'ref': The QName value '{http://www.w3.org/2001/04/xmlenc#}EncryptedKey' does not resolve to a(n) element declaration. Invalid SAML Response. Not match the saml-schema-protocol-2.0.xsd
invalid_response

OneLogin\Saml2\Auth Object
(
    [_settings:OneLogin\Saml2\Auth:private] => OneLogin\Saml2\Settings Object

Environment:
My setup is a load balancer with 2 windows servers and a single file-share. User connects to LB, web-sever running PHP calls the onelogin PHP files from the file-share (not on the same server as the webservers). The only reason I bring this up is because I am wondering if there is something to do with how the schemaLocations are trying to read the .xsd files.
Update:
I may have figured this out, just not a better way to fix it.
There is a function in the OneLogin file Utils.php called validateXML which loads the schema file that it compares the SAML response with. After some trial an error, I moved the schema files directly to the web server and not the file-share. After moving them and hardcoding the location of these schema files, the issue is resolved.
public static function validateXML($xml, $schema, $debug = false)
    {
        assert(is_string($xml) || $xml instanceof DOMDocument);
        assert(is_string($schema));

        libxml_clear_errors();
        libxml_use_internal_errors(true);

        if ($xml instanceof DOMDocument) {
            $dom = $xml;
        } else {
            $dom = new DOMDocument;
            $dom = self::loadXML($dom, $xml);
            if (!$dom) {
                return 'unloaded_xml';
            }
        }

        //$schemaFile = __DIR__ . '/schemas/' . $schema;
        $schemaFile = 'file://C:\inetpub\wwwroot\config\schemas\\'. $schema;

Prior to this change, the schema file would have been looking at the fileshare for this xsd.
I am not sure if this is a path issue with libXML not being able to read for a directory like this or whether its permissions etc.
I would prefer to have the schemas in the same folder as OneLogin and not have to refer to them from the web-server itself.
Anything stand out with my paths that I might be missing here?


text:
Q: Android's InputMethodService - how to get unicode characters? I'm trying to make a keyboard...
int code = 29; // Key code constant: 'A' key. Constant Value: 29 (0x0000001d)
KeyEvent k = new KeyEvent(KeyEvent.ACTION_UP, code);

InputConnection ic = getCurrentInputConnection();
ic.sendKeyEvent(k);

This code nicely send letter "A" to the application, as it is associated with the code "29", as from here http://developer.android.com/reference/android/view/KeyEvent.html
But what should I do, if I want to use unicode characters, such as in here
http://en.wikipedia.org/wiki/List_of_Unicode_characters

A: If you are building a keyboard app, and have keyboard layout in xml, you can look at suggestion provided by user Laurent' in another thread:
<Key android:codes="946" android:keyLabel="\u03B2"/>
<Key android:codes="946" android:keyLabel="&946;"/>
<Key android:codes="946" android:keyLabel="β"/>
<!-- Warning, you should use UTF-8 encoding for your project files if you use the third solution -->
<!-- all produce the same key with greek β character (unicode \u03B2, decimal 946) -->

A: Please check the softkeyboard  sample code.
If you are developing a new keyboard(for example for any other language), change the android:code attribute value to the unicode value which you want the keyboard to output.
This works fine and I think you can test it in the same softkeyboard project.


text: Q: How can I modify the contents of an XML file in JavaScript? Suppose if I have an XML file in a File object (https://developer.mozilla.org/en-US/docs/Web/API/File) and I want to read and modify the contents in the XML tree and update the File object with the new contents then how would I go about doing this?


text:
Q: How can I list every resource files of a directory pack URI? I have many XML files with "Build Action" set as "Resource". I can access them from code using the well known pack URI scheme, or just a relative URI (which is actually a valid pack URI, as stated by Microsoft in the pack URI msdn page, so everything is a pack uri :p), like this :
Uri uri1 = new Uri("pack://application:,,,/someFolder/myResource1.xml");
Uri uri2 = new Uri("someFolder/myResource2.xml");

Actually, I need to get a stream from each xml file. What I can do is the following :
Uri uri1 = new Uri("pack://application:,,,/someFolder/myResource1.xml");
var stream1 = App.GetResourceStream(uri1).Stream; // works fine

It works fine and I get my streams. Now here are my questions :
What if I do not know the names of my resources ? (only the path to "someFolder")
How can I list them ?
I cannot use Directory.GetFiles since resources are embedded into the assembly. A possible solution is to set the build action of my resources as "Embedded Resources" and then use the assembly.GetManifestResourceNames() function, but I'm stubborn and do not want to change this build action :p
Thanks !
EDIT : I came to something like this :
    /// <summary>
    /// Returns a dictionary of the assembly resources (not embedded).
    /// </summary>
    /// <param name="filter">A regex filter for the resource paths.</param>
    public static IDictionary<string, object> GetResources(string filter) {
        var asm = Assembly.GetEntryAssembly();
        string resName = asm.GetName().Name + ".g.resources";
        Stream stream = asm.GetManifestResourceStream(resName);
        ResourceReader reader = new ResourceReader(stream);

        IDictionary<string, object> ret = new Dictionary<string, object>();
        foreach (DictionaryEntry res in reader) {
            string path = (string)res.Key;
            if (Regex.IsMatch(path, filter))
                ret.Add(path, res.Value);
        }
        return ret;
    }


text:
Q: Ubuntu Firefox homepage temporarily showing Arabic I've noticed this evening that the default Ubuntu Firefox homepage on Ubuntu 12.04 momentarily displayed Arabic in the titlebar and for the links. This first happened 15 mins ago then I rebooted and tried again - still Arabic.
Just now I've tried one more time and it's now gone back to English.
No other application on my system (e.g. Chrome or the console) is displaying any Arabic and I've double checked my localisation settings and it's still English UK.
Also when I visited any other page on Firefox (e.g the normal Google search page, http://www.google.co.uk) the normal English page showed, not an Arabic version.
Any ideas on this one? Guessing it might have been a problem server side as it was the server-generated content showing Arabic - nothing client-side - as it seems to have sorted itself out just now... but just thought I'd check.
Have deleted all my cookies just in case it was an attempted XSS attack or something like that - but I haven't been doing anything silly so I'd suspect not.
It's 12.04, more or less up-to-date (just updated 5 packages now from last week, so now completely up-to-date), and localisation is English UK.
Thanks,
Nick


text:
Q: How to configure OS to re-assemble TCP segments I have an application that is reading in TCP data from a socket.  The sending device is sending out a full 1400 bytes of data to the server's socket on the other end.  Somewhere along the way, the packet is getting segmented/fragmented into a 1024 byte segment and a 376 byte segment.  In order to receive the data correctly on my application side, I'm having to read the socket twice and assemble the packet at the application level, which can have issues with a lot of traffic.
From everything I've read, the re-assembly of TCP segments is handled on the IP Layer.  I am running Windows Server 2012 and my application is utilizing Winsock.  Is there a way to configure the OS to re-assemble these packets as they are received on the port on this layer?

A: TCP is a streaming protocol and not a message protocol. The TCP stack in the OS ensures that data gets forwarded to the application in the correct order and that no data loss and no data duplication is done. It does not care about keeping any packet boundaries since as I said TCP is a stream protocol. Also, the sender is free to split a single write into multiple packets or combine multiple writes to a single packet. It will do splitting to adapt the packet size to the MTU/PMTU in order to avoid packet fragmentation during delivery and it does combining to reduce the overhead of delivery.
Thus the application should never rely on implicit message boundaries due to how the sending application has written the data but instead explicit (application level) message boundaries have to be used.

Is there a way to configure the OS to re-assemble these packets as they are received on the port on this layer?

No, you have to deal with it properly in your application.


text:
Q: python class attributes as instance constructor default parameters I would like to use class attributes as default parameters for instance constructor, and it seems python does not support it. Could someone explain why or correct the code below so that it can work?
OK but not explicit enough from my point of view
class B:
    class_size = 4
    def __init__(self):
        self.size = B.class_size

What I would like (does not work)
class A:
    class_size = 4
    def __init__(self,size = A.a_size):
        self.size = size

Using the above declaration python complains:
def __init__(self,size = A.a_size): NameError: name 'A' is not defined

A: A is not a name while the class namespace is being built. Just un-qualify the name (A.class_size -> class_size):
class A:
    class_size = 4

    def __init__(self, size=class_size):
        self.size = size

Caveat
The above does not take inheritance into account, though, should you want to override the default in a subclass. For that you're going to need to just manually look up the default value in the constructor:
class A:
    default_size = 4

    def __init__(self, size=None):
        if size is None:
            size = self.default_size
        self.size = size

class B(A):
    default_size = 15

print(A().size)
print(B().size)
print(B("yes").size)

outputs
4
15
yes

If None would otherwise be a valid value for your argument, you may opt for a sentinel value instead:
NOTSET = object()
# ...
def __init__(self, size=NOTSET):
    if size is NOTSET:
        # ...


text:
Q: How to call thumbnail by aqua resizer in best practice. Specify image dimensions's notify from GTmetrix I am using Aqua resizer to resize thumbnail on my loop. More flexible than using thumbnail from WordPress. The problem is, image result by Aqua Resizer's has no width and height pixel. The are missing width and/or height attributes.
It's decrease the load speed as shown by GTmetrix.
Here my code to call the image on the loop:
 <?php $thumb = get_post_thumbnail_id();
    $img_url = wp_get_attachment_url( $thumb,'full' );
    $image = aq_resize( $img_url, 150, 200, true, true, true );
 ?>
 <img src="<?php if($image) { echo esc_url($image);
 } else {
 echo catch_that_image();} ?>" alt="<?php  echo get_bloginfo('name'); ?>"/>

Would really appreciate your help.
Thank you.

A: So what's wrong with adding in the attributes as Mark is saying?
<?php $thumb = get_post_thumbnail_id();
   $img_url = wp_get_attachment_url( $thumb,'full' );
   $image = aq_resize( $img_url, 150, 200, true, true, true );
?>
<img src="<?php if($image) { echo esc_url($image);
} else {
echo catch_that_image();} ?>" width="150" height="200" alt="<?php  echo get_bloginfo('name'); ?>"/>


text:
Q: At what conditions a matrix can be transformed in a phase-variable form Given a matrix $A$:
$$
A=
\begin{bmatrix}
-5 & 1 & 0\\ 0 &-2 &1 \\ 0 & 0 & -1
\end{bmatrix}
$$
At which conditions one can transform $A$ in phase-variable form shown below:
$$
P=
\begin{bmatrix}
0 & 1 & 0\\ 0 &0 &1 \\ a_0 & a_1 & a_2
\end{bmatrix}
$$
where $a_0,a_1,a_2$ are constant determined to carry out the transformation.

A: Assuming you want to know if there is an invertible matrix $U$ such that
$UAU^{-1}=P$, computing characteristic polynomials shows that $(X+5)(X+2)(X+1)=X^3+8X^2+17X+10=X^3-a_2X-a_1X-a_0$, hence if $U$ exists, then $a_0=-10,a_1=-17,a_2=-8$.
Then, both $A$ and $P$ have the same characteristic polynomial with simple roots $-5,-2,-1$, so they are both diagonalisable, and similar to $D=\pmatrix{-5 & 0 & 0 \cr 0 & -2 &0 \cr 0 & 0 & -1 }$. Therefore, one can compute using standard methods two invertible matrices $Q,R$ such that $Q^{-1}AQ=D=R^{-1}P R$. Setting $U=RQ^{-1}$ gives $UAU^{-1}=P$.


text:
Q: Appending records to GridView If I have 'see more' button in the footer of grid view. when I click on it , I need to append more records from DB like 'Face Book'. I need to do that without  make full post back on grid.
Is there way to do that using J Query, Jason, or any thing else

A: As @Aristos said, you won't be able to append the rows using a GridView, as it's bound on the server side. You could, however, create a web service which returns pages of data. These could be appended to a <ul> which you've created with a repeater:
[WebMethod]
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public string Format(int offset, int limit) {
    //  return data from your database here

Then from jQuery,
var currentPage = 0;
var numPerPage = 30;
$.ajax({
    url: '/YourService.asmx/GetData',
    data: JSON.stringify({ 'offset': (numPerPage * ++currentPage), 'limit': numPerPage}),
    type: 'POST',
    dataType: 'json',
    contentType: 'application/json; charset=utf-8',
    success: function(response){
        // response.d contains your formatted results. If you have a <ul>, you could append them simply by doing:
        $.each(response.d, function() {
            $('<li/>').html(this).appendTo('#yourList');
        });
    });
});


text:
Q: VaultSharp: "permission denied" when trying to list secrets I keep trying to simply list the secrets in my KeyValue Vault via API and I'm getting "permission denied" using AppRole auth.  Here's what I have so far.
Caller
private async Task RetrieveSecrets()
{
    // Fails here, though it's the actual service method that fails (see below)
    List<string> secrets = (await _vaultService.GetSecretsList()).ToList();
    AvailableSecrets.Clear();
    foreach (string secret in secrets)
    {
        AvailableSecrets.Add(secret);
    }
}

VaultService
internal class VaultService : IVaultService
{
    private IVaultClient _client;

    public VaultService(IOptions<ApplicationSettings> applicationSettings)
    {
        CreateClient(applicationSettings.Value);
    }

    public async Task<IEnumerable<string>> GetSecretsList()
    {
        Secret<ListInfo> secret = await _client.V1.Secrets.KeyValue.V2.ReadSecretPathsAsync("", "secret");
        ListInfo secrets = secret.Data;
        return secrets.Keys;
    }

    private void CreateClient(ApplicationSettings settings, bool forceRecreate = false)
    {
        if (_client == null || forceRecreate)
        {
            // Role authorization
            IAuthMethodInfo authMethod = new AppRoleAuthMethodInfo(settings.VaultRoleId, settings.VaultSecretId);
            VaultClientSettings vaultClientsettings = new VaultClientSettings(settings.VaultUrl, authMethod);

            _client = new VaultClient(vaultClientsettings);
        }
    }
}

I've verified that keys do exist via the vault kv list secret/ command.  Output:
λ vault kv list secret/
Keys
----
creds

I've also double-checked the policy:
λ vault policy read my-policy
# Dev servers have version 2 of KV secrets engine mounted by default, so will
# need these paths to grant permissions:
path "secret/data/*" {
  capabilities = ["create", "update","list"]
}

path "secret/data/foo" {
  capabilities = ["read","list"]
}

Finally, I verified the RoleId and SecretId (and that the right one is getting passed in) using Postman and the following http calls:
Role: http://127.0.0.1:8200/v1/auth/approle/role/my-role/role-id
Secret: http://127.0.0.1:8200/v1/auth/approle/role/my-role/secret-id
I've been poking all over the place here, and I even tried playing around with the parameters on `` with this:
_client.V1.Secrets.KeyValue.V2ReadSecretPathsAsync("", "secret") // no dice
_client.V1.Secrets.KeyValue.V2ReadSecretPathsAsync("data", "secret") // also no dice

Any idea what I'm missing?

A: After a lot of tinkering around, I finally found the problem: a permissions issue in general.
The key turned out to be in the policy file, which was originally this:
λ vault policy read my-policy
# Dev servers have version 2 of KV secrets engine mounted by default, so will
# need these paths to grant permissions:
path "secret/data/*" {
  capabilities = ["create", "update","list"]
}

path "secret/data/foo" {
  capabilities = ["read","list"]
}

For starters, the second path was basically junk.  It was there because it got copied when I followed a tutorial.  More importantly, though: the first path would not let me list metadata.
Ultimately I changed it to the following:
λ vault policy read my-policy
# Dev servers have version 2 of KV secrets engine mounted by default, so will
# need these paths to grant permissions:
path "secret/data/*" {
  capabilities = ["create", "update","read","list"]
}

path "secret/*" {
  capabilities = ["create","update","read","list"]
}

The fact that they both now also have read/create/update/list isn't really the important part here -- I did that to make sure my POC could do everything it needed to.  The important part here was that there needed to be list permissions on secret/*.
Once I updated the policy, AppRole auth worked perfectly.


text:
Q: RavenDB: How do you update child entities? I have been playing around with RavenDB.  I have to say I am quite impressed, but I am struggling to understand how to update child objects.  For example, lets say we have the following:
public class Course
{
    public int Id { get; set; }
    public string Title { get; set; }
}

public class Student
{
    public Student()
    {
        Courses = new Collection<Course>();
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<Course> Courses { get; set; }
}

I am able to save one Student and two Courses associated to the student in the database.  I am able to load the Student with the two Courses without a problem as well.  But when I tried to modify the courses, for example student.Courses.Add(new Course { Id = 5, Title = "Accounting 101"}), I was expecting it to sync between what is in the database versus what is currently in student.Courses.  Basically, I am expecting it to delete the courses in the database and only have the course in student.Courses.  This maybe my misunderstanding of how RavenDB works.  I couldn't find any examples like this.  What is the best practice way of handling this situation?

A: No, it won't do any of what you described.  The way you have modeled it, there are two separate documents in the database:
Course
{
  Id : "courses/1",
  Title : "Algebra"
}

Student
{
  Id : "students/1",
  Name : "John",
  Courses :
    [
      {
        Id : "courses/1",
        Title : "Algebra"
      }
    ]
}

The benefit of denormalizing Course into Student is that you don't have to load Course documents when reviewing Student information to get the course's title.
The down side is that any changes to Course must be done to both documents.  If you just add a course to the student document, it is referring to a Course document that doesn't exist.  Raven won't stop you from doing that.  There are no referential integrity constraints in a document database.
In the real world, you would probably add a course before you add the course to a Student, and dropping all students from a course doesn't mean that there is no course.  So really, it's only actions like renaming a course that have to go touch both the course document and all student documents that have the relationship.
Often you will want to just use IList<string> CourseIds.  There is no requirement that you denormalize.  Review this documentation for further details.