text:
Q: Given start times and duration, show duration since started for every minute on the minute Background:
I have several hardware devices (controllers) to which commands are being sent when an operator presses a button on a web page. We are investigating why sometimes the communication is slow. I set up a python automated script to scrape the page and change controller modes every minute on three separate controllers. I log the beginning of the operation and the duration.
Sample Data:
Id  Cont_id Start_time (pst)    Duration (sec)
316 11002   2017-06-22 20:05:13 5
317 6224    2017-06-22 20:05:38 15
319 7782    2017-06-22 20:06:20 15
318 11002   2017-06-22 20:06:20 5
320 6224    2017-06-22 20:06:56 15
321 11002   2017-06-22 20:07:27 5
336 7782    2017-06-22 20:07:38 500
322 6224    2017-06-22 20:08:14 15
323 11002   2017-06-22 20:08:36 5
324 6224    2017-06-22 20:09:32 10
325 11002   2017-06-22 20:09:43 10
326 6224    2017-06-22 20:10:44 10
327 11002   2017-06-22 20:10:55 10
328 6224    2017-06-22 20:11:56 5
329 11002   2017-06-22 20:12:07 15
330 6224    2017-06-22 20:13:03 10

Desired Results:
I'd like to have a report that has an entry for every minute and tells me how long each controller has been in its current operation. For example, consider around the time ~20:07 in the sample data (controller 7782). I would like to see the following;
sample_time | cont_id | last_start_time | time_in_operation
20:08:00*   | 7782    | 20:07:38        | 22
20:08:00    | 11002   | 20:07:27        | 5 *
20:08:00    | 6224    | 20:06:56        | 15
20:09:00    | 7782    | 20:07:38        | 88
20:09:00    | 11002   | 20:08:36        | 5
20:09:00    | 6224    | 20:08:14        | 15
20:10:00    | 7882    | 20:07:38        | 148
....etc

*

*Note1: I show time for brevity - I actually want the entire date/time
Note2: This is 5 seconds because the operation is done, so use the
     duration value.

Question: My biggest problem is coming up with a mock entry every minute. Once that is solved, I think I can get the rest...So, how do I write a query that gives me an entry for every minute between two time ranges, written in a way that I can use to calculate the final report as per the sample data.
Setup:
CREATE TABLE public.operationtimelog (
    id int4 NOT NULL DEFAULT nextval('operationtimelog_id_seq'::regclass),
    controller_id int4 NOT NULL,
    op_start_time timestamp NOT NULL,
    op_duration int4 NOT NULL,
    CONSTRAINT operationtimelog_pkey PRIMARY KEY (id)
)
WITH (
    OIDS=FALSE
);

insert into
    operationtimelog (controller_id, op_start_time, op_duration) values
    (11002,  '2017-06-22 20:05:13', 5),
    (6224,   '2017-06-22 20:05:38', 15),
    (7782,   '2017-06-22 20:06:20', 15),
    (11002,  '2017-06-22 20:06:20', 5),
    (6224,   '2017-06-22 20:06:56', 15),
    (11002,  '2017-06-22 20:07:27', 5),
    (7782,   '2017-06-22 20:07:38', 500),
    (6224,   '2017-06-22 20:08:14', 15),
    (11002,  '2017-06-22 20:08:36', 5),
    (6224,   '2017-06-22 20:09:32', 10),
    (11002,  '2017-06-22 20:09:43', 10),
    (6224,   '2017-06-22 20:10:44', 10),
    (11002,  '2017-06-22 20:10:55', 10),
    (6224,   '2017-06-22 20:11:56', 5),
    (11002,  '2017-06-22 20:12:07', 15)

A: Answering your question: given two timestamps generate a table which holds records for every minute between them.
select time_column
from generate_series(
  '2017-06-22 20:00:00'::TIMESTAMP,
  '2017-06-22 20:09:00'::TIMESTAMP,
  '1m'
) x(time_column)

Output:
     time_column
---------------------
 2017-06-22 20:00:00
 2017-06-22 20:01:00
 2017-06-22 20:02:00
 2017-06-22 20:03:00
 2017-06-22 20:04:00
 2017-06-22 20:05:00
 2017-06-22 20:06:00
 2017-06-22 20:07:00
 2017-06-22 20:08:00
 2017-06-22 20:09:00

Then you can use a LEFT JOIN to connect your table/query to it by that time column with truncation of seconds for op_start_time from your sample data.
How to truncate seconds from a timestamp?
select date_trunc('m','2017-06-22 20:07:38'::timestamp)

Output:
     date_trunc
---------------------
 2017-06-22 20:07:00


text:
Q: Insert string with unknown chars (i.e ', ", `, etc.) I am not too much good with database, but I can manage simple database operation. Currently I am facing one issue when insert data into table. Let me explain scenario.
In my app, I am searching places via GoogleMapSDK and then drop down list of places I am selecting one place. Then I want to add that place as a favourite and insert all data in database. Now the problem is GoogleMapSDK returns place name awkward something like : ''Sapna''SPa'''''''.  And database query does not let me insert this data into database.
How can I insert data like this ?
I know is in above name if it contains one single quote or double quotes then can be managed with back slash, but how it can manage if you don't know what data will be there ?
I want to store data as it is, without replacing or removing any char.
If anyone have solution, please share.

A: You can prepare your querys with variable placeholders instead of constructing the full query string yourself.
For example:
a) INSERT INTO yourtable (name) VALUES ('''Sapna''SPa'''''''')

b) INSERT INTO yourtable (name) VALUES (?)

I'm not familiar with objective-c but usually you can run your querys safely in 3 steps:

*

*write your query with placeholders and prepare it (like query b)

*bind variables to placeholders

*execute your prepared statement

Consult your sqlite driver's documentation for details.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Choosing the right model for prediction Given a set of temperatures of different cities for a month, which prediction model should I use for a two day look ahead prediction? Regression models or Time series?

A: In lieu of an absolute or a priori answer, you could use your existing temperature data to evaluate the performance of the different prediction methods.
E.g. say you have 30 days of temperature data. Perform a set of trials, for both models, where you train the model on some initial segment of the data, say, days 1..n, where n<28, and record the prediction of the model for day n+2. This will give you some empirical evidence of the performance of the different models, given your data.
If you need more temperature data, you could always use a massive dataset like Berkeley Earth.


text:
Q: Retrofit 2, сохранение ответа Имеется код:
public void LoadDataShop(int localityId, String parameters){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(APIUrl.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        APIService service = retrofit.create(APIService.class);
        Call<Shops> call = service.getShopsBasket(localityId, parameters);
        call.enqueue(new Callback<Shops>() {
            @Override
            public void onResponse(Call<Shops> call, Response<Shops> response) {
                Log.e("Запуск","Запуск");
                ArrayList<Shop> shopsArray = response.body().getShops();//
//                Log.e("Размер",String.valueOf(shopsArray.size()));
//                for(int i = 0; i<shopsArray.size();i++){
//                    shops.add(shopsArray.get(i));
//                }
//                shops.addAll(shopsArray);
            }
            @Override
            public void onFailure(Call<Shops> call, Throwable t) {
                Log.e("Ошибка",t.getMessage());
            }
        });
    }

Он загружает список магазинов. Необходимо выполнить похожий метод для загрузки цен и только потом передать в адаптер
Проблема в том что я не могу сохранить результат. Пытался засунуть результат 1 запроса в ArrayList, который объявлен глобально во всем классе, и после выполнения этого метода отобразить элементы. Но его длина составляет 0, хотя приходит 7 объектов.
Судя по логам сначала выдает 0, потом 7, скорее всего из-за того что запрос асинхронный и сообщение срабатывает быстрее чем выполнился запрос.

A: Почитайте больше про CallBack. В данном случае у вас происходит задержка. Изначально происходит создание и отображение данных, а после получение. Вам стоит либо в Activity создавать Callback и работать внутри onResponce, либо сделать запрос синхронным (это неправильно, но как вариант для вас) примерно как-то так:
try {
    call.execute().body()...
}catch (IOException e) {
    e.printStackTrace();
}


text:
Q: What are the values taken by j in the loop What is the behavior of the following line in the class Sort?
for (int j = i+1; j > ListPerson.size(); j++) {

I added System.out.println(j); to see the values taken by j, but when executing, no value is displayed!
Why does Eclipse not consider ListPerson.get(j) as an error, knowing that j > ListPerson.size()?!!
package Tests;

public class Person {
    String nom;
    int age;

    public Person(String nom, int age) {
        this.nom = nom;
        this.age = age;
    }
}

package Tests;

import java.util.ArrayList;
import java.util.List;

import CompUnivSol2.Etudiant;

public class Sort {

    public static void main(String[] args) {
        List<Person> ListPerson = new ArrayList<Person>();
        ListPerson.add(new Person("Paul", 20));
        ListPerson.add(new Person("Coco", 18));
        ListPerson.add(new Person("Eric", 4));

        String temp1;
        int temp2;
        for (int i = 0; i < ListPerson.size(); i++) {
            for (int j = i + 1; j > ListPerson.size(); j++) {
                if (ListPerson.get(i).age > ListPerson.get(j).age) {

                    temp1 = ListPerson.get(j).nom;
                    ListPerson.get(j).nom = ListPerson.get(i).nom;
                    ListPerson.get(i).nom = temp1;

                    temp2 = ListPerson.get(j).age;
                    ListPerson.get(j).age = ListPerson.get(i).age;
                    ListPerson.get(i).age = temp2;
                }
            }
        }

        for (int i = 0; i < ListPerson.size(); i++) {
            System.out.print("\n N°" + (i + 1) + ": " + ListPerson.get(i).nom + ": " + ListPerson.get(i).age); //le \n pour mettre chaque
                                                                                //établissement dans 1 ligne
        }
    }
}

the last loop in the class Sort displays the following:

N°1: Paul: 20
N°2: Coco: 18
N°3: Eric: 4

A: Because of j > ListPerson.size() in the following line
for (int j = i + 1; j > ListPerson.size(); j++)

this loop is not getting executed at all.
When i = 0 -----> j = 1 -----> the condition gets evaluated as 1 > 3 (i.e. j > ListPerson.size())
As you can understand, 1 > 3 is false and therefore the loop does not get executed.
You need to change it to
for (int j = i + 1; j < ListPerson.size(); j++)

Apart from this problem, your sorting logic is also not correct. Instead of swapping the persons, you are just swapping their names. To fix the problem, replace
String temp1;
int temp2;
for (int i = 0; i < ListPerson.size(); i++) {
    for (int j = i + 1; j > ListPerson.size(); j++) {
        if (ListPerson.get(i).age > ListPerson.get(j).age) {

            temp1 = ListPerson.get(j).nom;
            ListPerson.get(j).nom = ListPerson.get(i).nom;
            ListPerson.get(i).nom = temp1;

            temp2 = ListPerson.get(j).age;
            ListPerson.get(j).age = ListPerson.get(i).age;
            ListPerson.get(i).age = temp2;
        }
    }
}

with
Person temp = null;
for (int i = 0; i < ListPerson.size(); i++) {
    for (int j = i + 1; j < ListPerson.size(); j++) {
        if (ListPerson.get(i).age > ListPerson.get(j).age) {
            temp = ListPerson.get(i);
            ListPerson.set(i, ListPerson.get(j));
            ListPerson.set(j, temp);
        }
    }
}

However, an elegant way would be to use Collections.sort instead of sorting this way.
Feel free to comment in case of any doubt/issue.


text:
Q: Same OS (Windows 10) twice in Dell BIOS boot sequence Just as the title says, in a way or another I have got two boot options in my boot sequence which both point to the same boot file but have different names. In the past there only was the "Windows 10" option, but after a recent operation with GParted there had appeard the third option, which in fact points to the same OS as the first one.
The operation in GParted mentioned above: some time ago I installed Ubuntu 20.04 on an external HDD, but due to lack of experience the installation wasn't configured properly and the result was that Ubuntu was using the EFI partition of my internal SSD to boot instead of an own EFI partition on the external HDD. I wanted to solve this, because I wanted to keep the two separated and eventually wanted to be able to boot the external HDD on another computer too. So I copied the EFI partition from the SSD to the beginning of the HDD, assigned the flags it needed and then removed the Ubuntu files from the first EFI partition and the Microsoft files from the second EFI partition (because I obviously didn't need those anymore on the mentioned drives) with the terminal in the GParted image.
Everything works just fine, but then there's this frustrating thing that the "UEFI: SK hynix SC311 etc." option always reappears in the boot sequence, even if I delete it from the firmware settings. I have also tried to remove both "Windows 10" and "UEFI: SK hynix etc." options, and they both reappeared at the next reboot.
Here are the pictures of my screen for further clarification (I don't know how to make a screenshot outside the OS). And please excuse the exagerated width, but I'm new here and I don't know how to make images smaller.

A: EFI supports two kinds of boot entries:

*

*User-configurable entries that can point to any bootloader on the EFI System Partition,

*Automatic entries that are generated if an appropriately-named file exists on that partition. For x86-64 systems the file would be EFI\Boot\BootX64.efi (case-insensitive because it's FAT).
The 2nd variant was originally intended for bootable external media (CDs, USB etc.) that's supposed to be bootable without additional configuration. But it's also used on fixed drive ESPs because some EFI implementations are buggy and/or incomplete. One example is Virtualbox's EFI, which forgets all user-configured boot entries when a VM is powered off. In such cases having an always-present automatic entry as a last resort is convenient.
If you're willing to sacrifice some portability to get rid of the extra entry, deleting or renaming EFI\Boot from the ESP should do the trick. Note that it may get recreated by whatever you're booting though.


text:
Q: Why all already set auto layout constrains are gone if change the frame of view?
As shown in screen shot I made all 4 views' widths equally and height equally after that if i change the frame size of green view all the other constraints as Horizontal spacing,vertical spacing are gone and I have to start from the beginning for all view to work in both portrait and landscape.
Also after that i Set All constrains again and still in landscape mode labels are not showing properly as shown in screen shot
I set these constrains.
Is there something I am missing?

A: Look at the log for more information to make sure your constraints are breaking or not.
Follow these steps to see if you have Unsatisfiable / Ambiguous Constraints
1) Run the app and then pause it.
2) Type/send the following message to UIWindow in lldb debugger.
           po [UIWindow keyWindow] _autoLayoutTrace]

3) This gives you the auto-layout trace and you can easily figure out what's going wrong.

A: The reason why the constraints which were already were removed is because the constraints were not satisfied. The system intelligently adjusts the constraints if it find the constraints were not satisfied. Refer to previous answer and make sure the autoLayoutTrace has no violations.


text:
Q: Python: изменение константы во внешней библиотеке Представим, что есть какая-то внешний модуль, выкачавыемый через PIP, и в нем есть следующие строки:
TIMEOUT = 50

def test_const():
    print(TIMEOUT)

Как без изменения внешнего модуля, поменять эту константу? Пробовал так, не помогло:
from out_module import test_const

out_module.TIMEOUT = 10
test_const()

A: from out_module import test_const

импортирует только функцию test_const в глобальные переменные.
Для того чтобы появилась константа TIMEOUT в глобальных переменных надо импортировать весь модуль, либо так
from out_module import test_const
import out_module

out_module.TIMEOUT = 10
test_const()

либо так
import out_module

out_module.TIMEOUT = 10
out_module.test_const()


text:
Q: Application variable is nil in testing environment My application works fine, but I can't get a test to pass. I'm new at rails so forgive me if the answer is obvious.
I need a variable available to every view, so I'm doing this within application_controller.rb:
class ApplicationController < ActionController::Base
  protect_from_forgery
  before_filter :course
  def course
    @course = Course.find_slug(params[:course])
  end
end

My test case looks like this:
it "creates an attempt" do
  sign_in current_user
  params = {:id => challenge.id, :description => "this was hard!", :course => "design"}
  @course = FactoryGirl.create(:course)
  post :completed, params
  response.should redirect_to "/#{@course.slug}/?challenge_slug=" + challenge.slug
  Attempt.count.should == 1
  Attempt.last.description.should == params[:description]
end

The method within my controller looks like this:
  def completed
    @challenge = Challenge.find(params[:id])
    @challenge.completed(current_user, params)
    redirect_to "/#{@course.slug}/?challenge_slug=" + @challenge.slug.to_s
  end

All this works fine if I'm using the application, but the test says:
  1) ChallengesController completing a challenge creates an attempt
     Failure/Error: post :completed, params
     NoMethodError:
       undefined method `slug' for nil:NilClass
     # ./app/controllers/challenges_controller.rb:16:in `completed'
     # ./spec/controllers/challenges_controller_spec.rb:36:in `block (3 levels) in <top (required)>'

If I hardcode my controller to say redirect_to "#{'expected_value'}" then the test passes, so it seems that within the testing environment I don't have access to the application variable @course, is this correct?
I'm lost on how to solve this. Any help is appreciated.

A: One solution is to stub the find method and return the instance variable.
before(:each) do
  @course = FactoryGirl.create(:course)
  Course.stub(:find_slug).and_return(@course)
end

This makes your tests more robust as the test for "find_slug" should be in your Course model, not the controller.


text:
Q: Resolve host to IP address and display it in a popup using a Chrome extension I'm developing a Chrome extension to do the following.
When clicked on the icon, the popup shows the ip address of the currently displayed page.
This extension should work on every page. But the issue is the IP of the current url should have be loaded when the url is loaded. Not when the popup is shown so that there will be no delay between the pop up and getting the IP address via a web service.
So in essence the popup of the extension is different for every tab.
Should this be a page action or a browser action ?
And how do I get the data from the web service in the background and assign it to a popup before it is actually displayed ?
Any info is really appriciated.

A: This answer contains the full code for testing the extension. To test, create each file, store it in the same directory, and load it via chrome://extensions/ (developer mode).

"This extension should work on every page." -> Browser action.
There are two methods to capture the URL of a page as soon as possible. Both methods have to be used in the background page.

*

*Using chrome.tabs.onUpdated.
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
    if (changeInfo.status === 'loading' && changeInfo.url) {
        processUrl(tabId, tab.url); // or changeInfo.url, does not matter
    }
});

*Using the chrome.webRequest API:
chrome.webRequest.onBeforeRequest.addListener(function(details) {
    processUrl(details.tabId, details.url); // Defined below
}, {
    urls: ["*://*/*"],
    types: ["main_frame"]
});

Either method will capture the tab and url. In your case -showing the IP in a popup for the current tab-, the first method is preferred, because it is triggered for each tab update. The latter will only be triggered for http: and https: URLs.
Either method calls the processUrl function. This function is going to process the URLs for the given tabs. I recommend to cache the IP addresses, to avoid too many requests to the web service.
background.js
var tabToHost = {};
var hostToIP = {};

function processUrl(tabId, url) {
    // Get the host part of the URL.
    var host = /^(?:ht|f)tps?:\/\/([^/]+)/.exec(url);

    // Map tabId to host
    tabToHost[tabId] = host ? host=host[1] : '';

    if (host && !hostToIP[host]) { // Known host, unknown IP
        hostToIP[host] = 'N/A';    // Set N/A, to prevent multiple requests
        // Get IP from a host-to-IP web service
        var x = new XMLHttpRequest();
        x.open('GET', 'http://www.fileformat.info/tool/rest/dns.json?q=' + host);
        x.onload = function() {
            var result = JSON.parse(x.responseText);
            if (result && result.answer && result.answer.values && result.answer.values[0]) {
                // Lookup successful, save address
                hostToIP[host] = result.answer.values[0].address;
                setPopupInfo(tabId);
             }
         };
         x.send();
    }

    // Set popup info, with currently (un)known information
    setPopupInfo(tabId);
}
function setPopupInfo(tabId) { // Notify all popups
    chrome.extension.getViews({type:'popup'}).forEach(function(global) {
        global.notify(tabId);
    });
}

// Remove entry from tabToIp when the tab is closed.
chrome.tabs.onRemoved.addListener(function(tabId) {
    delete tabToHost[tabId];
});
// Add entries: Using method 1 ( `onUpdated` )
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
    if (changeInfo.status === 'loading' && changeInfo.url) {
        processUrl(tabId, tab.url); // or changeInfo.url, does not matter
    }
});

// Init: Get all windows and tabs, to fetch info for current hosts
chrome.windows.getAll({populate: true}, function(windows) {
    windows.forEach(function(win) {
        if (win.type == 'normal' && win.tabs) {
            for (var i=0; i<win.tabs.length; i++) {
                processUrl(win.tabs[i].id, win.tabs[i].url);
            }
        }
    });
});

Once the IP is found, the IP is saved in a hash. This hash looks like:
hostToIP = {
    'stackoverflow.com': '64.34.119.12',
    'superuser.com': '64.34.119.12'
};

As you can see, two hosts may refer to the same IP. The reverse is also true: A host may have multiple IP addresses (Lookup Google, for example).
The background page communicates with a browser action popup, if opened.
popup.js
// Get initial tab and window ID
var tabId, windowId;
chrome.tabs.query({active:true, currentWindow:true, windowType:'normal'},
  function(tabs) {
    if (tabs[0]) {
        // Found current tab
        window.tabId = tabs[0].id;
        windowId = tabs[0].windowId;
        requestUpdate();
    }
});
// Receive tab ID updates
chrome.tabs.onActivated.addListener(function(activeInfo) {
    if (activeInfo.windowId === windowId) {
        requestUpdate();
    }
});

// Communication with background:
var background = chrome.extension.getBackgroundPage();

// Backgrounds calls notify()
function notify(tabId, url, ip) {
    if (tabId === window.tabId) { // Tab == current active tab
        requestUpdate();
    }
}
// Get fresh information from background
function requestUpdate() {
    // tabId is the current active tab in this window
    var host = background.tabToHost[tabId] || '';
    var ip = host && background.hostToIP[host] || 'N/A';
    // Now, do something. For example:
    document.getElementById('host').textContent = host;
    document.getElementById('ip').textContent = ip;
}

popup.html
<!DOCTYPE html>

<meta charset="utf-8">
<title>Host to IP</title>

Host:
IP  :

manifest.json
{
    "name": "Host To Tab",
    "manifest_version": 2,
    "version": "1.0",
    "description": "Shows the IP of the current tab at the browser action popup",
    "background": {"scripts":["background.js"]},
    "permissions": ["http://www.fileformat.info/tool/rest/dns.json?q=*", "tabs"],
    "browser_action": {
        "default_popup": "popup.html"
    }
}

Relevant documentation

*

*Browser Actions

*chrome.tabs API (heavily used)

*DNS in client-side JavaScript - documentation of the web service

*chrome.windows.getAll method (to get initial information).


text:
Q: Git(hub) keep giving `Host key verification failed` error I am trying to add ssh-key to my github account but i keep getting Host key verification failed error.

img url: https://image.ibb.co/k94mT8/PDv4oQ.jpg
I have followed this steps: https://help.github.com/articles/checking-for-existing-ssh-keys/

Generating a new SSH key
   ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

Adding your SSH key to the ssh-agent
  eval $(ssh-agent -s)

Adding a new SSH key to your GitHub account

and tried almost all related stackoverflow answers but the error is still alive.
Where i did wrong?
Edit: I can clone with https but not with ssh.

A: Run that command. This will probably solve your issue.
ssh git@github.com -vvvv

Thanks: https://www.reddit.com/r/git/comments/8m8y56/github_keep_giving_host_key_verification_failed/dzlrvzk/

A: It's probably late, but anyway. Are you sure that you type 'yes' when terminal asked you: 'Are you sure you want to continue connecting (yes/no)?'. If you will be just press Enter - connection will be failure


text:
Q: Large pySpark DataFrame: .collect() is crashing even after .limit I'm working with pyspark 2.1.1.
I created a PySpark DataFrame with a sqlContext.sql('select...') on a spark cluster which is to big for .collect() or .toPandas().
Since I want to use it in smaller parts with pandas I first just want to work on a really small part of it in pandas to test some code.
I tried several combinations of .limit(), .cache(), collect() and .toPandas() all crashed my sparkContext and/or caused an java.lang.OutOfMemoryError.
E.g. although the Dataframe does only have 3 small columns: this code is causing an OutOfMemoryError:
test = psdf.limit(5).cache()
test2 = test.collect()

It seems like .limit() is not really working as I expect.
How may I extract a small part of the table with pyspark which is really just a small part with which I may work really fast?


text:
Q: Fragment hide animation is not playing I'm trying to toggle my fragment with slide animation
Using this code:
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
SearchPanelFragment existingFragment = (SearchPanelFragment) manager.findFragmentByTag(SearchPanelFragment.FRAGMENT_NAME);
transaction.setCustomAnimations(R.xml.slide_down_search_panel, R.xml.slide_up_search_panel);
if (existingFragment != null) {
    if (existingFragment.isVisible())
        transaction.remove(existingFragment);
} else {
    transaction.add(R.id.top_panel_fragment, new SearchPanelFragment(this), SearchPanelFragment.FRAGMENT_NAME);
}

    transaction.commit();

So far I get only enter animation on transaction.add When is exit animation played? I could only get it when using transaction.replace but then I was just swaping an old fragment with identical new one, and what I want is to hide/remove/detach/whatever it's neccessary to make it dissapear with exit animation played
EDIT: I tried hide, remove and detach. No matter what I do, the animation is not played. It's played only on add, show, and replace
EDIT 2:
There might be something wrong with the second animation. Please take a look on both on them. First one slides down and seems to be working just fine.
Slide down
<translate
    android:duration="500"
    android:fromXDelta="0%"
    android:fromYDelta="-100%"
    android:toXDelta="0%"
    android:toYDelta="0%" />

Slide up
<translate
    android:duration="700"
    android:fromXDelta="0%"
    android:fromYDelta="0%"
    android:toXDelta="0%"
    android:toYDelta="-100%" />

A: You're actually using the wrong function.
According to the documentation for setCustomAnimations(int enter, int exit):

Set specific animation resources to run for the fragments that are entering and exiting in this transaction. These animations will not be played when popping the back stack.

Instead you should use setCustomAnimations (int enter, int exit, int popEnter, int popExit):

Set specific animation resources to run for the fragments that are entering and exiting in this transaction. The popEnter and popExit animations will be played for enter/exit operations specifically when popping the back stack.

A: Edit
The bug has been fixed as of June 7th 2013. I believe starting at revision 18, the bug has been fixed.
This no longer should be an issue if you are using the latest Support Library Revision
Old Answer
http://code.google.com/p/android/issues/detail?id=32405 There is a bug in support library. The only chance to get it work is get support library sources and recompile it yourself


text:
Q: D - Exception not handled by scope statement Why does this code result in an exception during runtime, when I would expect it to be handled by the scope statement?
void scopeTest(ref int i) {
  i = 10 / i;
  scope(failure) i = 0;
}
...
int j = 0;
j.scopeTest;

The same runtime error happens with scope(exit) being used instead.
When compiling with -run flag with ldc, I get Error: message: Floating point exception (core dumped)
Error: program received signal 2 (Interrupt). With dmd, I get Error: program killed by signal 8.

A: That's a processor exception. The scope(failure) only occurs to D language exceptions (which only includes system and processor things on 32-bit Windows!).

A: scope(failure) is only executed when a Dlang exception is throwed. But in this particular case, this is a processor error, catched by your operating systems detecing a division by zero and proceeding to kill your process (because it assumes your process is in an invalid state). The right way is to catch the error yourself is NEVER EXECUTE invalid operations (A simple IF clause can help to solve this particular division by zero problem, but applies to segment faults too)
(It doesn't sound very practical but is a design trade-off. Better make YOUR program check for invalid operations when needed and BEFOREHAND than complicate compilers, portability, over-coupling compilers/libraries with non-portable OS/CPU specific stuff and (most important) slow-down overall performance because error handling is happening AFTERWARDS)

A: My reading of the explanation in Programming in D is that the scope(failure) does not catch or prevent the exception, it just makes sure that the code runs in the event of an exception. A bit like a catch{} block that does something in the case of an exception, and then re-throws the same exception, but cleaner.
The book (and the language spec) speak of exiting the scope due to an exception. If scope caught or prevented the exception then it would not cause the execution to leave that scope.
The example at the bottom of PinD scope also shows the object.Exception, even though the code contained multiple scope(failure) statements.
(I am a pretty experienced but not a very experienced D programmer.)


text:
Q: Performance: Loop incl. AJAX vs. a single request with php loop I wrote a PHP that is currently looping through data, validating and importing them into a database. This can take some time, depending on the amount of data to run through.
My next step is to make this "user-friendly" so others can use it, not just me. I was looking at the components I want to implement, including a progress bar so the user knows the script isn't just stuck but is doing something.
Now the question comes up: should I use a JavaScript loop through the data, have them validated one by one and imported to the database with the help of an AJAX call to my php script? This would be pretty useful as well to update the progress bar after each iteration.
Or is it—performance-wise—better to do a single request to the php script which then loops through the data? In that case: how could I implement the updating progress bar?
These are a bunch of questions. The overall purpose is to see what my options are and what arguments speak for each. Thanks in advance!

A: Well if you want to have a progress bar, then you will need to do it 1-by-1, you would count all the records and then very time one calls back as completed, you would increment the progress bar by a certain percentage.
100 / amount of records = percentage to increase progress bar.

However, the issue with that approach is that if somewhere along the line it fails, you will need to know where it did so, or devise a way to make sure duplicates are not added to the database (If that's even an issue).
It would be better to add the data at once, faster and cleaner, but it would remove the possibility of having a progress bar that actually gives you a correct progress report.


text:
Q: How to Deserialize binary protobuf to json with bash script I have developed a bash script to deserialize binary protobuf to json but output is look like json but no true json
Code:
#!/bin/bash
...
binaryMsg= ..
echo binaryMsg > /tmp/di.bin

protoc --decode=my.proto.PkgDiStatus controller.proto</tmp/di.bin

it gives output like below
ups_status {
  low_battery: false
  no_power_out: false
  replace_battery: false
  common_fault: false
}
testing_mode: false

I have to extract values of low_battery or replace_batter, Although this output can be parse with custom script like sed but if i get json then jq can be use for parsing.


text:
Q: How To Run kubectl apply commands in terraform I have developed a terraform script to create a k8 cluster on GKE.
Post successful creation of cluster, I have set of yaml files to be applied on k8 cluster.
How can I invoke the below command in my terraform script?
kubectl create <.yaml>

A: You can use the Terraform kubectl third party provider. Follow the installation instructions here: Kubectl Terraform Provider
Then simply define a kubectl_manifest pointing to your YAML file like:
# Get your cluster-info
data "google_container_cluster" "my_cluster" {
  name     = "my-cluster"
  location = "us-east1-a"
}

# Same parameters as kubernetes provider
provider "kubectl" {
  load_config_file       = false
  host                   = "https://${data.google_container_cluster.my_cluster.endpoint}"
  token                  = "${data.google_container_cluster.my_cluster.access_token}"
  cluster_ca_certificate = "${base64decode(data.google_container_cluster.my_cluster.master_auth.0.cluster_ca_certificate)}"
}

resource "kubectl_manifest" "my_service" {
    yaml_body = file("${path.module}/my_service.yaml")
}

This approach has the big advantage that everything is obtained dynamically and does not rely on any local config file (very important if you run Terraform in a CI/CD server or to manage a multicluster environment).
Multi-object manifest files
The kubectl provider also offers data sources that help to handle files with multiple objest very easily. From the docs kubectl_filename_list:
data "kubectl_filename_list" "manifests" {
    pattern = "./manifests/*.yaml"
}

resource "kubectl_manifest" "test" {
    count = length(data.kubectl_filename_list.manifests.matches)
    yaml_body = file(element(data.kubectl_filename_list.manifests.matches, count.index))
}

Extra points: You can templatize your yaml files. I interpolate the cluster name in the multi-resource autoscaler yaml file as follows:
resource "kubectl_manifest" "autoscaler" {
  yaml_body = templatefile("${path.module}/autoscaler.yaml", {cluster_name = var.cluster_name })
}

A: When creating multiple Terraform resources, it is usually better to use named resource instances than to use a list (count). If the source file is updated and the order of Kubernetes resources change, it may cause Terraform to delete/create resources just because of the index change.  This code creates a key by concatenating kind and metadata.name fields:
data "kubectl_file_documents" "myk8s" {
  content = file("./myk8s.yaml")
}

resource "kubectl_manifest" "myk8s" {
  # Create a map of { "kind--name" => raw_yaml }
  for_each  = {
    for value in [
      for v in data.kubectl_file_documents.myk8s.documents : [yamldecode(v), v]
    ] : "${value.0["kind"]}--${value.0["metadata"]["name"]}" => value.1
  }
  yaml_body = each.value
}

In the future you may want to use Hashicorp's official kubernetes_manifest resource instead (as of 2.5.0 -- in beta, buggy):
resource "kubernetes_manifest" "default" {
  for_each = {
    for value in [
      for yaml in split(
        "\n---\n",
        "\n${replace(file("./myk8s.yaml"), "/(?m)^---[[:blank:]]*(#.*)?$/", "---")}\n"
      ) :
      yamldecode(yaml)
      if trimspace(replace(yaml, "/(?m)(^[[:blank:]]*(#.*)?$)+/", "")) != ""
    ] : "${value["kind"]}--${value["metadata"]["name"]}" => value
  }
  manifest = each.value
}

A: There are a couple of ways to achieve what you want to do.
You can use the Terraform resources template_file and null_resource.
Notice that I'm using the trigger to run the kubectl command always you modify the template (you may want to replace create with apply).
data "template_file" "your_template" {
  template = "${file("${path.module}/templates/<.yaml>")}"
}

resource "null_resource" "your_deployment" {
  triggers = {
    manifest_sha1 = "${sha1("${data.template_file.your_template.rendered}")}"
  }

  provisioner "local-exec" {
    command = "kubectl create -f -<<EOF\n${data.template_file.your_template.rendered}\nEOF"
  }
}

But maybe the best way is to use the Kubernetes provider.
There are two ways to configure it:

*

*By default your manifests will be deployed in your current context ( kubectl config current-context )

*The second way is to statically define TLS certificate credentials:

provider "kubernetes" {
  host = "https://104.196.242.174"

  client_certificate     = "${file("~/.kube/client-cert.pem")}"
  client_key             = "${file("~/.kube/client-key.pem")}"
  cluster_ca_certificate = "${file("~/.kube/cluster-ca-cert.pem")}"
}

Once done that, you can create your own deployment pretty easy. For a basic pod, it'd be something as easy as:
resource "kubernetes_pod" "hello_world" {
  metadata {
    name = "hello-world"
  }

  spec {
    container {
      image = "my_account/hello-world:1.0.0"
      name  = "hello-world"
    }

    image_pull_secrets  {
      name = "docker-hub"
    }
  }
}

A: In case for the remote url hosting the yaml file, and the yaml file has included multiple configs/objects, here's what can be done.
resource "null_resource" "controller_rancher_installation" {

  provisioner "local-exec" {
    command = <<EOT
      echo "Downloading rancher config"
      curl -L https://some-url.yaml -o rancherconfig.yaml
    EOT
  }
}

data "kubectl_path_documents" "rancher_manifests" {
    pattern = "./rancherconfig.yaml"
    depends_on = [null_resource.controller_rancher_installation]
}

resource "kubectl_manifest" "spot_cluster_controller" {
    count     = length(data.kubectl_path_documents.spot_controller_manifests.documents)
    yaml_body = element(data.kubectl_path_documents.spot_controller_manifests.documents, count.index)
}

The idea is to download it firstly, and then apply it. This is based on observation:

*

*pattern = "./rancherconfig.yaml" doesn't support remote url, only
local files.

*"kubectl_manifest" by default only applies the first
config/object in the yaml file.

A: Adding some more information to existing answers for 2022 viewers. Given question is missing information about where these terraform & kubectl command are need to be executed
Case 1: Developer is using a local system that is not part of Google Cloud Platform
In this case, when you are using null_resource to execute a command then your command will run in you local pc not in google cloud.
Case 2: Developer is using a system that is part of Google Cloud Platform like Google Console Terminal or Google Cloud Code
In this case, when you are using null_resource to execute a command then your command will run in a temporary environment that is actively managed google cloud.
From here, it is possible to execute kubectl command using terraform. Said that, next question is it a good approach to do? It's not.
GCP is not a free resource. If you are building/using tools, it is important to use the right tool for right resource. In DevOps operations, there are two core areas. One is setting up infra where Terraform works best and next is managing infra where Ansible works best. For the same reason, GCP actively provide support for these.

A: You can use terraform local-exec to do this.
   resource "aws_instance" "web" {
     # ...
     provisioner "local-exec" {
      command = "echo ${aws_instance.web.private_ip} >> private_ips.txt"
     }
   }

Ref: https://www.terraform.io/docs/provisioners/local-exec.html

A: The answers here are great.  One suggestion as your requirements evolve from the initial manifest, you may want to look at creating a helm chart from the the manifest (or maybe one already exists) and use the terraform helm provider instead to set the values for your environment.
https://tech.paulcz.net/blog/getting-started-with-helm/
You'll notice an advantage to helm provider is that is easy to override and manage changes in values by terraform environment instead of embedding it into the manifest.
https://registry.terraform.io/providers/hashicorp/helm/latest/docs/resources/release

A: You can also also use the helm provider together with the itscontained chart. For example, the tekton dashboard could be installed like this, building on Yuri's Yaml splitting expression:
data "http" "tekton_dashboard_install" {
  url = "https://storage.googleapis.com/tekton-releases/dashboard/previous/v0.26.0/tekton-dashboard-release.yaml"

  request_headers = {
    Accept = "application/octet-stream"
  }
}

locals {
  tekton_dashboard_manifests = [
    for yaml in split(
      "\n---\n",
      "\n${replace(data.http.tekton_dashboard_install.body, "/(?m)^---[[:blank:]]*(#.*)?$/", "---")}\n"
    ) :
    yamldecode(yaml)
    if trimspace(replace(yaml, "/(?m)(^[[:blank:]]*(#.*)?$)+/", "")) != ""
  ]
}

resource "helm_release" "tekton_dashboard" {
  name       = "tekton_dashboard"
  repository = "https://charts.itscontained.io"
  chart      = "raw"
  version    = "0.2.5"
  namespace  =  "tekton-pipelines"

  values = [
    yamlencode({ resources = local.tekton_dashboard_manifests })
  ]
}

Some YAML files like the tekton core file come with a namespace definition, which must be filtered out first. Which is easy after the YAML is parsed.
This solution avoids the "Provider produced inconsistent result after apply" problems with the kubernetes_manifest resources and the hacky workarounds that follow.

A: The best way would be to use the Kubernetes provider of Terraform


text:
Q: {"error":{"message":"(#100) Missing message or attachment","type":"OAuthException","code":100}} This is my code
    private void postToWall(String msg) {
    Bundle parameters = new Bundle();

    JSONObject attachment = new JSONObject();

    String myjosn="{\"name\":\"LangGuage\",\"href\":\"http://www.hunkatech.com\",\"caption\":\" \",\"description\":\""+messageToPost+"\",\"media\":[{\"type\":\"image\",\"src\":\"http://hwsdemos.com/LangGuage/medal_1.png\",\"href\":\"http://www.hunkatech.com\"}],\"properties\":{\"Powered by:\":{\"text\":\"Hunka Technology Pvt. Ltd.\",\"href\":\"http://www.hunkatech.com\"}}}";

            try {

        parameters.putString(Facebook.TOKEN, facebook.getAccessToken());

            parameters.putString("attachment",myjosn.toString());

        String response = facebook.request("me/feed", parameters, "POST");

        System.out.println("----responce" + response);

        if (response.contains("Duplicate status message")) {
            progressHandler.sendEmptyMessage(1);
            resp = 1;

        } else if (response == null || response.equals("")
                || response.equals("false") || response.contains("error")) {
            Log.d("error", "error response");
        } else {
            progressHandler.sendEmptyMessage(0);
            resp = 0;

        }

    } catch (Exception e) {
        Log.e(TAG, "Posting fail");

        e.printStackTrace();

    }

}

I want to post message with image on Facebook wall.my json is correct i have checked it on json formatter editor.I got following exception.need suggestion how to solve it.
UPDATE: My message and images posted with the help of below code:
parameters.putString("link", "http://www.hunkatech.com");
parameters.putString("picture", "http://hwsdemos.com/LangGuage/medal_1.png");
parameters.putString("name", "LangGuage");// name of link
parameters.putString("captions", "hello");
parameters.putString("message", "This is my message!!");

But I want to have image left to the text but above code gives result as Imgae below message.
UPDATE: I am unable to post anything form json.can anyone please solve this problem I want to send attachment which bind image and massege with json.

A: You can try to put this parameter additionally :
parameters.putString("message", "this is my message");

Edit :
you can try :
parameters.putString("link", "http://www.hunkatech.com");
parameters.putString("picture", "http://hwsdemos.com/LangGuage/medal_1.png");
parameters.putString("name", "LangGuage");// name of link
parameters.putString("captions", "hello");
parameters.putString("message", "This is my message!!");

A: Here how I done it.
private void publishFeedDialog() {
        System.out.println("Working");
        Bundle postParams = new Bundle();
        postParams.putString("name", "I am an Engineer");
        postParams.putString("caption",
                "Working very heard to make things work.");
        postParams
                .putString("description",
                        "This project is killing me, Still I am trying, and finally I got success.");
        postParams.putString("link", "http://www.kodebusters.com");
        postParams
                .putString(
                        "picture",
                        "http://cdn1.iconfinder.com/data/icons/iconslandsport/PNG/128x128/Soccer_Ball.png");

        new MYasync(postParams).execute();

    }

Run your network calls on AsyncTask or it may through exception
 class MYasync extends AsyncTask<Void, Void, Void> {

            Bundle params;
            private String res;

            public MYasync(Bundle params) {
                super();
                this.params = params;
            }

            @Override
            protected void onPostExecute(Void result) {
                System.out.println(res);
                super.onPostExecute(result);
            }

            @Override
            protected Void doInBackground(Void... pp) {
                try {
                    res = facebook.request("me/feed", params, "POST");

                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return null;
            }

        }


text:
Q: Unable to find 'Message Body' TextBox. 'Search Criteria' did not match. (TYPE_1001) Hi I'm working on email object cloning.  The error is:

Unable to find 'Message Body' TextBox. 'Search Criteria' did not match. (TYPE_1001)
An error occurred at line number 8 of Task 'EmailPractice'. Open the
Task in Workbench to view action at line number 8.

A: Are you trying to touch a server? Or object clone something that is in a web browser email client like Gmail or Yahoo?
If it's the server, that's really easy you can use the $Email Message$ variable and it auto-magically pulls the body of the email as it loops through an email server.
Something that is going to generate dynamically like a browser is gonna be tough, but you might be able to do something like that in gmail or something by turning the page to "html only" mode.  Good luck!


text:
Q: How to convert int to char[] with sprintf() if char is pointer and the int not? I likely don't understand the sprintf function.
char s[30];
int i;

scanf("%d",&i);
sprintf(s,i); /*->warning: makes pointer from int*/

A: sprintf accepts the target char[] as the first argument, and the rest of the arguments are the same as printf, or scanf's (format string first, then additional args if present).
So, in your case, it would simply be:
char s[30];
int i;

scanf("%d",&i);
sprintf(s, "%d", i);

For an input of 3, s would become '3'.
With sprintf(s, "%d%d", i, i);, it would become '33'.
The reason it tried to interpret i as a pointer in your example, was that it expected a (char) pointer (the format string).


text:
Q: Analog to curl's --data-binary switch in jmeter's HTTP Request I've got a working curl request that goes as so:
curl -H "Content-Type: application/octet-stream" -X POST --data-binary @sample.bin http://127.0.0.1:31415/test

sample.bin holds binary data.
In my jmeter test plan, I have "sample.bin" stored in FILENAME. This is what I put into the body of my HTTP Request:
${__eval( ${__FileToString(${FILENAME})})}

Unsurprisingly, this isn't working out. How can I emulate the --data-binary switch?

A: Alright, after RTFM carefully yet another time, I discovered that if it is a POST or PUT or PATCH request and there is a single file whose 'Parameter name' attribute (below) is omitted, then the file is sent as the entire body of the request, i.e. no wrappers are added.
Thus, putting ${FILENAME} under file path in the "Send Files with the request" section (while leaving its paramter name empty and specifying an encoding) did the trick for me:


text:
Q: Allow all users to use chmod on a NTFS file system Issue:
I have a dual-boot PC, Ubuntu / Windows 10, that share access to a NTFS disk partition (mounted as /DATA/ in Ubuntu).
I need to avoid the "Permission denied" error when a chmod command is executed on a file in such shared partition, regardless the user calling this command. This is because I chmod is called as part of bigger procedures and the users cannot just avoid them, and when they return an error the whole procedure stops.
What I tried:
/DATA/ is now being mounted with the permissions option (mapping file is activate) and under a non-root user that has the ID of 1001, and all users are part of the the group with ID of 1003, to which rwx is allowed, i.e.:
UUID=...  /DATA  ntfs  auto,users,rw,permissions,umask=007,uid=1001,gid=1003  0  0

This solution ALMOST works. Everyone can r+w and, when the user 1001 calls chmod we don't get an error. It does not make any change indeed, but it is not a problem. The problem is that for other users the command chmod still trigger errors as they are not considered the owners of the files.

Is there an way to give ownership of the partition mounted on /DATA/ to all users? Or to the user who first logins at least?
Or at least make the chmod command never return an error?

A: Does the program that calls chmod hard-code the path to /bin/chmod?
If not, if it just runs whichever chmod program is first in the PATH, try creating a directory that contains only a symlink called 'chmod' to /bin/true.
e.g. (as root):
# mkdir /usr/local/dummy
# ln -s /bin/true /usr/local/dummy/chmod

Then set the PATH to have this directory first (PATH="/usr/local/dummy:$PATH") before running the program.  You can create a wrapper script to set the PATH and then run the program.
You might want to make a symlink for chown too.
BTW, this is stating the obvious, but you don't want this PATH setting to be the default.  You only want it when running the program that triggers the problem.

A: Contrary to popular belief, NTFS is a POSIX-compliant file system. It supports all POSIX filenames and POSIX permissions §
In Windows the POSIX permisions are stored as extended attributes in the $EA_INFORMATION stream. I don't know if the current ntfs-3g driver supports that, but it does support mapping Windows permissions to POSIX permissions via user mapping file. After configuring that ntfs-3g will handle the permission translation automatically when you run chmod.

§ That's because in the 1980s the US federal government required that certain types of government purchases be POSIX-compliant, therefore MS had to include a POSIX subsystem in Windows. As a result NTFS must also support POSIX features like special characters in filenames, hardlinks, case sensitivity, permissions... It was first used for Microsoft POSIX subsystem and later Windows Services for UNIX (SFU), Subsystem for UNIX-based Applications and finally windows-subsystem-for-linux.


text:
Q: How do I store images with Backand and Ionic? How exactly do I go about storing profile images for in the Users object?

A: You can use a Base64 encoded image to save in the user object.
Helpful articles covering this are base64-images and data-uris
Hope it helps.

A: In Backand server side add the "Backand Storage" action, with this code:
function backandCallback(userInput, dbRow, parameters, userProfile) {
  // upload file
  if (request.method == "POST"){
    var url = files.upload(parameters.filename, parameters.filedata);
    return {"url": url};
  }
  // delete file
  else if (request.method == "DELETE"){
    files.delete(parameters.filename);
    return {};
  }
}

And on the client side you can use this code in Ionic, it is based to copy the code from here: backand docs


text:
Q: Forest - how to make nodes grow in separate directions MWE:
\documentclass{article}
\usepackage{tikz}
\usepackage[edges]{forest}

\newcommand{\nodecircle}{circle,fill,outer sep=0,inner sep=1pt}

\begin{document}

    \begin{forest}
        [,\nodecircle, alias = I, s sep=0.4cm,l sep=2cm,
        [Rain]
        [Shine]
        ]
        \node[above] at (I){Nature};
    \end{forest}

\end{document}

This produces a forest with two nodes, growing downwards.
I know that to change the direction in which it grows, I have to use the grow = option command.
However, how do I make both child nodes grow in separate directions?
Specifically, I want the first child node to grow east, and the second to grow west.
However, how do I grow in two different directions from the same parent node? Specifically, I want the Rain node to be horizontally to the right (i.e east) and the Shine node to be west.
This question provides an answer which even the person who answered deemed not elegant. I was wondering if there is a newer way to do it.

A: This code works (based off Method 1 here):
\documentclass{article}
\usepackage{tikz}
\usepackage[edges]{forest}

\newcommand{\nodecircle}{circle,fill,outer sep=0,inner sep=1pt}

\begin{document}

\begin{forest}
    [,\nodecircle, alias = I, l sep=2cm, grow = east
    [,\nodecircle, before computing xy={l=3cm,s=0cm}, alias = rain]
    [,\nodecircle, before computing xy={l=-3cm,s=0cm}, alias = shine]
    ]
    \node[above] at (I){Nature};
    \node[above] at (rain){Rain};
    \node[above] at (shine){Shine};
\end{forest}

\end{document}

More elegant solutions are very welcome.


text:
Q: How do I pass data from an ASP.NET WebAPI ApiController to an ASP.NET MVC Controller? Let's say I have the following method in my ASP.NET Web API controller:
public HttpResponseMessage Get(string code1, string code2)
{
    var response = new HttpResponseMessage(HttpStatusCode.Redirect);
    response.Headers.Location = new Uri("/", UriKind.Relative);

    return response;
}

I'd like to take the values passed in for code1 and code2 and make them available to an MVC Controller (based on the redirect above, let's just assume it's the HomeController). What is the best way to do this?
A few considerations:

*

*I'm not calling the WebAPI. A 3rd party site calls the endpoint and passes along code1 and code2 (it's part of an OAuth dance and is the reason I use the redirect).

*One of the values will be an access token used later for authentication. (Yes, this would eventually use HTTPS.)

*I'd like a method that's flexible enough to pass one or more values back to the MVC Controller.

*I do not necessarily need the data to live passed the session.

Thanks!
Update: Here's a look at the final code and approach.
public async Task<HttpResponseMessage> Get(string display, string code)
{
    var auth = new AuthenticationClient();
    await auth.WebServer(_consumerKey, _consumerSecret, _callbackUrl, code);

    var url = string.Format("/?token={0}&api={1}&instance_url={2}", auth.AccessToken, auth.ApiVersion,
        auth.InstanceUrl);

    var response = new HttpResponseMessage(HttpStatusCode.Redirect);
    response.Headers.Location = new Uri(url, UriKind.Relative);

    return response;
}

A: Not sure you have much choice other than to use a query string parameter.  Path parameters don't really make much sense as there is no natural hierarchy with an auth token.


text:
Q: Не правильно отправляю данные Решил всё сам.
A: *

*Уберите return true. //читаем про return

*Атрибут задаёт значение при загрузке страницы. То, что хотите, это dialogMessage.val()

*Не .attr('disabled','true'), а .prop('disabled', true) //читаем про атрибуты, свойства...


text:
Q: how to validate firebase rule with boolean value? I have set rules in firebase to validate is admin or not, here is the rule
"rules": {
  "Users": {
    "$uid": {
      ".read": "auth != null && $uid === auth.uid ||
               (root.child('Users').child('$uid').child('admin').val() == true)",
      ".write": "auth != null && $uid === auth.uid ||
               (root.child('Users').child('$uid').child('admin').val() == true)",
    }
  }
}

The problem is that I am trying to read and write from Admin app, but I am unable to read and write from app as I have tried like this can any please help me to find out the solution....?
myViewHolder.paid.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
        reference.child(getRef(position).getKey()).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                String postKey = getRef(position).getKey();

                if (snapshot.exists()) {
                    Boolean isadmin = (Boolean) snapshot.child("admin").getValue();
                    if (isadmin == true) {

                        reference.child(postKey).child("adminScores").setValue(0);
                        Toast.makeText(view.getContext(), "Updated", Toast.LENGTH_SHORT).show();

                    } else {
                        Toast.makeText(view.getContext(), "No such data", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(view.getContext(), "data not found", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                Toast.makeText(view.getContext(), "Errors", Toast.LENGTH_SHORT).show();
            }
        });
    }
});

Here is my database stracture,

I want the solution that how could I fetch data from firebase Realtime database and after fetching data from firebase how could I check, read and write data into database....

A: The problem is the child('$uid') in this code:
(root.child('Users').child('$uid').child('admin').val() == true)

The '$uid' here is just a literal string, while you want it to be the value of the uid variable. To use that value, don't put quotes around $uid:
(root.child('Users').child($uid).child('admin').val() == true)

Also see the Firebase documentation on wildcard capture variables.


text:
Q: MDX Sorting: Show Name Of Day but sort by order of days I am new to MDX and I am struggling with ordering/sorting.  I am looking to compare sales by the day of the week (Sun, Mon, Tue...)  I have a calendar dimension set up based on a day by day table which joins to (I am using SQL verbiage, not familiar with MDX verbiage just yet) the measurements cube by a date key.   For each date key I have a column for what day, what name of day, # of the day (1-7), month #, Week#, Month Name, etc.
I want to display the Name of the day, but sort by the # of the day.
I have tried numerous iterations, but here is the simple query I am working with:
SELECT
{
  NONEMPTY([CAL Calendar].[Month Name].Members)
} ON COLUMNS,
{
  ORDER({NONEMPTY([CAL Calendar].[Week Day Name].Members)}, [CAL Calendar].[Week Day].CurrentMember.Member_Name, BDESC)
} ON ROWS
FROM [DEVICE_FACTS]
WHERE ([CAL Calendar].[Cal Date Key].[20140101]:[CAL Calendar].[Cal Date Key].[20140615], [Measures].[Widget_New % (Of AllWidgets)])

I get an error
"The MDX Function CURRENTMEMBER failed because the coordinate for the "Week Day" attribute contains a set."

I know that the error is coming from the second parameter of the ORDER() function, [CAL Calendar].[Week Day].  The query will only process results if the second parameter is from the same field as the first parameter.  But I don't want to sort by the NAME of the week, I want to sort by the order of the days in the week.

A: The WHERE clause accepts only a tuple. A Tuple is a cell of the cube, meaning, it's given by specifying 1 and only 1 member in each dimension (if no member is specified, the "All" member is assumed).
In your query, you try to slice by a set, which is a range of dates. The way to do it is to first define a member, based on an Aggregation of that set, and then using that new member on the tuple:
WITH MEMBER [CAL Calendar].[Current Period] as Aggregate([CAL Calendar].[Cal Date Key].[20140101]:[CAL Calendar].[Cal Date Key].[20140615] )
SELECT
{
  NONEMPTY([CAL Calendar].[Month Name].Members)
} ON COLUMNS,
{
  ORDER({NONEMPTY([CAL Calendar].[Week Day Name].Members)}, [CAL Calendar].[Week Day].CurrentMember.Member_Name, BDESC)
} ON ROWS
FROM [DEVICE_FACTS]
WHERE ([CAL Calendar].[Current Period], [Measures].[Widget_New % (Of AllWidgets)])

A: This is a change you should make in the SSAS multidimensional model. You have two choices:

*

*Change the key column on the week day name dimension attribute to be the weekday number, and make weekday name the name and sort by the key.  Detailed instructions are here.

*Change the orderbyattribute property on the weekday name dimension attribute to weekday number. Detailed instructions are here.


text:
Q: HUH721010AL5200 drives with different number of sectors (WD vs Dell) I ordered some spare hard drives to replace a failed hard drive in my zfs pool (raidz2 with 12 10TB hard drives on a supermicro server running Ubuntu). I made sure to order hard drives with the exact same model number as those already in the pool (HUH721010AL5200). However, it appears that the new ones I received are Dell OEM, while the original drives are Western Digital.
When I tried to replace the failed (WD) hard drive with a new one (Dell), the zfs replace command failed with the following error message: "Device is tool small".
Upon closer inspection, it appears that the two drives have a different number of sectors.
Here is the result of gdisk for my new drive:

gdisk -l /dev/sdi GPT fdisk (gdisk) version 1.0.3
Partition table scan:   MBR: protective   BSD: not present   APM: not
present   GPT: present
Found valid GPT with protective MBR; using GPT. Disk /dev/sdi:
19134414848 sectors, 8.9 TiB Model: HUH721010AL5200 Sector size
(logical/physical): 512/4096 bytes Disk identifier (GUID):
ED5CF966-DA38-2D4B-8F8E-3C3867C25E07 Partition table holds up to 128
entries Main partition table begins at sector 2 and ends at sector 33
First usable sector is 34, last usable sector is 19134414814
Partitions will be aligned on 2048-sector boundaries Total free space
is 4029 sectors (2.0 MiB)
Number  Start (sector)    End (sector)  Size       Code  Name    1
2048     19134396415   8.9 TiB     BF01  zfs-57963ba0e4d1284c    9
19134396416     19134412799   8.0 MiB     BF07

And the same thing for one of the old drives:

gdisk -l /dev/sdh GPT fdisk (gdisk) version 1.0.3
Partition table scan:   MBR: protective   BSD: not present   APM: not
present   GPT: present
Found valid GPT with protective MBR; using GPT. Disk /dev/sdh:
19532873728 sectors, 9.1 TiB Model: HUH721010AL5200 Sector size
(logical/physical): 512/4096 bytes Disk identifier (GUID):
6EEE7537-C089-544B-A500-EE19A147CA99 Partition table holds up to 128
entries Main partition table begins at sector 2 and ends at sector 33
First usable sector is 34, last usable sector is 19532873694
Partitions will be aligned on 2048-sector boundaries Total free space
is 4029 sectors (2.0 MiB)
Number  Start (sector)    End (sector)  Size       Code  Name    1
2048     19532855295   9.1 TiB     BF01  zfs-2363298e7ec25d90    9
19532855296     19532871679   8.0 MiB     BF07

As you can see, the new drive has fewer sectors --> smaller capacity --> zfs refuses to use it.
I was told to update the firmware of the hard drive, but I'm not sure how to proceed and I want to be super careful not to lose any data.
Anyone has an idea, short of returning these drives and finding/buying the version made by WD?
Thank you,
jf
EDIT: adding the result of smartctl in response to the comment by @shodanshok
For the new drive (too small):
smartctl --all /dev/sdi
smartctl 6.6 2016-05-31 r4324 [x86_64-linux-4.18.0-21-generic] (local build)
Copyright (C) 2002-16, Bruce Allen, Christian Franke, www.smartmontools.org

=== START OF INFORMATION SECTION ===
Vendor:               HGST
Product:              HUH721010AL5200
Revision:             LS17
Compliance:           SPC-4
User Capacity:        9,796,820,402,176 bytes [9.79 TB]
Logical block size:   512 bytes
Physical block size:  4096 bytes
Formatted with type 2 protection
LU is fully provisioned
Rotation Rate:        7200 rpm
Form Factor:          3.5 inches
Logical Unit id:      0x5000cca27349c848
Serial number:        2YH9KX5D
Device type:          disk
Transport protocol:   SAS (SPL-3)
Local Time is:        Wed May 12 11:15:06 2021 CDT
SMART support is:     Available - device has SMART capability.
SMART support is:     Enabled
Temperature Warning:  Enabled

=== START OF READ SMART DATA SECTION ===
SMART Health Status: OK

Current Drive Temperature:     31 C
Drive Trip Temperature:        50 C

Manufactured in week 36 of year 2018
Specified cycle count over device lifetime:  50000
Accumulated start-stop cycles:  3
Specified load-unload count over device lifetime:  600000
Accumulated load-unload cycles:  5
Elements in grown defect list: 0

Vendor (Seagate) cache information
  Blocks sent to initiator = 17381195776

Error counter log:
           Errors Corrected by           Total   Correction     Gigabytes    Total
               ECC          rereads/    errors   algorithm      processed    uncorrected
           fast | delayed   rewrites  corrected  invocations   [10^9 bytes]  errors
read:          0        0         0         0         95          0.044           0
write:         0        0         0         0          4          0.011           0
verify:        0        0         0         0        271          0.000           0

Non-medium error count:        0

SMART Self-test log
Num  Test              Status                 segment  LifeTime  LBA_first_err [SK ASC ASQ]
     Description                              number   (hours)
# 1  Background short  Completed                   -   12484                 - [-   -    -]
# 2  Background short  Completed                   -   12413                 - [-   -    -]

Long (extended) Self Test duration: 63514 seconds [1058.6 minutes]

And for comparison, one of the older drives:
smartctl --all /dev/sdh
smartctl 6.6 2016-05-31 r4324 [x86_64-linux-4.18.0-21-generic] (local build)
Copyright (C) 2002-16, Bruce Allen, Christian Franke, www.smartmontools.org

=== START OF INFORMATION SECTION ===
Vendor:               HGST
Product:              HUH721010AL5200
Revision:             A384
Compliance:           SPC-4
User Capacity:        10,000,831,348,736 bytes [10.0 TB]
Logical block size:   512 bytes
Physical block size:  4096 bytes
LU is fully provisioned
Rotation Rate:        7200 rpm
Form Factor:          3.5 inches
Logical Unit id:      0x5000cca2732326c0
Serial number:        2YGMA92D
Device type:          disk
Transport protocol:   SAS (SPL-3)
Local Time is:        Wed May 12 11:19:35 2021 CDT
SMART support is:     Available - device has SMART capability.
SMART support is:     Enabled
Temperature Warning:  Enabled

=== START OF READ SMART DATA SECTION ===
SMART Health Status: OK

Current Drive Temperature:     32 C
Drive Trip Temperature:        85 C

Manufactured in week 23 of year 2018
Specified cycle count over device lifetime:  50000
Accumulated start-stop cycles:  41
Specified load-unload count over device lifetime:  600000
Accumulated load-unload cycles:  2669
Elements in grown defect list: 0

Vendor (Seagate) cache information
  Blocks sent to initiator = 53115368926871552

Error counter log:
           Errors Corrected by           Total   Correction     Gigabytes    Total
               ECC          rereads/    errors   algorithm      processed    uncorrected
           fast | delayed   rewrites  corrected  invocations   [10^9 bytes]  errors
read:          0       41         0        41    3717572      74439.685           0
write:         0        0         0         0     605524      58839.145           0
verify:        0        0         0         0      49259          0.000           0

Non-medium error count:        0

No self-tests have been logged

Thanks again for the help.
jf

A: The two drivers probably use a different Host Protected Area (HPA) settings. Please check it by using hdparm -N /dev/yourdisk
EDIT: based on your smartctl output, the first (smaller) disk is formatted with additional sector integrity data - for example, with 520-byte physical sectors. This will naturally means a smaller portion of the available raw storage capacity can be dedicated to user data.
You should be able to re-format your disk by using sg_format - ie: issuing something similar to sg_format --format --size=512 --fmtpinfo=0 /dev/yourdisk


text:
Q: Excel VBA UDF - Fail to pass a variant array resulting from UDFas an input in second UDF I am struggling with using the array resulting from an UDF I have written as the argument to another UDF.
The function returns the #value error.
I can not figure where the problem lies.
Below is the code.
Any help / advice would be greatly appreciated ;)
This one works..
Function fTA_GetSMA(ByRef varData As Variant, ByRef lPeriod As Long) As Variant

' This function computes a simple moving average over a defined period.

Dim l As Long
Dim dSum As Double
Dim var() As Variant

    Application.Volatile
    varData = varData.Value2
    ReDim var(LBound(varData, 1) To UBound(varData, 1), 1)
    For l = LBound(varData, 1) To UBound(varData, 1)
        If l < lPeriod Then
            dSum = dSum + varData(l, 1)
        ElseIf l = lPeriod Then
            dSum = dSum + varData(l, 1)
            var(l, 1) = dSum / lPeriod
        ElseIf l > lPeriod Then
            dSum = dSum + varData(l, 1) - varData(l - lPeriod, 1)
            var(l, 1) = dSum / lPeriod
        End If
    Next l
    fTA_GetSMA = var

End Function
This one works also.
Function fTA_GetTR(ByRef varData As Variant) As Variant
' This function computes the true range of a financial time series.
' The input data must be a matrix containing O, H, L, C.
Dim var() As Variant
Dim l As Long
Dim dMaxTR As Double
Dim dMinTR As Double

    Application.Volatile
    varData = varData.Value2
    ReDim var(LBound(varData, 1) To UBound(varData, 1), 1)
    For l = LBound(varData, 1) To UBound(varData, 1)
        If l = 1 Then
            dMinTR = varData(l, 3)
            dMaxTR = varData(l, 2)
        ElseIf l > 1 Then
            dMaxTR = Application.WorksheetFunction.Max(varData(l, 2), varData(l - 1, 4))
            dMinTR = Application.WorksheetFunction.Min(varData(l, 3), varData(l - 1, 4))
        End If
        var(l, 1) = dMaxTR - dMinTR
    Next l

    fTA_GetTR = var

End Function
THIS IS THE ONE which is not working..
Function fTA_GetATR(ByRef varData As Variant, ByRef lPeriod As Long) As Variant
' This function computes the average true range of a financial time series over a given number of periods.
' the input data must be a matrix containing O, H, L, C.
' the average formula is a SMA
Dim var() As Variant
Dim varATR() As Variant

    ReDim var(LBound(varData, 1) To UBound(varData, 1), 1)
    ReDim varATR(LBound(varData, 1) To UBound(varData, 1), 1)
    var = fTA_GetTR(varData)
    varATR = fTA_GetSMA(var, lPeriod)
    Debug.Print varATR
    fTA_GetATR = varATR

End Function

A: You can only use VarData.Value2 if if Var contains a range reference: it won't work if VarData is a variant array.
Your UDFs expect Range arguments as input (because you use .Value2) but return a variant containing an array. So when you call one of them using the output from a different UDF it fails because the input is not a range.
You can detect this by setting a breakpoint and showing the Locals window to inspect what the Var variable contains.

The way to handle this is to do something like this
if IsObject(VarData) then VarData=VarData.Value2


text:
Q: Custom Jenkins scheduler We're seeing a problem with Jenkins and the scheduling of builds. Specifically, we trigger Jenkins to build a pipeline of work with every push to every branch of our git repo. On its own, the whole pipeline can take from 10 to 20 minutes to build. This can cause a problem if multiple pushes to a branch happened faster than the builds are completing. Multiplied by the twenty or thirty branches that are in development.
So, I'd like to be able to automatically deprioritise any scheduled builds on Jenkins if they are triggered on a Git commit sha that is no longer the tip of its branch. This is just one example of a factor that might indicate a desired priority. Others would be that branches with open pull requests should have higher priority than those without; or manual input in order to prioritise a PR or branch that needs feedback immediately.
Is there anyway to programmatically interact with the Queue of jobs on Jenkins and reorder it?
There is the Priority Sorter Plugin, but as far as I know this assigns each build a static priority. I would like to dynamically reprioritise items in the queue based on external info (e.g. from git).
I've found reference to two other plugins whose names indicate that they might do what I want, but I can't find any meaningful documentation on them. The former doesn't provide the options it claims to, and the latter doesn't even exist in the plugins repository. Neither seems to be maintained.
My alternatives seem to be

*

*write my own implementation of hudson.model.Queue, which seems like overkill

*maintain a separate queueing service that triggers individual jobs on Jenkins, in which case what is Jenkins even for?

Am I missing something obvious? I can't be the only person who wants more fine-grained control of Jenkins build ordering.


text:
Q: Is there an easy way to multiply two 2-digit numbers that have flipped digits? I am currently a sophomore in high school competing in UIL academics in Texas. I am competing in the number sense test. Among the questions is the need to quickly multiply 2 two digits numbers, but as with all the questions present in the test, there is always a faster way to do things. One type of question that reoccurs in each test at every competition (I've gone to 3 so far (: ) is the need to multiply two 2-digit numbers together that have their digits flipped when compared to the other number(43*34 and 56*65). I was wondering if there was a faster way to do this than to mentally multiply them. Thanks for the help!

P.S. If there is a way to improve the formatting of the question, it would be greatly appreciated if you would kindly tell me!

A: I propose the following visual scheme.
Edit: after reading the other answers, I noticed $\color{darkblue}{Arby}$ had the same idea.
To multiply the numbers $\overline{ab}\times\overline{ba}$
Start by laying the product $a\times b=\overline{pq}$ twice : $\overline{pq.pq}$
Then calculate $a^2+b^2=\overline{du}\quad$ call the unit $u$ and the decade $d$
So $\overline{ab}\times\overline{ba}=\overline{(pq+d+\varepsilon).(pq+u0)}$ where $\varepsilon=0,1$ is propagating the addition carry if any.

Examples:
$\begin{array}{l|l|l}
56\times65 & 5^2+6^2=25+36\to 6:1 & \overline{(30+6)(30+10)}=3640\\
43\times34 & 3^2+4^2=9+16\to 2:5 & \overline{(12+2)(12+50)}=1462\\
73\times37 & 3^2+7^2=9+49\to 5:8 & \overline{(21+5)(21+80)}=2\color{red}701\quad carry\\
88\times88 & 8^2+8^2=64+64\to 12:8 & \overline{(64+12)(64+80)}=7\color{red}744\quad carry
\end{array}$
Of course this is just a mean of presenting $10a^2+101ab+10b^2$, but I think it is easier to do mentally when proceeding this way.
The addition carrying may appear scary, yet in fact it happens only for $73,77,85,88,94,95,96,98,99$ and their mirrors, it is a simple addition in all other cases.

A: Let the two numbers be $xy$ and $yx$ and we want to calculate their multiplication.
There is a very simple procedure.
$1.$ Multiply both the digits.
$2.$ Multiply both the digit and add $2$ trailing zeros.
$3.$ Find the sum of the square of both the digits and $1$ trailing zero.
Add the numbers obtained in above steps and you will get the answer.
Here is an example. Suppose I want to calculate $37\cdot73$. Calculation is as follows:
$1. \ 7\cdot 3=21$
$2. \ 2100$
$3. \ 7^2 + 3^2 = 49 + 9 = 58$ after adding a zero it becomes $580$.
Answer is $21+2100+580=2701.$
P.S. You need to know the squares of all the digits from $0$ to $9$

A: Algebraically, you're asking about a shortcut for $(10a+b)(10b+a)$. That works out to: $$10a^{2}+101ab+10b^{2}$$
101 isn't hard to multiply by, especially considering that $a \times b$ will never be more than a 2-digit number in this scenario.
If you can square and slap a 0 on the end, you can handle the first and last parts.
Let's try $56 \times 65$ from your example. That's $250 + 360 + 3030 = 610 + 3030 = 3640$.
Get the idea?
There's only 41 different such 2-digit problems, so memorization might also be considered. 9 of those 41 are really just mentally squaring multiples of 11 up to 99, so that really only leaves 32 such problems.

A: Similarly from Vedic math I've seen before, the product of $a\times10+b$ and its transpose is $ab/(a^2+b^2)/ab$. So for $73\times37$ you would first multiply 3 and 7 getting and remembering 21, next $3^2+7^2=9+49=58$ which would actually be 580 (why?). You would add the 21 getting 601. Next use $3\times7=21$ again, but this time you get 2100 (again, why?). Adding 601 you get the final answer 2701.
This method generalizes well. $ab\times cd=ac/(ad+cb)/bd$ You can figure out formulas for more digits as well.
Edit: by the way, and another easy to remember trick from Vedic math is mutltiplying two 2-digit numbers with the same first digit and whose last digits sum to 10. In this case $ab\times ac$ is simply the first number times one more than the first number, followed by the product of the last numbers (using a zero in the tens digit if necessary). Easier to show than to explain. $79\times 71=(7\times 8)+09=5609$, $24\times 26=(2\times 3)+24=624$, $65\times 65=(6\times 7)+25=4225$

A: If you are like me, who knows all the squares of two digit numbers, then you can do it like this: $$36\times 63=36\times(100-36-1) = 3600-1296-36 = 2268.$$


text:
Q: SSH smoke & mirrors Situation:
I've been given SSH access to a server running LAMP (Redhat) and the brief is to migrate files and database from current live server to this new development server for testing.
Further this SSH access is contained within a Protected Workspace, so basically I have to access this companies internal network and then I can access the server there through SSH.
Issue:
SSH - WTF?? :- In the murky world of media agency smoke and mirrors alas I'm not allowed to  admit weakness and it appears that I won't have access to my familiar tools (filezilla + sequelpro)
I managed to logon to the server yesterday with Putty though have no idea how to achieve the mission:

*

*Create a database

*Import data to that database

*Upload files

*Set permission on files and folders

*At what address will I be able to view the website?

Is there a kind soul out there who can point me in the right direction?
Thanks.

A: What's the problem with FileZilla? If its available on the server - run it, SSH has nothing to do with that. You'll probably want to have X server running on your computer though, and set up port forwarding in Putty to allow applications running through SSH to connect to it.
SSH is what it is: secured shell connection. Once you gained access through SSH you can do everything you could do using local console.


text:
Q: Passing windows identity to WCF from ASP.NET I have a WCF service hosted in IIS with integrated windows authentication enabled and anonymous authentication disabled. When I try and call this service from ASP.NET, I'm getting the following MessageSecurityException:
"The HTTP request is unauthorized with client authentication scheme 'Negotiate'. The authentication header received from the server was 'Negotiate,NTLM'.]"
Any ideas?
This is my service configuration:
<system.serviceModel>
<bindings>
  <basicHttpBinding>
    <binding name="CalculatorServiceBasicHttpBinding">
      <security mode="TransportCredentialOnly">
        <transport clientCredentialType="Windows" />
      </security>
    </binding>
  </basicHttpBinding>
</bindings>
<services>
  <service name="Service.CalculatorService"
           behaviorConfiguration="CalculatorServiceBehavior">
    <endpoint name="BasicHttpEndpoint"
              address=""
              binding="basicHttpBinding"
              bindingConfiguration="CalculatorServiceBasicHttpBinding"
              contract="Framework.ICalculatorService">
    </endpoint>
  </service>
</services>
<behaviors>
  <serviceBehaviors>
    <behavior name="CalculatorServiceBehavior">
      <serviceMetadata httpGetEnabled="true"/>
      <serviceDebug includeExceptionDetailInFaults="true"/>
    </behavior>
  </serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>

This is how I'm calling the service:
var basicHttpBinding = new BasicHttpBinding();
basicHttpBinding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
basicHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
var factory = new ChannelFactory<Framework.ICalculatorService>(basicHttpBinding, new EndpointAddress("http://localhost/CalculatorService/CalculatorService.svc"));
factory.Credentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;
var proxy = factory.CreateChannel();
var emailAddress = proxy.GetMyEmailAddress();
((ICommunicationObject)proxy).Close();
factory.Close();

A: Your WCF configuration works for me so most likely you don't have IIS configured correctly for your WCF service (and possibly your ASP.NET client). Make sure the IIS site hosting your service is configured as described in this TechNet article for IIS 7. Out of the box, IIS 7 is not enabled for Windows authentication. If you're using IIS 6, there then you'll need to search to see how it's configured for Windows authentication.
Once IIS is set up correctly for your service, you need to configure the ASP.NET site that is calling your service. By default, the ASP.NET AppPool for your web site will use a local machine account (ApplicationPoolIdentity or possibly NetworkService). You'll need to change that account to an appropriate domain account. You also need to ensure your service allows that domain account to access it by either adding an Authorization Rule in IIS Manager or updating the service web.config file as described in the TechNet article.


text:
Q: Is it possible to display raw Html from database in ASP.NET MVC 3? I have a table in my db where one of the properties is an Html page (without the html, head and body tags), and I intend to put it in the middle of one of my views - say, I call a cotroller method that takes an argument, and return a view passing this html big string as the model. I searched for it (not much, I admit), and found the following method:
<%= System.Web.HttpUtility.HtmlDecode(yourEncodedHtmlFromYouDatabase) %>

That was found here in stackoverflow. When I tried a similar razor aproach, I ended up with this:
@System.Web.HttpUtility.HtmlDecode("
Test
")

That's the idea, but it didn't work quite as I planned.

A: All you need is: @Html.Raw(yourEncodedHtmlFromYouDatabase)
I'm assuming that the html in the database has been properly sanitized (or at least from a reliable source), because if not, you could be opening yourself up to cross-site scripting attacks.
The reason your approach didn't work is that Razor HTML-encodes output by default (every time you use @ to display something). Html.Raw tells Razor that you trust the HTML and you want to display it without encoding it (as it's already raw HTML).

A: You can also return a HTMLString and Razor will output the correct formatting, for example.
@Html.GetSomeHtml()

public static HtmlString GetSomeHtml()
{
    var Data = "abc
123";
    return new HtmlString(Data);
}

This will allow you to display HTML


text:
Q: Strange behavior of the progressbar To download a JSON file from an NVD site I use the following code:
#!/usr/bin/env python
from tqdm import tqdm
import time
import requests
import re
chunk_size = 1024
# Download JSON
year = input("Enter year: ")
url = requests.get('https://nvd.nist.gov/vuln/data-feeds#JSON_FEED')
for filename in re.findall("nvdcve-1.1-" + year + "\.json\.zip", url.text):
    print("\r[!] Received file: " + filename)
    r = requests.get("https://nvd.nist.gov/feeds/json/cve/1.1/" + filename, stream=True)
    total_size = int(r.headers['content-length'])
    with open("/tmp/" + filename, 'wb') as f:
        for chunk in tqdm(iterable=r.iter_content(chunk_size=chunk_size), total=total_size / chunk_size, unit='KB'):
            f.write(chunk)
        time.sleep(1)
        print("\n[+] The download is complete")

When running this application, everything works well and the file is downloaded, but a strange error appears in Pycham and the terminal:
82%|████████▏ | 2726/3342.5546875 [00:00<00:00, 1478.94KB/s]/usr/lib/python3/dist-packages/tqdm/std.py:522: TqdmWarning: clamping frac to range [0, 1]
full_bar = Bar(
100%|██████████| 3343/3342.5546875 [00:00<00:00, 3577.67KB/s]
[+] The download is complete

Tell me, please, what is the problem?
I searched all over google, but I didn't find anything useful.

A: Thanks to a tip on the resource github.com/tqdm/tqdm/issues/681 further github.com/tqdm/tqdm#redirecting-writing there i found that you can set the parameter: dynamic_ncols=True
as a result, it turned out like this:
for chunk in tqdm(iterable=r.iter_content(chunk_size=chunk_size), total=total_size / chunk_size, unit=' KB', dynamic_ncols=True):

now everything works and no error \ warning appears. Checked on several operating systems.


text:
Q: Codeigniter : how to change path for session How I can change current path from /~shinobu22/ci into /? I have problem about session lose after redirect or change page.

So, I think it's happen from my URL /~shinobu22/ (I didn't create this name MAC OS create from my username).

A: Have you tried changing the application/config/config.php file for the cookie path:
$config['cookie_path'] = '/';

Another option is to allow it site-wide:
$config['cookie_domain'] = ".example.com";


text:
Q: Roblox Studio Expected '}' (to close '{' at line 5), got 'game' I did a tutorial of AlvinBlox's Pet Egg but it's not working. I keep on getting an error saying:
Fixed:

18:34:03.253 - ServerScriptService.PetModule:7: Expected '}' (to close
'{' at line 5), got 'game'   18:34:03.255 - Requested module
experienced an error while loading

New Problem:
19:26:49.473 - ServerScriptService.PetModule:54: Expected 'then' when parsing if statement, got 'number'
This is the script:
local petModule = {}

petModule.pets = {

    ["Legendary"] = {
        game.ReplicatedStorage:WaitForChild("Pets"):WaitForChild("Dominus Ultimus");
        game.ReplicatedStorage:WaitForChild("Pets"):WaitForChild("Demonic Dominus");
    };

    ["Rare"] = {
    game.ReplicatedStorage:WaitForChild("Pets"):WaitForChild("Forgotten kraken");
        game.ReplicatedStorage:WaitForChild("Pets"):WaitForChild("Mythical Demon");
        game.ReplicatedStorage:WaitForChild("Pets"):WaitForChild("Creature of light");
    };

    ["Uncommon"] = {
        game.ReplicatedStorage:WaitForChild("Pets"):WaitForChild("Angel");
        game.ReplicatedStorage:WaitForChild("Pets"):WaitForChild("Pumkin");
    game.ReplicatedStorage:WaitForChild("Pets"):WaitForChild("Ninja");
    };

    ["Common"] = {
        game.ReplicatedStorage:WaitForChild("Pets"):WaitForChild("Dog");
        game.ReplicatedStorage:WaitForChild("Pets"):WaitForChild("Cat");
        game.ReplicatedStorage:WaitForChild("Pets"):WaitForChild("Fox");
        game.ReplicatedStorage:WaitForChild("Pets"):WaitForChild("Panda");
    };

}

-- Weighted Selection o((>ω< ))o

petModule.rarities = {

    ["Legendary"] = 7.5; -- Change the Legendary,Rare,Uncommon and Common
--   number to increase or decrease chance

    ["Rare"] = 15;

    ["Uncommon"] = 25;

    ["Common"] = 50;

}

petModule.chooseRandomPet = function()

    local randomNumber = math.random(1,100)

    local counter = 0

    for rarity, weight in pairs(petModule.rarities) do
        counter = counter + weight
        if Random number <= counter then --This is the problem

            local rarityTable = petModule.pets[rarity]
            local chosenPet = rarityTable[math.random(1,#rarityTable)]

            return chosenPet

        end
    end

end

return petModule

A: For your new problem, I saw that you typed Random number instead of random number in the if statement. So it should look like this "if random number <= counter then".


text:
Q: Arquivo php.ini, 'reseta configurações' durante start do apache Estou enfrentando uma falha com o UwAmp. Sempre que altero configurações no arquivo PHP.INI e reinicio o UwAmp, as configurações voltam para default. No Xampp ou no VampServer, o problema não ocorre.
Aparece a seguinte mensagem;

"This file has been modified by another program. Do you want to reload it?"

Alguém já passou por esse problema?


text:
Q: Coordinate transformation in the context of special relativity I was wondering how can one change from Cartesian coordinate system to some other like polar coordinates or spherical coordinates, in the context of special relativity. For example, with the four-velocity, $$V^{\mu}=\frac{\mathrm{d} x^{\mu}}{\mathrm{d} \tau},\tag{1}$$ where $\mu=0,1,2,3$, $x^0=ct$, $x^1=x$, $x^2=y$ and $x^3=z$, if I want to change to cylindrical coordinates, can I simply use the transformations $x=r\cos (\theta)$, $y=r\sin(\theta)$, $z=z$, $t=t$ and then use the chain rule with partial derivatives to work out the four velocity in spherical coordinate, or I am missing something?
Another example, in the relativistic Lagrangian, $$\mathcal{L}=-mc^2\sqrt{1-\frac{|\mathbf{v}|^2}{c^2}}-U(\mathbf{r}),\tag{2}$$ it is correct to choose $r$ and $\theta$ as generalised coordinates, substitute $|\mathbf{v}|^2=\dot{r}^2+r^2\dot{\theta}^2$, to have $$\mathcal{L}=-mc^2\sqrt{1-\frac{\dot{r}^2+r^2\dot{\theta}^2}{c^2}}-U(r),\tag{3}$$ to create a "relativistic central force problem"?
Another question that I have is how this will affect the metric tensor? And the line element?

A: You are doing it correctly.
In reference to your comment, to find the minkowski metric in cylindrical coordinates, it is easiest to transform the line element so:
$$
ds^2=g_{\mu\nu}dx^\alpha dx^\beta \tag{1},
$$
Where usually the minkowski metric is denoted by $\eta_{\mu\nu}$
Which is
$$
ds^2 = -c^2dt^2+dx^2+dy^2+dz^2 \tag{2}
$$
In Cartesian.
If you use the transformation equations and chain rule as you said, you get:
$$
ds^2=-c^2dt^2 + dr^2 + r^2d\theta^2+dz^2 \tag{3}
$$
It's easy to see that $\eta_{\mu\nu}\neq g_{\mu\nu}$ from looking at the first equation.
To summarize:
$$\eta_{\mu\nu} = Diag(-1, 1, 1, 1) \tag{4}$$
$$g_{\mu\nu}= Diag(-1, 1, r^2, 1) \tag{5}$$
With $g_{\mu\nu}$ being the minkowski metric in cylindrical coordinates.
And this usually falls under General relativity rather than special as it's concerned with the curvature of space time.


text:
Q: Multiple images gallery after a single preview HTML / CSS /JS I want to create a gallery of multiple images, from a single "preview". I'll explain better. Let's say I have 3 different images which are 3 different products. By clicking on each of these, I would like to open a gallery (different for each preview) of x images for each single product.
I tried to create it using LIGHTBOX by Lokesh Dhakar, but I can only have one image for each single preview and the gallery is only one.
I have tried several attempts, but I can't get any better
Here is my code, hope someone has some ideas

<title>IMAGE GALLERY</title>
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <link rel="stylesheet" type="text/css" href="css/lightbox.min.css">

 Image Gallery Design

body{
    font-family: sans-serif;
}
h1{
    text-align: ceter;
    color: forestgreen;
    margin: 30px 0 50px;
}

.gallery img{
    filter: grayscale(100%);
    transition: 1s;
}
.gallery img:hover{
    filter: grayscale(0);
    transform: scale(1.1);
}

A: *

*Hide the other  elements of the same set using a CSS Utility class like u-none that does display: none;

*Use  only for the first set thumbnail

lightbox.option({
  resizeDuration: 200,
  wrapAround: true
});
.u-none {display: none;}

<link href="https://cdnjs.cloudflare.com/ajax/libs/lightbox2/2.11.3/css/lightbox.css" rel="stylesheet" type="text/css" />

or wrap all the hidden set images inside a common parent
 with that u-none class .


text:
Q: Is there a reasonable way to obtain enough Eldwater to promote a unit from 4 stars to 5 stars? In order to promote an Adventurer from 4 stars to 5 stars, a total of 25,000 Eldwater is required, compared to the 2,500 required to promote from 3 stars to 4 stars. The only ways I've found that you can obtain Eldwater is through getting duplicate Adventurers in summons and the roughly 100 you get from daily endeavors.
Now the issue is that you get very little Eldwater from duplicate summons (500-1000 if I remember correctly) and only 100 from daily endeavors. Without spending any money and only doing the daily endeavors, that's 250 days worth of endeavors. If we include summons through Wyrmite, in this example tenfold summons, you maybe get 2 Adventurers per summon. Assuming both of those are duplicates, that's still only 1000-2000 Eldwater per summon. To reach the amount of Eldwater required for a promotion using only summons, that's still 13-25 tenfold summons.
The amount of Eldwater required to promote from 4 stars to 5 stars is so extreme that I feel like I'm missing some important or simpler way to obtain the resource.

A: I don't believe you're missing anything. As far as I am aware the only sources of eldwater are:

*

*Daily endeavor, participate in co-op play. Recently increased from 100 to 300.

*Getting duplicate adventurers in a summon. 150 (3*), 1000 (4*), or 3000 (5*) each.

*Selling wyrmprints or dragons. 150 (3*), 1000 (4*), or 3000 (5*) each. Note that event dragons and wyrmprints are worth 1/10 the normal value.

*Hard mode clear bonuses. You get 1500 per chapter cleared.

*Event rewards. The Kindness and Captivity raid had 2900 available, and the current A Wish to the Wind facility event has a total of 8400.

With the recent change to the daily endeavor and the amount available in the current event it's possible they realize 25,000 was a little too high a target, especially since eldwater is also necessary for the final mana circle. Either way, at this point choose wisely when choosing an adventurer to promote!