text:
Q: Android Spinner's onItemSelected executed twice when going back to Fragment I created a spinner for my Fragment that populates it with data retrieved from an HTTP callout. When the Fragment is first created, I populate the spinner with its selection choices, set its setOnItemSelectedListener and set its initial selection in onCreateView().
    stateSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
        {

            if (spinnerPosition != position)
            {
                spinnerPosition = position;
                TextView stateSelected = (TextView) view;
                String stateSelectedStr = stateSelected.getText().toString();

                LinearLayout ballotsDisplay = (LinearLayout) getActivity().findViewById(R.id.ballotsDisplay);
                ballotsDisplay.removeAllViews();

                Map<String, String> calloutParams = new HashMap<String, String>();
                calloutParams.put("state", stateSelectedStr);

                // Create and execute AsyncTask to retrieve ballots
                new RetrieveBallots().execute(calloutParams);
            }
        }

        public void onNothingSelected(AdapterView<?> parent) {
            return;
        }
    });

    // Set default selection for spinner
    int defaultState = adapter.getPosition(userState);

    if (defaultState == -1)
    {
        defaultState = 0;
    }

    stateSpinner.setSelection(defaultState);

When the Fragment is created, everything works well, the spinner position is set to its default and the spinner item is selected once as shown in the log below:
5009-5009/com.project.test D/TEST﹕ onCreateView called
5009-5009/com.project.test D/TEST﹕ stateSpinner.setSelection
5009-5009/com.project.test D/TEST﹕ onActivityCreated called
5009-5009/com.project.test D/TEST﹕ onResume called
5009-5009/com.project.test D/TEST﹕ spinner item selected

The problem occurs when I navigate away from the Fragment to another fragment (I store the fragment onto backstack). When I click back to go back to my original Fragment, the spinner seems to have its item selected twice:
5009-5009/com.project.test D/TEST﹕ onCreateView called
5009-5009/com.project.test D/TEST﹕ stateSpinner.setSelection
5009-5009/com.project.test D/TEST﹕ onActivityCreated called
5009-5009/com.project.test D/TEST﹕ onResume called
5009-5009/com.project.test D/TEST﹕ spinner item selected
5009-5009/com.project.test D/TEST﹕ spinner item selected

So I have 2 questions:
1) Why does the spinner register 2 item selection occurrences when returning to it from the Back button.
2) Is there a fix to prevent 2 item selections from occurring? Right now the fragment is being populated with duplicate data since it retrieves the data twice.
** EDIT **
After changing to stateSpinner.setSelection(defaultState, false), I would get a null Pointer exception at ballotsDisplay.removeAllViews(); seems like ballotsDisplay is set to null for some reason with that change
stacktrace:

05-15 07:25:48.303    6153-6153/com.poliseewriters.polisee E/AndroidRuntime﹕ FATAL EXCEPTION: main
      java.lang.NullPointerException
              at com.polisee.ballotmeasures.BallotMeasuresFragment$1.onItemSelected(BallotMeasuresFragment.java:287)
              at android.widget.AdapterView.fireOnSelected(AdapterView.java:882)
              at android.widget.AdapterView.selectionChanged(AdapterView.java:865)
              at android.widget.AdapterView.checkSelectionChanged(AdapterView.java:1017)
              at android.widget.Spinner.layout(Spinner.java:363)
              at android.widget.AbsSpinner.setSelectionInt(AbsSpinner.java:292)
              at android.widget.AbsSpinner.setSelection(AbsSpinner.java:269)
              at com.polisee.ballotmeasures.BallotMeasuresFragment.setStateSpinner(BallotMeasuresFragment.java:314)
              at com.polisee.ballotmeasures.BallotMeasuresFragment.onCreateView(BallotMeasuresFragment.java:201)
              at android.support.v4.app.Fragment.performCreateView(Fragment.java:1786)
              at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:953)
              at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1136)
              at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739)
              at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1499)
              at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:456)
              at android.os.Handler.handleCallback(Handler.java:605)
              at android.os.Handler.dispatchMessage(Handler.java:92)
              at android.os.Looper.loop(Looper.java:137)
              at android.app.ActivityThread.main(ActivityThread.java:4441)
              at java.lang.reflect.Method.invokeNative(Native Method)
              at java.lang.reflect.Method.invoke(Method.java:511)
              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
              at dalvik.system.NativeStart.main(Native Method)

** EDIT: Updated code to prevent onItemSelected from executing twice, needed to add null check for ballotsDisplay **
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    if (savedInstanceState != null) {
        Log.d("TEST", "bundle = " + savedInstanceState.toString());
    }

    Log.d("TEST", "onCreateView called");

    View view = (View) inflater.inflate(R.layout.fragment_ballot_measures, container, false);

    setStateSpinner(view);

    return view;
}

private void setStateSpinner(View view) {

    try {
        states = Utilities.getAllStateNames();
    }
    catch (Exception e) {
        Log.e("Error", "Error retrieving names: " + e.getMessage());
    }

    Spinner stateSpinner = (Spinner) view.findViewById(R.id.stateSpinner);

    final ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), R.layout.ballotmeasures_state_spinner, states);
    adapter.setDropDownViewResource(R.layout.ballotmeasures_state_spinner_dropdown);

    stateSpinner.setAdapter(adapter);

    stateSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        // Callback method to invoke when a state has been selected
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
        {
            Log.d("TEST", "spinner item selected");

                TextView stateSelected = (TextView) view;
                String stateSelectedStr = stateSelected.getText().toString();

                // Remove all currently displayed views in the layout
                LinearLayout ballotsDisplay = (LinearLayout) getActivity().findViewById(R.id.ballotsDisplay);
                if (ballotsDisplay != null)
                {
                    ballotsDisplay.removeAllViews();
                }

                Map<String, String> calloutParams = new HashMap<String, String>();
                calloutParams.put("state", stateSelectedStr);

                // AsyncTask to execute data retrieval
                new RetrieveBallots().execute(calloutParams);
            }

        public void onNothingSelected(AdapterView<?> parent) {
            return;
        }
    });

    // Set default selection for spinner
    int defaultState = adapter.getPosition(userState);

    if (defaultState == -1)
    {
        defaultState = 0;
    }

    Log.d("TEST", "stateSpinner.setSelection");
    stateSpinner.setSelection(defaultState, false);
}

A: The problem is the onItemSelected() callback gets called twice by Android Framework (maybe by design), the first time the view parameter is null, and the second time it is instantiated.
You cannot prevent 2 item selections from occurring, but you can check if the view variable is null, if not, do the rest things.

A: Use stateSpinner.setSelection(defaultState, false); in place of stateSpinner.setSelection(defaultState);

A: Add condition view!=null in ItemSelectedListener like this:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                        if(view!=null)
                        {//write your code
                        }
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {

                    }
                });


text:
Q: Can I implement .ToString() on C++ structs for debugging purposes? In C#, if I define a struct, I can also override ToString(). Then when I'm debugging and I add a watch or hover my mouse over an instance of the struct, the tooltip will be the computed ToString() rather than the type name of the struct.
Can I do that in C++ and/or C++/CLI somehow? That is, can I define a method as part of the struct (or do anything else) that will cause the watch-value/tooltip to display a string of my choosing? The default string rendering in Visual Studio for C/C++ is a list of all the struct's field values (or as many as can be jammed into the little box).
My types all C-style structs. (It was actually written in C before I converted the files to .cpp and fixed some type issues so I could run it in CLI.) Here's an example struct:
struct other_dollars_node
{
    struct other_dollars_node *next_other_dollars;
    override *overrides;
    long     other_dollars_id;
    tm       effective_date;
    double   amount;
}

I have very little experience with C++/CLI -- most of my experience has been with native C/C++ and C#. I'm using Visual Studio 2013.
Update: since almost all the existing code uses native C syntax, and I would prefer a solution that works without having to refactor it, the CLI aspect may be less important.

A: I think what you want to do is to provide a debugger visualization for your native structs. I did a little searching on MSDN, and found this page: Create custom views of native objects in the debugger.
Basically, what you need to do is add a file to C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\Packages\Debugger\Visualizers to tell Visual Studio how to show your structs in the debugger window. There are many examples there, and the link above provides some good explanation, though I admit I haven't tried it myself.

redpajama_set_name: RedPajamaStackExchange


text:
Q: diffrence from the max in each group I have a DataFrame like this:
df = pd.DataFrame({'id':['pt1','px1','t95','sx1','dc4','px5'],
'group':['f7','f7', 'f7','f8','f8','f8'],
'score':['2','3.3','4','8','4.9','6']})

I want to add another column and calculate the difference between each score in each group with the maximum score of that group. The expected result would be:
group id  score  score_diff
f7  pt1     2         -2
f7  px1   3.3        -.7
f7  t95     4          0
f8  sx1     8          0
f8  dc4   4.9        -3.1
f8  px5     6         -2

Would appreciate if you could please help. I want to run the code on 2000+ records. Below is my code but it gives me score difference from the previous record in each group. however, I want to calculate the score difference from max score in each group.
result = df.groupby(['fk'])['score'].diff()

A: You can use groupby and transform to generate the max for each row of the dataframe, and then use simple substraction operation to get the desired output. Here's a working example.
In [1]: df
Out[1]:
  group   id score
0    f7  pt1     2
1    f7  px1   3.3
2    f7  t95     4
3    f8  sx1     8
4    f8  dc4   4.9
5    f8  px5     6

In[2]: df['score'] = df.score.astype(float)

In[3]: df['score_diff'] = df.score - df.groupby('group')['score'].transform('max')

In[4]: df
Out[4]:
  group   id  score  score_diff
0    f7  pt1    2.0        -2.0
1    f7  px1    3.3        -0.7
2    f7  t95    4.0         0.0
3    f8  sx1    8.0         0.0
4    f8  dc4    4.9        -3.1
5    f8  px5    6.0        -2.0

Note:

*

*Please make sure that score column is a numeric (e.g: float), I used df.score.astype(float) to convert it to float.


text:
Q: Execute selection from script in Vim I'm trying to incorporate vim into my main workflow. A major sticking point for me has been interactively editing and running programs/scripts.
For example given that I'm currently vimmed into test.py
print('hello')
x = 5
y = x+2
print(y)

Without leaving vim how would I:
a) run the whole script without leaving vim
b) run just "print('hello')"

A: Commenters and the other answer have pointed out how to run a file from vim. But they glossed over some really powerful possibilities. I'd like to explain how some of those work in more detail.
The simplest possible way of running a python script in vim, is to just call the python interpreter on the file, e.g.
:!python %

or, as I prefer to do to make sure there are no unsaved changes,
:w | !python %

But it is not even necessary to have a file to run a python script in vim. The reason why is because :w != save! :w means write, and if no argument is provided, it happens to write to the file you are editing. However, you can write to STDOUT, to another file, or even to another program. So if you'd like to run your buffer as python code without having a file to save and run, you may simply do:
:w !python

This meanse write the current buffer into the external program "python". This literally just sends the contents of your buffer directly to python.
Now here's where it gets really cool. In vim, :w is an "ex command", e.g. a command that you run from the vim command line that originally came from ex, a very old line based unix text editor. The awesome thing about ex commands is that since they are all line based, you can directly state which lines you would like the command to apply to. For example:
:2w myfile.txt

will write only line two to the file "myfile.txt". You can even supply a range, e.g.
:2,7w myfile.txt

will write lines 2-7 to "myfile.txt". This means that using your example, we can run
:1w !python

to run just
print('hello')

To make this more convenient, you can use visual mode to select every line you would like to run, which will automatically fill in the right range for you. This will look like
:'<,'>w !python

To make this more convenient, I would recommend adding something like
xnoremap <leader>p :w !python<cr>

to your .vimrc. Then you can visually select whatever you want and run it as python code by typing
\p

(replace \ with whatever you have set up as your leader). You could also do
nnoremap <leader>p :w !python<cr>

or
nnoremap <leader>p :w | !python %<cr>

depending on whether you want to save to a file or not.

A: Create a function for a range as discussed in this question:
fu PyRun() range
  echo system('python -c ' . shellescape(join(getline(a:firstline, a:lastline), "\n")))
endf

Create a mapping for visual mode:
vmap <C-F6> :call PyRun()<CR>

Then you can select a range and press Control-F6. The range of lines will be executed by python. The result will be displayed in the command area.

A: You can run a program from vim using :!, i.e. :!python3 % to run your current script.
If you want to bind a key to it, another easy way would be to set makeprg to your python executable: :set makeprg=python3 and then bind a key to :make<cr>. In that case I would set up autocmds that switch the makeprg depending on the file type.
If you want to run a simple statement, you could either use Python's -c switch:
:!python3 -c 'print("Hello world")', or you could just run :!python3 without arguments to be dropped into a REPL without leaving Vim.


text:
Q: Starting background tasks with Capistrano For my RubyOnRails-App I have to start a background job at the end of Capistrano deployment. For this, I tried the following in deploy.rb:
run "nohup #{current_path}/script/runner -e production 'Scheduler.start' &", :pty => true

Sometimes this works, but most of the time it does not start the process (= not listed in ps -aux). And there are no error messages. And there is no nohup.out, not in the home directory and not in the rails app directory.
I tried using trap('SIGHUP', 'IGNORE') in scheduler.rb instead of nohup, but the result is the same.
The only way to get it work is removing the ":pty => true" and do a manual Ctrl-C at the end of "cap deploy". But I don't like this...
Are there any other chances to invoke this Scheduler.start? Or to get some more error messages?
I'm using Rails 2.3.2, Capistrano 2.5.8, Ubuntu Hardy on the Server

A: I'd like to share my solution which also works when executing multiple commands. I tried many other variants found online, including the "sleep N" hack.
run("nohup sh -c 'cd #{release_path} && bundle exec rake task_namespace:task_name RAILS_ENV=production > ~/shared/log/<rakelog>.log &' > /dev/null 2>&1", :pty => true)

This is a dup response launching background process in capistrano task but want to make sure others and myself can google for this solution.

A: With :pty => true, user shell start-up scripts (e.g. bashrc, etc.) are (usually) not loaded. My ruby program exited right after launching because of the lack of dependent environment variables.
Without :pty => true, as you described in the question, capistrano hangs there waiting for the process to exit. You'll need to redirect both stdout and stderr to make it return immediately.
run 'nohup ruby -e "sleep 5" &' # hangs for 5 seconds
run 'nohup ruby -e "sleep 5" > /dev/null &' # hangs for 5 seconds
run 'nohup ruby -e "sleep 5" > /dev/null 2>&1 &' # returns immediately. good.

If your background task still doesn't run. Try redirecting stdout and stderr to a log file so that you can investigate the output.

A: Do you want your Scheduler job to run continually in the background and get restarted when you run Capistrano?
If so, then for that I use runit  http://smarden.sunsite.dk/runit/ and DelayedJob http://github.com/Shopify/delayed_job/tree/master

*

*Install runit in the mode of not replacing init

*Add your background job as a runit service and add the log monitor for it from runit.

*Have Capistrano call sudo sv kill job_name  to kill and restart the job.

My backround job is an instance of the Rails plugin DelayedJob which handles background Rails tasks. I kill it with every Capistrano deploy so it will restart with the updated code base.
This has proved to be very reliable.
HTH,
Larry

A: If this task scheduler has a -d switch it will work. For example passenger standalone has a -d option to start it as a demonized process.
namespace :passenger_standalone do
  task :start do
    run "cd #{current_path} && passenger start -e #{rails_env} -d"
  end
  task :stop do
    run "cd #{current_path} && RAILS_ENV=#{rails_env} passenger stop"
  end
  task :restart do
    stop
    start
  end
end


text:
Q: Ubuntu 12.10 64bit fresh install, wireless issue!
Possible Duplicate:
How do I get my Broadcom BCM4313 working correctly?

Just installed a fresh Ubuntu 12.10 64bit on my laptop, run the update manager, restarted and suddenly I can't use my wifi anymore.
Ubuntu software center installed automatically the wifi additional driver as you can see in my screenshot.

If I mark the option "Do not use the device" and apply changes, restarting Ubuntu my wifi is back and I can use it.
If I run iwconfig my terminal is showing this
Now if I use Ubuntu for more than 20 minutes surfing the web my wifi it keeps to be connected but I don't receive any signal from it. Any page I try to open it simply don't open (just waiting icon). If I disconnect my wifi and connect it again, same issue, it doesn't work. The only way to make it work again is to restart Ubuntu. And the same story it happens again after   aprox. 20, 30 minutes.
WIFI device details: 03:00.0 Network controller [0280]: Broadcom Corporation BCM4313 802.11b/g/n Wireless LAN Controller [14e4:4727] (rev 01)
Thanks,
Dave

A: @chili555
I run this one using wired:
sudo apt-get install linux-headers-generic
sudo apt-get install --reinstall bcmwl-kernel-source
sudo modprobe wl

and after a restart the wifi additional driver is actived and working

If my wifi will disconnect again I'll let you know.

A: When you start and your wireless is not working, check to see if the correct module is loaded:
    lsmod | grep wl

If it is not listed, load it:
    sudo modprobe wl

Does your wireless spring to life? If so, let's get it to load automagically:
    sudo su
    echo wl >> /etc/modules
    exit

Now does your wireless start as expected on boot?


text:
Q: Link checker - need some help I got this script called "rapidshare link checker v2 php by Bigfish"
At the moment the script checks the links inside $links =  " ". I would like it to check all the megaupload links on the page.
If that doesnt work it would be ok if you guys help me make some changes so the script ignores all code except megaupload links.
The script link text

A: Inside the foreach loop add a conditional:
$pos = strpos($url,"megaupload");

if($pos === false)
{
 //skip checking
}
else
{
  //go ahead and do the checking
}


text:
Q: WebView: fatal error: unexpectedly found nil while unwrapping an Optional value I'm trying to change my WebView URL, but every time I get fatal error: unexpectedly found nil while unwrapping an Optional value.
What's wrong? Thanks.
@IBOutlet weak var myWebView: UIWebView!
override func viewDidLoad() {
    super.viewDidLoad()
    myWebView.delegate = self
    let url = NSURL (string: "http://cnn.com");
    let requestObj = NSURLRequest(url: url! as URL);
    myWebView.loadRequest(requestObj as URLRequest);

}

func changeURL(urlIncome:String) {
        let url = NSURL(string: urlIncome)
        let requestObj = NSURLRequest(url: url as! URL)
        myWebView.loadRequest(requestObj as URLRequest);
}

My AppDelegate code:
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?
var vc = ViewController()

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    UIApplication.shared.statusBarStyle = .lightContent

    OneSignal.initWithLaunchOptions(launchOptions, appId: "", handleNotificationReceived: { (notification) in

        let payload = notification?.payload
        //let fullMessage = payload?.title
        if let additionalData = payload?.additionalData, let actionURL = additionalData["url"] as? String {
            self.vc.changeURL(urlIncome: actionURL);
        }

    }, handleNotificationAction: { (result) in

        // This block gets called when the user reacts to a notification received
        let payload = result?.notification.payload
        let fullMessage = payload?.title

        NSLog(fullMessage!);

    }, settings: [kOSSettingsKeyAutoPrompt : true, kOSSettingsKeyInFocusDisplayOption : false])

    // Override point for customization after application launch.
    return true
}

A: The reason why its crashing is because you are force casting URL and URL request.
Change the below code
let url = NSURL (string: "http://cnn.com");
let requestObj = NSURLRequest(url: url! as URL);
myWebView.loadRequest(requestObj as URLRequest);

to
let url = URL(string: "http://google.com")!
myWebView.loadRequest(URLRequest(url: url))

A: This is a code I've just tested in Swift 3 with Deployment Target 9.0 set into General tab in XCode 8.2. It works smoothly, hope this helps:
your ViewController.swift:
var myUrl = ""

override func viewDidLoad() {
        super.viewDidLoad()

        if myUrl == "" {
let url = URL (string: "http://cnn.com")
webView.delegate = self
webView.loadRequest(URLRequest(url: url!))
} else {
let url = URL (string: myUrl)
webView.delegate = self
webView.loadRequest(URLRequest(url: url!))
}

    }

AppDelegate:
if let additionalData = payload?.additionalData, let actionURL = additionalData["url"] as? String {
            let mainStoryboardIpad : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
         let myVC : UIViewController = mainStoryboardIpad.instantiateViewControllerWithIdentifier("ViewController") as UIViewController
myVC.myUrl = actionURL
         self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
         self.window?.rootViewController = initialViewControlleripad
         self.window?.makeKeyAndVisible()
        }

Also remember to add App Transport Security into your Info.plist file in order to allow Arbitrary Loads (unless you've already done that :)
<key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
    </dict>


text:
Q: The... rising numbers of those out of work are adding greatly to the government's problems Which option fits best for the followings sentence:

The.........rising numbers  of those out of work are adding greatly to the
   government's problems.

*

*High

*Hard

*Steeply

*Promptly

This question also prompted another related question in my mind about a general grammar guides.
As we know, the word rising is an adjective. I'd like to ask if it is grammatically correct to use another adjective before a gerund + noun phrase.

*

*Rapid rising prices caused chaos.

*Rapid developing countries..

A: Sometimes verbs can turn into adjectives by adding -ing. These are called participles. In this example, rising is a type of adjective called a participle.
Adjectives modify nouns (see these links). Adverbs modify verbs, adjectives, and other adverbs (see this). High and hard are adjectives, so they cannot modify the participle (adjective) rising.
From the OED, promptly has these definitions:

*

*With little or no delay; immediately

*At exactly a specified time; punctually

The context of the sentence suggests that the problem is worsening over time, and the sentence does not refer to a specific time or instance. So, promptly does not fit the sentence.
The only remaining choice is steeply. Steeply is an adverb, and it can be applied to an ongoing situation.

The steeply rising numbers of those out of work are adding greatly
  to the government's problems.

In the second example, rapid is an adjective, so it cannot modify rising or developing. Adding -ly turns it into an adverb, and adverbs can modify adjectives. So, rapidly can modify rising or developing. Both of these are correct:

Rapidly rising prices caused chaos.
Rapidly developing countries...


text:
Q: TileMill for Windows After hours and days of trying to build TileMill from source on Windows, I'm more than frustrated. Is there anyone willing to share his/her up-to-date TileMill for Windows with me?
I tried to build a version a few weeks ago. But basically, I'm only interested in a version which supports setting a transparent color for raster data (which current 0.10.1 for Windows does not). It's "image-filters:colorize-alpha", that I'm interested in.


text:
Q: Facade pattern - return original object or modified original object I have e.g. object like this:
Original obj = new Original();

And I use from this object e.g. method like(this object has many methods and fields):
obj.getMeYourName();
And I would like to have similar object which is almost same but some methods return something else. I want to solve it by facade.
So, at first I want to create facade and decided if I would return direct object or modified.
What is the best way?
Something like this: ?
Original obj = new Original();

OriginalFacade obj = new OriginalFacade(Original obj, boolean getDirectObject);

OriginalFacade(Original obj, boolean getDirectObject) {
if (getDirectObject) {
    return obj //How to convert object into OriginalFacade type?
} else {
   obj.setMeYourName("Something else");
   return obj; //Howto convert object into OriginalFacade type?
}
}

So, I have 2 problems:
1, is it good solution choose original object or modified original object thru constructor with e.g. boolean getDirectObject?
2, how to easy return original object which must me mapped into OriginalFacade Object
     Must I have implement all methods from original object?

A: Actually, the facade pattern uses a common interface that is used by clients.
For instance:
public interface Facade {
    public String getMeYourName();
    public void someOtherMethod();
}

public class Original implements Facade {
    private String name;

    Original(String name) {
        this.name = name;
    }

    public String getMeYourName() {
        return name;
    }

    public void someOtherMethod() {
        // a lot of great code
    }
}

public class Modified implements Facade {
    private Facade original;
    private String otherName;

    Modified(Facade original, String otherName) {
        this.original = original;
        this.otherName = otherName;
    }

    public String getMeYourName() {
        return otherName;
    }

    public void someOtherMethod() {
        original.someOtherMethod();
    }
}

The clients should only need to see the Facade interface, and shouldn't need to care which actual implementation they are dealing with.

A: Your code demonstrates you have not understood Facade at all.
In first place Facade should be used to provide a simple interface to complex algorithms.
Second, the facade pattern allows you to access its composed objects, for example:
public class OriginalFacade{
  public Original original;
}

Unless you follow the Law of Demeter, this code is perfect valid.
Regardless, if Facade is used, you should not need to access those objects.
The following link explains a little bit of Facade
I recommend you buy and read this book

A: Facade is not the patter to be used here. It is used to make a complex interface simpler, for example, making out-of-the-box usage patterns.
In your case, why don't you just extend the Original class and overload the methods you want to behave differently?


text:
Q: Flask doing calculations returns wrong values I am trying to calculate 3 things, profit, total cost and the amount.
A user puts in the amount of coins he/she wants to spend. Each product has a buy price and a selling price, and I need to get, well profit, total cost, and amount.
I am doing that with this piece of code right here:
@app.route('/bflipper', methods=['POST', 'GET'])
def bFlipper():
    product_name = []
    f = requests.get(
        'https://api.hypixel.net/skyblock/bazaar?key=73ac0a44-4c41-4933-a9ee-b4095be2b6d2').json()
    for x in productNames:
        product_name.append(f["products"][x]["product_id"])
    if request.method == 'POST':
        userInput = request.form['coins'] # UserInput
        userInput = int(userInput)
        sell = [product['sell_summary'][0]['pricePerUnit']
                for product in f['products'].values() if product['sell_summary']]

        buy = [product['buy_summary'][0]['pricePerUnit']
               for product in f['products'].values() if product['buy_summary']]

        amount = []
        for x in range(len(buy)):
            amount.append(userInput * buy[x]) # This here calculates the amount user can buy

        total = []
        for x in range(len(buy)):
            total.append(amount[x] * buy[x])# This here calculates the total cost

        profit = []
        for x in range(len(buy)):
            sell_profit = amount[x] * sell[x]
            buy_profit = amount[x] * sell[x]
            total_profit = sell_profit - buy_profit
            profit.append(total_profit) # This here calculates the profit user will make
        return render_template("flipper.html", userInput=userInput, product_name=product_name, profit=profit, amount=amount, total=total, sell=sell, buy=buy)
    else:
        return render_template("flipper.html", product_name=product_name)

The issue is that it returns the wrong values, for example:
User puts in '123321' coins. The program will then do:
123321 / buy = amount # how many of product x he/she can buy with 123321 coins.
amount * buy = total cost # the total cost
total cost(sell) - total cost(buy) # how much profit it will make

Currently, it returns the wrong values. 123321 / 4.6 = 26808 (the amount) # 4.6 is an example of a product buy price
shows in the browser as: 727594. Which is a bit wrong! How do I fix this?

A: as roganjosh said, there is nothing to do with flask. The answer is just to debug the program and you will probably find your math mistake. Maybe open a test file and see if your math is correct there.


text:
Q: Sorting of only non Zero values in PHP Array I want to sort only those values in array which are not 0 and all 0 values key should be at bottom. so for example if our array is like this-
array
{
    [0]=>4
    [1]=>0
    [2]=>2
    [3]=>0
    [4]=>3
}

So sorted array I should get like below
array
{
    [2]=>2
    [4]=>3
    [0]=>4
    [1]=>0
    [3]=>0
}

A: Use uasort() function:
$arr = array(
    4, 0, 2, 0, 3
);

uasort($arr, function($a, $b){
    if ($a == 0) {
        return 1;
    }
    if ($b == 0) {
        return -1;
    }
    return ($a < $b) ? -1 : 1;
});

print_r($arr);

A: Using a custom sort function you could use:
function usortTest($a, $b) {

    if( $a == 0 ) return 1;
    if( $b == 0 ) return -1;

    return gmp_cmp($a, $b);

}

$test = array(4,0,2,0,3);
usort($test, "usortTest");

print_r($test);

May need to be refactored/improved, but the documentation should help you understand custom sort functions.

A: There is a PHP function call uasort that lets you define a function to sort an array and maintain array key ordering.
The return value of your defined function must be 0, -1 or 1 depending on if the values are the same, if the second value is less than the first value, or if the second value is greater than the first value, respectively.
To achieve what you are attempting would require a function similar to:
$array = array(4,0,2,0,3);
uasort($array, function($a,$b) {
    // push all 0's to the bottom of the array
    if( $a == 0 ) return 1;
    if( $b == 0 ) return -1;
    if($a == $b) {return 0; }   // values are the same
    return ($a < $b) ? -1 : 1;  // smaller numbers at top of list
});
var_dump($array);
/*
array (size=5)
  2 => int 2
  4 => int 3
  0 => int 4
  3 => int 0
  1 => int 0
*/

A: Or go with what @axiac said:
$a = array(4, 0, 2, 0, 3);

function getZeros(&$a) {
    $zeros = array();
    for($i = 0; $i < count($a); $i++) {
        if($a[$i] === 0) {
            $zeros[] = 0;
            unset($a[$i]);
        }
    }

    return $zeros;
}

$zeros = getZeros($a);
sort($a);
$a = array_merge($a, $zeros);

echo join(', ', $a);


text:
Q: Pandas and Dictionary: How to get all unique values for each key? I want to build a dictionary such that the value in the key-value pair is every unique value for that key.
Consider this example:
df = pd.DataFrame({'id': [1, 2, 3, 1, 2, 3], 'vals': ['a1', 'a2', 'a3', 'a2', 'a2a', 'a3a']})

# only yields last entry
dict(zip(df['id'], df['vals']))
# results
{1: 'a2', 2: 'a2a', 3: 'a3a'}

# expected value
{1: ['a1', 'a2'], 2: ['a2', 'a2a'], 3: ['a3', 'a3a']}

A: Use:
result = df.groupby("id")["vals"].agg(list).to_dict()
print(result)

Output
{1: ['a1', 'a2'], 2: ['a2', 'a2a'], 3: ['a3', 'a3a']}

A: You could use a dict comprehension, like so:
{k: group['vals'].tolist() for k, group in df.groupby('id')}

which outputs
{1: ['a1', 'a2'], 2: ['a2', 'a2a'], 3: ['a3', 'a3a']}

A: print(df.groupby('id')['vals'].apply(lambda x: x.tolist()).to_dict())


text:
Q: Get value or checked value in Checkbox & RadioButton - Fastest way? I'm currently working a Survey App where user choose or fill up some form with CheckBoxes and RadioButton and it will save in Firebase Real-Time database eventually once the 'Finish' button is clicked. Now I have this lines of code where I need to duplicate this type of codes in order for me to recognize which RadioGroup and RadioButton I need to read and save. It's like a loop and lengthy process for me.

On these line (in switch), I'm going to duplicate this until RadioGroup thirteenG, and I know it's kinda frustrating for me.

This will be  the result once the button is clicked.

Now my problem is not an actual problem, I just wanna know and need a help on how do I make it shortcut or make it easy so that I wouldn't duplicate it anymore, you know what I mean, so that I will also save time and a line of code.
In short, the fastest way to read a CheckBox and RadioButton value within the RadioGroup.
Thank you so much, any help will be much appreciated. Thanks again and have a good day!
I have only tried case instead of else.

A: checkbox :
You can call isChecked() on a checkbox to get its status.
if(checkbox.isChecked){
//checkbox checked
} else {

}

radiogroup:
// get selected radio button from radioGroup
int selectedId = radioGroup.getCheckedRadioButtonId();

// find the radiobutton by returned id
radioButton = (RadioButton) findViewById(selectedId);

// and you can get value from radioButton using radioButton.getText
Toast.makeText(MyAndroidAppActivity.this,
       radioButton.getText(), Toast.LENGTH_SHORT).show();


text:
Q: How to pass exact memory size to free() if void* allocation size is known As far as I know ; In c++ and c delete operator or free() function can know  the size of allocated memory from  pionter data type and delete can call the destructor automatically.
If the allocated pointer is registered using a kind of singleton static dynamic array which don't use new operator in its mechanism (ie. malloc only)
in oveloaded new pointer. this array register void* pointers and take the size of that pointer from overloaded new operator
Ex.
void * operator new (size_t sz) {
  void * m = malloc (sz);
  Dynamic_Array::get_instance()->add(m,sz) ; //registering  pointer
  return m ;
}

so My question is how to use the information about size to release the exact allocated memory that I forget to delete using the destructor of this array.
Ex.
Dynamic_Array::~Dynamic_Array() {
  int index = 0;
  while(index < storage_size) //storage_size: total number of pointers in array

 /* storage is void** array which  register
   allocated pointers as void* and use classic memset and memcpy to enlarge*/

    {
      if (storage[index] != NULL) printf("Pointer : %d was not deleted\n", storage[index]);
//how to use delete or free here to delete void* pointer  but with known size of memory
      index ++;
      }
}

Thank you.

A:
As far as I know ; In c++ and c delete operator or free() function can know the size of allocated memory from pionter data type

No. The delete operator calls the free() function; the free() function knows the size from metadata associated with the pointer somehow, for example a length word in the preceding word of memory.

and delete can call the destructor automatically.

Yes.

My question is how to use the information about size to release the exact allocated memory that I forget to delete using the destructor of this array.

You don't need to know. See above.

A: in C,
The free() function uses the data structure in the heap that surrounds the allocated memory.
That data structure includes the real start address of the allocated memory, the address of the prior memory block in the heap, and the address of the next memory block in the heap.
In general, the heap is actually two linked lists.
One is allocated memory and one is free memory.
a malloc operation takes an appropriately sized block from the free linked list and puts it into the allocated memory linked list.
This may involve breaking a larger free memory block into two smaller memory blocks, where one is moved to the allocated memory linked list and pointer are adjusted in the free memory list for the new block
A free removes the entry from the allocated memory linked list and puts it into the free linked list.
then if the free linked list contains two adjacent memory blocks, then those two memory blocks are combined into a single/larger memory block.
There are several algorithms that may be used to determine exactly which free area is broken up/moved to the allocated memory list.


text:
Q: How do I find application insights logs for specific ILogger I use asp.net core logging like this:
public class MyClass
{
    private readonly ILogger<MyClass> _logger;
    public readonly EventId NoEntryFoundEventId = new EventId(1, "No Entry Found");

    public MyClass(ILogger<MyClass> logger)
    {
        _logger = logger;
    }

    public void Foo(decimal entryId)
    {
        _logger.LogError(NoEntryFoundEventId, "MyCustomMessage\t: Entry ID: {EntryId}", entryId);
    }
}

An I setup the logger like this:
services.AddApplicationInsightsTelemetry();

loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Information)

How do I find the logs for MyClass in Azure portal?

A: As far as I understand, you want to find the log entries in Application Insights that are specifically linked to your class MyClass.
It is in the Property "CategoryName".
Getting Started with Application Insights for ASP.NET Core
Your program.cs should look something like this
public static IWebHost BuildWebHost(string[] args) =>
  WebHost.CreateDefaultBuilder(args)
    .UseStartup<Startup>()
    .UseApplicationInsights()
    .Build();

Then link the ASP.NET ILogger to Application Insights
public void Configure(IApplicationBuilder app, IHostingEnvironment env,
    ILoggerFactory loggerFactory)
{
/*...existing code..*/
        loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Warning);
}

If you set it up like this, your ILogger will automatically use the full name of MyClass as a category name, and you will see that in Application Insights under the property "CategoryName".
https://github.com/Microsoft/ApplicationInsights-aspnetcore/tree/develop/src/Microsoft.ApplicationInsights.AspNetCore/Logging/Implementation
private void PopulateTelemetry(ITelemetry telemetry,
   IReadOnlyList<KeyValuePair<string, object>> stateDictionary, EventId eventId)
    {
        IDictionary<string, string> dict = telemetry.Context.Properties;
        dict["CategoryName"] = this.categoryName;
...

See also this question for an image on how this will look in Application Insights:
Using Application Insights with ILoggerFactory

(Image is taken directly from this answer, please tell me if this is not allowed and I will remove it)
The data is added as a "custom property" and can be filtered like that in the portal:

Some more info:
https://learn.microsoft.com/en-us/azure/application-insights/app-insights-api-custom-events-metrics#properties
https://learn.microsoft.com/en-us/azure/application-insights/app-insights-analytics-tour#custom-properties-and-measurements


text:
Q: C++ Build File for Sublime Text 3 I found a build system for c++ for st3 and it is pretty good but there is a small kink it does not compile unless a .exe file with the source file name exists in the directory. Any idea on how to automate it with the build to create a file if it does not exist or continue?
"windows":
{
"cmd": ["g++", "$file_name","-o", "${file_base_name}.exe", "-lm", "-Wall", "&","start", "${file_base_name}.exe"]
},
"selector": "source.c++",
"shell": true,
"working_dir": "${file_path}"
}

A: That should run regardless, as the build will create a .exe file with the source name in the current directory. If for some reason it isn't working, remove everything on line 2 after "-Wall" so that it looks like this:
"windows":
{
"cmd": ["g++", "$file_name","-o", "${file_base_name}.exe", "-lm", "-Wall"]
},
"selector": "source.c++",
"shell": true,
"working_dir": "${file_path}"
}


text:
Q: Spark BigQuery Connector: BaseEncoding$DecodingException: Unrecognized character: 0xa I am trying to save a spark dataframe to a BigQuery table from an AWS EMR cluster. I am using the spark-bigquery-connector to do this. I have encoded my gcloud credentials service json file to Base64 from the command-line and am simply pasting the string for the credentials options. This does not work however, and causes the encoding error below. I know my json file is correct because I use it while running my script locally. What is causing this issue?
GCLOUD Service Credentials JSON File Structure
{
  "type": "service_account",
  "project_id": "<MY_PROJECT_NAME>",
  "private_key_id": "<PRIVATE_KEY_ID>",
  "private_key": "-----BEGIN PRIVATE KEY-----<LONG LIST OF CHARS>-----END PRIVATE KEY-----\n",
  "client_email": "service@project.iam.gserviceaccount.com",
  "client_id": "<CLIENT_ID>",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/<service>%40<project>.iam.gserviceaccount.com"
}

Spark Code
df \
        .drop(*cols_to_drop) \
        .write \
        .format("bigquery") \
        .option("temporaryGcsBucket", "emr_spark") \
        .option("credentials", "<LONG_BASE64_STRING>") \
        .option("project", "<MY_PROJECT_NAME>") \
        .option("parentProject", "<MY_PROJECT_NAME>") \
        .option("table", "<MY_PROJECT_NAME>:dataset.table") \
        .mode("overwrite") \
        .save()

Error:
py4j.protocol.Py4JJavaError: An error occurred while calling o137.save.
: java.lang.IllegalArgumentException: com.google.cloud.spark.bigquery.repackaged.com.google.common.io.BaseEncoding$DecodingException: Unrecognized character: 0xa
    at com.google.cloud.spark.bigquery.repackaged.com.google.common.io.BaseEncoding.decode(BaseEncoding.java:219)
    at com.google.cloud.spark.bigquery.repackaged.com.google.api.client.util.Base64.decodeBase64(Base64.java:104)
    at com.google.cloud.spark.bigquery.SparkBigQueryOptions.createCredentials(SparkBigQueryOptions.scala:47)
    at com.google.cloud.spark.bigquery.BigQueryRelationProvider$.createBigQuery(BigQueryRelationProvider.scala:125)
    at com.google.cloud.spark.bigquery.BigQueryRelationProvider$$anonfun$getOrCreateBigQuery$1.apply(BigQueryRelationProvider.scala:107)
    at com.google.cloud.spark.bigquery.BigQueryRelationProvider$$anonfun$getOrCreateBigQuery$1.apply(BigQueryRelationProvider.scala:107)
    at scala.Option.getOrElse(Option.scala:121)
    at com.google.cloud.spark.bigquery.BigQueryRelationProvider.getOrCreateBigQuery(BigQueryRelationProvider.scala:107)
    at com.google.cloud.spark.bigquery.BigQueryRelationProvider.createRelation(BigQueryRelationProvider.scala:79)
    at org.apache.spark.sql.execution.datasources.SaveIntoDataSourceCommand.run(SaveIntoDataSourceCommand.scala:45)
    at org.apache.spark.sql.execution.command.ExecutedCommandExec.sideEffectResult$lzycompute(commands.scala:70)
    at org.apache.spark.sql.execution.command.ExecutedCommandExec.sideEffectResult(commands.scala:68)
    at org.apache.spark.sql.execution.command.ExecutedCommandExec.doExecute(commands.scala:86)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:131)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:127)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeQuery$1.apply(SparkPlan.scala:155)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:152)
    at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:127)
    at org.apache.spark.sql.execution.QueryExecution.toRdd$lzycompute(QueryExecution.scala:80)
    at org.apache.spark.sql.execution.QueryExecution.toRdd(QueryExecution.scala:80)
    at org.apache.spark.sql.DataFrameWriter$$anonfun$runCommand$1.apply(DataFrameWriter.scala:676)
    at org.apache.spark.sql.DataFrameWriter$$anonfun$runCommand$1.apply(DataFrameWriter.scala:676)
    at org.apache.spark.sql.execution.SQLExecution$$anonfun$withNewExecutionId$1.apply(SQLExecution.scala:78)
    at org.apache.spark.sql.execution.SQLExecution$.withSQLConfPropagated(SQLExecution.scala:125)
    at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:73)
    at org.apache.spark.sql.DataFrameWriter.runCommand(DataFrameWriter.scala:676)
    at org.apache.spark.sql.DataFrameWriter.saveToV1Source(DataFrameWriter.scala:285)
    at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:271)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:282)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:238)
    at java.lang.Thread.run(Thread.java:748)
Caused by: com.google.cloud.spark.bigquery.repackaged.com.google.common.io.BaseEncoding$DecodingException: Unrecognized character: 0xa
    at com.google.cloud.spark.bigquery.repackaged.com.google.common.io.BaseEncoding$Alphabet.decode(BaseEncoding.java:490)
    at com.google.cloud.spark.bigquery.repackaged.com.google.common.io.BaseEncoding$Base64Encoding.decodeTo(BaseEncoding.java:974)
    at com.google.cloud.spark.bigquery.repackaged.com.google.common.io.BaseEncoding.decodeChecked(BaseEncoding.java:233)
    at com.google.cloud.spark.bigquery.repackaged.com.google.common.io.BaseEncoding.decode(BaseEncoding.java:217)
    ... 39 more

A: I believe the issue arises because the connector expects string input, but the Base64 encoding generates a bytes object. So simply utf-8 decoding the Base64 encoded bytes solved my DecodingException.
import json
import base64
creds = JSON credentials

# Dump json to str. Encode to utf-8 to get bytes. Encode bytes to Base64 bytes.
# Decode bytes to get a string
creds64 = base64.b64encode(json.dumps(creds).encode('utf-8')).decode('utf-8')

A: The issue was how the string was represented in my python script.
Representing the string in multiple lines caused the encoding error:
credentials="""
ewogICJ0eXBlIjogInNlcnZpY2VfYWNjb3VudCIsCiAgInByb2plY3RfaWQiOiAiPE1ZX1BST0pFQ1RfTkFNRT4iL
AogICJwcml2YXRlX2tleV9pZCI6ICI8UFJJVkFURV9LRVlfSUQ+IiwKICAicHJpdmF0ZV9rZXkiOiAiLS0tLS1CRU
dJTiBQUklWQVRFIEtFWS0tLS0tPExPTkcgTElTVCBPRiBDSEFSUz4tLS0tLUVORCBQUklWQVRFIEtFWS0tLS0tXG4
iLAogICJjbGllbnRfZW1haWwiOiAic2VydmljZUBwcm9qZWN0LmlhbS5nc2VydmljZWFjY291bnQuY29tIiwKICAi
Y2xpZW50X2lkIjogIjxDTElFTlRfSUQ+IiwKICAiYXV0aF91cmkiOiAiaHR0cHM6Ly9hY2NvdW50cy5nb29nbGUuY
29tL28vb2F1dGgyL2F1dGgiLAogICJ0b2tlbl91cmkiOiAiaHR0cHM6Ly9vYXV0aDIuZ29vZ2xlYXBpcy5jb20vdG
9rZW4iLAogICJhdXRoX3Byb3ZpZGVyX3g1MDlfY2VydF91cmwiOiAiaHR0cHM6Ly93d3cuZ29vZ2xlYXBpcy5jb20
vb2F1dGgyL3YxL2NlcnRzIiwKICAiY2xpZW50X3g1MDlfY2VydF91cmwiOiAiaHR0cHM6Ly93d3cuZ29vZ2xlYXBp
cy5jb20vcm9ib3QvdjEvbWV0YWRhdGEveDUwOS88c2VydmljZT4lNDA8cHJvamVjdD4uaWFtLmdzZXJ2aWNlYWNjb
3VudC5jb20iCn0=
"""

Representing the string in one line fixed my issue:
credentials="ewogICJ0eXBlIjogInNlcnZpY2VfYWNjb3VudCIsCiAgInByb2plY3RfaWQiOiAiPE1ZX1BST0pFQ1RfTkFNRT4iLAogICJwcml2YXRlX2tleV9pZCI6ICI8UFJJVkFURV9LRVlfSUQ+IiwKICAicHJpdmF0ZV9rZXkiOiAiLS0tLS1CRUdJTiBQUklWQVRFIEtFWS0tLS0tPExPTkcgTElTVCBPRiBDSEFSUz4tLS0tLUVORCBQUklWQVRFIEtFWS0tLS0tXG4iLAogICJjbGllbnRfZW1haWwiOiAic2VydmljZUBwcm9qZWN0LmlhbS5nc2VydmljZWFjY291bnQuY29tIiwKICAiY2xpZW50X2lkIjogIjxDTElFTlRfSUQ+IiwKICAiYXV0aF91cmkiOiAiaHR0cHM6Ly9hY2NvdW50cy5nb29nbGUuY29tL28vb2F1dGgyL2F1dGgiLAogICJ0b2tlbl91cmkiOiAiaHR0cHM6Ly9vYXV0aDIuZ29vZ2xlYXBpcy5jb20vdG9rZW4iLAogICJhdXRoX3Byb3ZpZGVyX3g1MDlfY2VydF91cmwiOiAiaHR0cHM6Ly93d3cuZ29vZ2xlYXBpcy5jb20vb2F1dGgyL3YxL2NlcnRzIiwKICAiY2xpZW50X3g1MDlfY2VydF91cmwiOiAiaHR0cHM6Ly93d3cuZ29vZ2xlYXBpcy5jb20vcm9ib3QvdjEvbWV0YWRhdGEveDUwOS88c2VydmljZT4lNDA8cHJvamVjdD4uaWFtLmdzZXJ2aWNlYWNjb3VudC5jb20iCn0="

As mentioned in comments, you can also use the backslash at the end of each line as well


text:
Q: When do Borel propositional theories have topologically tame truth assignments? Let $(P_r)_{r \in \mathbb{R}}$ be an $\mathbb{R}$-indexed family of propositional variables. Let $\mathcal{L}$ be the collection of all propositional sentences formed from the variables $(P_r)_{r \in \mathbb{R}}$. We can clearly regard $\mathcal{L}$ as a Polish space in a natural way. A theory $T$ is a subset of $\mathcal{L}$. A truth assignment is a function $f: \mathbb{R} \to \{\top,\bot\}$. We say that a truth assignment $f$ satisfies a theory $T$ if it does so in the standard sense of propositional logic. We'll say that a theory $T$ is Borel if it is Borel as a subset of $\mathcal{L}$.
Broadly speaking, I'm interested in characterizing when a Borel or otherwise topologically tame theory has a topologically tame completion. Three versions of this question immediately come to mind.

Questions. When is a consistent Borel theory satisfied by a Borel measurable truth assignment? A Baire measurable truth assignment? A Lebesgue measurable truth assignment?

We could of course ask similar questions about $\Sigma^1_1$ or $\Pi^1_1$ theories. In the case of $\Sigma^1_1$ theories at least, I believe we can reduce this to the Borel case, although please tell me if I've missed something in this argument.

Proposition. For any consistent $\Sigma^1_1$ theory $T$, there is a consistent Borel theory $T' \supseteq T$.

Proof. Let $C \subseteq 2^{\mathcal{L}}$ be the  collection of consistent theories. It is fairly direct to show that $C$ is $\Pi^1_1$ on $\Sigma^1_1$ (i.e., for any Polish space $X$ and any $\Sigma^1_1$ set $A \subseteq X \times \mathcal{L}$, the set $\{x \in X : A_x \in C\}$ is $\Pi^1_1$). Therefore, by the first reflection theorem there is a Borel $T' \in C$ with $T' \supseteq T$. $\square$
One thing to note about this proposition is that it means we can always extend a consistent Borel theory to a consistent Borel theory that is closed under logical consequence. For any Borel theory $T$, the set of sentences logically entailed by $T$ is $\Sigma^1_1$. This allows us to build a chain $(T_i)_{i<\omega}$ of consistent Borel theories with $T_0 = T$ such that the logical consequences of $T_{i+1}$ are contained in $T_i$. The union is then a consistent Borel theory closed under logical consequence.
I think it might be possible to make a partial statement using Lecomte's infinite arity generalization of the Kechris-Solecki-Todorcevic dichotomy. Specifically, given a Borel theory $T$, we can define a $\Sigma^1_1$ $\omega$-ary hypergraph $A \subseteq (\mathbb{R}\times \{\top,\bot\})^\omega$ where $\alpha \in (\mathbb{R} \times \{\top,\bot\})^\omega$ is in $A$ if and only if $\alpha$ is non-constant and codes a partial truth assignment that is inconsistent with $T$. This is clearly a $\Sigma^1_1$ relation. Lecomte's result then implies that if a certain Borel hypergraph does not have a Baire measurable homomorphism into our hyergraph $A$, then $A$ has a countable Borel coloring. Each monochromatic set in this coloring is an anticlique in the graph, and therefore corresponds to a partial truth assignment that is consistent with $T$. Applying the Baire category theorem or basic facts about the Lebesgue measure then implies that we can find truth assignments that are either Baire measurable in some open set or Lebesgue measurable on some set of positive measure. One could then try to iterate this argument, using the partial truth assignment to make a bigger consistent Borel theory.
At the moment I'm unsatisfied with this approach though because, whereas Lecomte's result is sharp in its own context, we're only using part of it here. Really, we have a finitary hypergraph with arbitrarily high arity edges (since consistency is a finitary property), and really we're just after an anticlique, not a coloring. I haven't been able to find anything that seemed directly relevant to me in the descriptive set theoretic literature.
Similar questions have been investigated in a first-order context by Hjorth and Nies, but I'm not sure how directly applicable their work is to my questions here.


text:
Q: Comparar dos coches (Arrays) introduciendo sus identificadores por scanner ¿Cómo podría sacar el coche con mayor número de kilómetros pidiendole al usuario que introduzca dos identificadores de los coches?.
public class Coches {

    int identificador;
    int kilometros;

    public Coches(){}

    public Coches(int identificador, int kilometros) {
        this.identificador = identificador;
        this.kilometros = kilometros;
    }

    public int getIdentificador(){
        return identificador;
    }

    public int getKilometros(){
        return kilometros;
    }
}

public class Pruebas{

     public static void main(String[] args) {

         Scanner teclado = new Scanner(System.in);

         Coches coche = new Coches();

         // Se almacenan un numero máximo de coches (4).

         Coches array [] = new Coches [4];

         int contador = 0;

         while (contador < array.length) {

             System.out.println("Introduce el identificador del coche : ");

             int identificador;
             int kilometros;

             System.out.print("Identificador :");
             identificador = teclado.nextInt();

             System.out.print("Kilometros :");
             kilometros = teclado.nextInt();

             coche = new Coches(identificador,kilometros);

             array [contador] = coche;
             contador++;

             System.out.print("Coche dado de alta");
             System.out.println();
        }

        System.out.print("Se ha alcanzado el maximo de coches.\n");

        //Busca cual realizo mayor kilometraje:
        int maxKilometros = 0;
        int indiceCoche = 0;

        for(int i = 0; i < array.length; i++){
            if(array[i].getKilometros() > maxKilometros){
                maxKilometros = array[i].getKilometros();
                indiceCoche = i;
            }
        }

        System.out.print("El coche que ha recorrido más kilometros es:"  + array[indiceCoche].getIdentificador() + " Kilometros: "+ array[indiceCoche].getKilometros() +"\n");
    }
}

Necesito que en la última parte se introduzcan dos identificadores por teclado, y una vez introducidos los compare y me digan cual es el coche de mayor autonomía.
// Comparar dos coches introduciendo sus identificadores.

System.out.print("Introduzca el primer identificador :");
System.out.print("Introduzca el segundo identificador :");

¿Cómo se podría hacer?.
Gracias, Saludos.
Gracias a Jorgesys por la respuesta en el anterior hilo.

A: Solo debes leer el identificador por teclado
int idcoche1 = teclado.nextInt(),
    idcoche2 = teclado.nextInt(),
    indiceCoche1 = -1,
    indiceCoche2 = -1;

luego usas el mismo ciclo que ya tienes:
for(int i = 0; i< array.length; i++){
    if(array[i].getIdentificador() == idcoche1){
        indiceCoche1 = i;
    }
    if(array[i].getIdentificador() == idcoche2){
        indiceCoche2 = i;
    }
}

luego comparas los coches:
if (array[indiceCoche1].getKilometros() > array[indiceCoche2].getKilometros(indiceCoche2)){
    System.out.print("El coche 1 tiene mas autonomia");
} else {
    System.out.print("El coche 2 tiene mas autonomia");
}

Recuerda hacer las validaciones correspondientes en la entrada del usuario (este es un ejemplo):
int coche = -1;
do {
    try {
        coche = teclado.nextInt();
    } catch (InputMismatchException e) {
        System.out.print("HAs ingresado algo mal");
    }
} while (coche > 1);

puedes ver mas sobre validación en este link: EL LINK
Disclaimer: Siento si hay algún error, pero no tengo ningún IDE a la mano, por lo tanto nada de esto está probado.


text:
Q: iTunesConnect Encryption of an app My question is about this question:

Is your product designed to use cryptography or does it contain or incorporate cryptography?

I don't know what to answer because my app is using the commoncrypto framework and md5 encryption. What should I answer?
Codes used in App:
 (NSString *) md5:(NSString *) input
 {
 const char *cStr = [input UTF8String];
 unsigned char digest[16];
  CC_MD5( cStr, strlen(cStr), digest ); // This is the md5 call

  NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];

  for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
  [output appendFormat:@"%02x", digest[i]];

  return  output;

 }

A: md5 is a hash function and hash functions are one-way and are not encryption.
If all you are using is a hash function the answer is No you are not using encryption.
If you are using AES, DES of other encryption, that is two-way crypto functions then the answer is YES.
Merely adding the CommonCrypto framework makes no difference, it is the usage of encryption that counts.
The only concern is any encryption in the app, there is no concern with anything done on a related server.

A: iTunes Connect does not care server-side implementation.
If you use MD5 or any other encryption mechanism in server side (but not in App side), you should choose No for the answer.


text:
Q: Changing css property dyamically using javascript .gridArea {
  margin-left: 12px;
  margin-bottom: 12px;
  height: 200px;
  width: 98%;
  overflow: auto;
  border: solid 1px #333366;
}

If I have the above css class defined in a file xyz.css and I want to change dynamically the property from "overflow" to "hidden" using JavaScript, how can it be done ?

A: you can apparently alter the css, some guy explains it Here
or you can change the elements instead of touching the css
var elements = document.getElementsByClassName('gridArea');

for (var i = 0; i < elements.length; i++) {
    elements[i].style["overflow"]="hidden";
}

or if you are willing to try jQUery(which is simply a free javascript extension, you can do it in one line:
$(".gridArea").css({"overflow":"hidden"});

A: The simplest solution to change the property for both current and future elements is to override the overflow property's value in a dynamically created stylesheet element:
var s = document.createElement('style');
s.innerHTML = '.gridArea {overflow: hidden;}';
document.querySelector('head').appendChild(s);

DEMO: http://jsbin.com/galicuto/1/edit
If you only need to change the value for a single element, you could change it via the style property:
var el = document.querySelector('.gridArea');
el.style.overflow = 'hidden';

If you want to change it for all the elements currently in the document, you can do the same, but iterate over the results given by document.querySelectorAll.

A: Using Query Selector
var el = document.querySelector('.gridArea');
el.style.overflow = "hidden";


text:
Q: How to set content of SWT Text element from an instance of a class that is called by an Eclipse command? I implemented an Eclipse view by extending ViewPart. In this particular view, I have also implemented a text input field Text and a few buttons which execute a particular Eclipse command.
For example:
IHandlerService handlerService = (IHandlerService) PlatformUI
                                .getWorkbench().getService(
                                        IHandlerService.class);
handlerService.executeCommand("com.company.commandxyz", null);

This command calls a handler which then invokes a service to hook into the DSF extensions. To be specific, I have implemented a custom CommandFactory by extending CommandFactory_6_8. This allows me to queue commands to GDB and then get the result back. However, I want to set the response in the Text field which is located located in the View where the com.example.commandxyz was invoked.
Unfortunately, I cannot pass any reference to this implementation of the DSF extension. I tried the following code to get the Eclipse view in order to subsequently set the text (which is a property of this view):
IViewPart vp = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView("com.example.myview");

However, I receive the following exception upon calling:
Exception in thread "MI RX Thread" java.lang.NullPointerException

Any idea how I can access the UI thread to retrieve the property of the view in order to set it?

A: The PlatformUI code you mention must run in the UI thread.
Use Display.asyncExec or Display.syncExec to execute code in the UI thread from some other thread.
With Java 8 use:
Display.getDefault().asyncExec(() -> { ... code to run in UI thread });

With earlier versions of Java use:
Display.getDefault().asyncExec(new Runnable() {
  public void run() {
     ... code to run in UI thread
  }
});

asyncExec runs the UI code asynchronously the next time the UI is ready to run code. syncExec runs synchronously blocking the current thread until the UI runs the code.


text:
Q: String reverse function why does the below function (f) work when i put cout in the function body but does't work when
i put cout after the function call
#include <iostream>
using namespace std;
void f(string str)
{
    int size=str.size();
    for (int i=0;i<size/2;i++)
    {
        char temp=str[i];
        str[i]=str[size-i-1];
        str[size-i-1]=temp;
    }
}
int main ()
{
    string a="abcd";
    f(a);
    cout<<a;   //output: abcd
}

#include <iostream>
using namespace std;
void f(string str)
{
    int size=str.size();
    for (int i=0;i<size/2;i++)
    {
        char temp=str[i];
        str[i]=str[size-i-1];
        str[size-i-1]=temp;
    }
    cout<<str;
}
int main ()
{
    string a="abcd";
    f(a);  //output: dcba
}

I am new to programming so i don't know concepts like pointers which i am guessing is the problem here.

A: This is because the variable a is not modified by the function void f(string str). f takes a copy of the string and then uses that copy to reverse the string. This means that the original string a is unchanged.
If you want to make it so that f does not take a copy, you can pass the string by reference using the & operator.
void f(string& str) will use the same string for a and str as they will be referring to the same data in memory.


text:
Q: Find $\int_0^1g(x)dx$, $\,\,g(x) = \int_0^x\frac{f(t)f^n(t)-(f'(t))^2}{f^2(t)}dt$, $\,\,f(x) = \frac{1}{1+x^4}$ $$f:\mathbb R \to \mathbb R, \,f(x) = \frac{1}{x^4+1} $$
$$g:\mathbb R \to \mathbb R \, g(x) = \int_0^x\frac{f(t)f^n(t)-(f'(t))^2}{f^2(t)}dt$$
$$Find\int_0^1g(x)dx$$
So far I only realized $g(x)$ can be rewritten as:
$$g(x) = \int_0^x{f^{n-1} -\frac{(f'(t))^2}{f^2(t)}}dt$$
$$g(x) = \frac{f^n(x) - f^n(0)}{n} - \int_0^x{\frac{(f'(t))^2}{f^2(t)}}dx$$
$$g(x) = \frac{1}{n}\bigg(\frac{1}{(1+x^4)^n} + 1\bigg) - \int_0^x{\frac{(f'(t))^2}{f^2(t)}}dx$$
I don't have any clue what to do next, would greatly appreciate any help :).


text:
Q: ¿Cömo cambiar el estilo de un div que se crea dinámicamente? Hola tengo varios divs que se crean dinámicamente, es decir, no están inicialmente en el código sino que con angular ng-repeat se crean varios divs con la clase box-header quisiera cambiar sus propiedades cada vez que le hago clic pero no funciona,  el  código en otra plantilla HTML si funciona bien pero en este caso no. ¿Me podría decir alguien que estoy haciendo mal?
mi script.js dice lo siguiente;
    var open = 0;
$('#este').click(function () {
    if (open === 0) {
        $('#este').css({
            'border-radius': '0px 0px 43px 43px / 0px 22px 40px 40px',
            'background-color': '#555454',
            'color': 'white',
            'margin-top': '5%',
            'padding': '3px',
        });
        open = 1;
    }  else {
        if (open===1) {
            $('#este').css({
                'border-radius': '0px 0px 43px 43px / 0px 22px 40px 40px;',
                'background-color': 'white',
                'color': 'black',
                'margin-top': '5%',
                'padding': '3px'
            });
            open=0;}
    }
});

Y el HTML que genera las listas:

//aqui hago click para cambiar propiedad -->

 {{item.documentos}}

                                <input type="text" id="twit" ng-model="searchinput" readonly value="{{item.descripcion}}" placeholder="{{item.descripcion}}" cloack  />

                                                {{item.nombre}}

A: Puedes hacer uso de la directiva ng-click
 //aqui hago click para cambiar propiedad

Dentro de tu Controller
angular.module('myApp', [])
.controller('lista_claves', ['$scope', function($scope) {
    $scope.open = 0;
    $scope.myFunc = function($event,item) {
    var elem = $event.currentTarget || $event.srcElement;
    if ($scope.open === 0) {
               $(elem).css({
                  'border-radius': '0px 0px 43px 43px / 0px 22px 40px 40px',
                  'background-color': '#555454',
                  'color': 'white',
                  'margin-top': '5%',
                  'padding': '3px',
          });
    $scope.open = 1;
    }  else {
        if ($scope.open===1) {
            $(elem).css({
                'border-radius': '0px 0px 43px 43px / 0px 22px 40px 40px;',
                'background-color': 'white',
                'color': 'black',
                'margin-top': '5%',
                'padding': '3px'
            });
             $scope.open=0;
         }
    };
}]);

A: De acuerdo a lo que logro entender según tu pregunta lo que quieres hacer es agregar propiedades css a un item cuando este true o en su defecto false, para esto yo te recomiendo hacer uso de ng-class de angularJs agregando una clase cuando sea true o agregando otra cuando sea false, o no agregar ninguna clase, a continuación veras un ejemplo para que te hagas una IDEA de como funciona y como puedes trabajarlo, lo que no entiendas me preguntas.

var app = angular.module("myApp", []);

app.controller("myCtrl", function ($scope, $http) {

$scope.claves =  [
        {
            "documentos": "Sin clasificar (1)",
            "clave": "0",
            "descripcion": "Sin clasificar"
        },
        {
            "documentos": "Pedimento Aduanal (3)",
            "clave": "2",
            "descripcion": "Pedimento Aduanal"
        },
        {
            "documentos": "Facturas de Gastos (A cuenta de Terceros) (4)",
            "clave": "3",
            "descripcion": "Facturas de Gastos (A cuenta de Terceros)"
        },
        {
            "documentos": "Cuentas de Gastos MOZ (2)",
            "clave": "4",
            "descripcion": "Cuentas de Gastos MOZ"
        },
        {
            "documentos": "COVE (4)",
            "clave": "5",
            "descripcion": "COVE"
        },
        {
            "documentos": "Facturas de Mercancías (Compra de Mercancias) (1)",
            "clave": "6",
            "descripcion": "Facturas de Mercancías (Compra de Mercancias)"
        },
        {
            "documentos": "Guía aérea, conocimiento de embarque o carta de porte (1)",
            "clave": "25",
            "descripcion": "Guía aérea, conocimiento de embarque o carta de porte"
        }
    ]
 });
<!DOCTYPE html>

                            ejemplo

Lo que hice fue agregar un ng-init e iniciar una variable en false item.open = false, luego en el div hijo del ng-repeat agregamos el ng-click ng-click="item.open = !item.open" donde decimos que cuando le demos click a un item este va cambiar de false a true y aplicara la clase item-open, esto sucede en el ng-class "{'item-open' : item.open}" donde decimos que agregue la clase item-open cuando item.open sea true y si es false pues no agregue ninguna clase.
Otra cosa que puedes hacer es agregar el item-close al ng-class de esta manera ng-class="{'item-open' : item.open, 'item-close' : !item.open}" pero entonces todos los div del ng-repeat van a tener la clase item-close ya que la variable item.open es false ya que así lo tenemos en el ng-init="item.open = false".Puedes revisar la documentación del ng-class

A: Para utilizar eventos jQuery con elementos dinamicos, debes usar on().  Algo asi:
$('#oficinas').on('click', '.box-header', function () {
  if (open === 0) {
    $('#este').css({
        'border-radius': '0px 0px 43px 43px / 0px 22px 40px 40px',
        'background-color': '#555454',
        'color': 'white',
        'margin-top': '5%',
        'padding': '3px',
    });
    open = 1;
  }  else {
    if (open===1) {
        $('#este').css({
            'border-radius': '0px 0px 43px 43px / 0px 22px 40px 40px;',
            'background-color': 'white',
            'color': 'black',
            'margin-top': '5%',
            'padding': '3px'
        });
        open=0;}
  }
});


text:
Q: Extract numbers, dot and comma using regex match I am trying to extract amount $50,000.00 from string which has number, comma and dot. My code is below:
var amount = '$50,000.00Fund Transfer to XXXX9090 Ref #0675'.match(/[^0-9,.]/);

A: You can use [\d,]+\.\d+ in case dot is required in the number, like: [\d,]+\.\d+.
In case dot is optional - you may use [\d,]+(\.\d+)?,
but in this case you may capture undesired values like: 9090 and 0675.
As result your code must looks like this:
var amount = '50,000.00Fund Transfer to XXXX9090 Ref #0675'.match(/[\d,]+\.\d+/)[0]

In case this number must be the most left number - like this:
var amount = '50,000.00Fund Transfer to XXXX9090 Ref #0675'.match(/^[\d,]+\.\d+/)[0]

A: ^ at a start of a charactor class means not. And also you are missing +.
Meaning of your expression is not a digit or , or . and only once
Answer is
/^[\d,\.]+/ or /^[0-9,\.]+/

A: Try this one - \d{1,3}(,\d{3})*\.\d{2}. It should match only those numbers which are properly formatted with decimal separator (dot .) and thousands separator (comma ,):

const amount = '50,000.00Fund Transfer to XXXX9090 Ref #0675'.match(/\d{1,3}(,\d{3})*\.\d{2}/)[0];

console.log(amount)

You can also match numbers with a dollar sign at the beginning, but you need to escape that character in your regexp, since it has a special meaning (end of string):
\$\d{1,3}(,\d{3})*\.\d{2}


text:
Q: jquery div positioning Can someone help with this jsfiddle?
http://jsfiddle.net/4Ns44/
Intended purpose: when the page is scrolled down, link expands in the view port, This works good. But as we scroll up, I would like the expand window to stop where it started. ie, below the header div. Right now, the position:fixed is causing it to remain at top even after the header div becomes visible.
some help with position:fixed

A: If I understand what you're trying to do, I think you want to check for when scrollTop is less than the original position of #expand. In particular:
var minY = $('#header').height();

In the scroll handler:
// this will reset to the original position
if (top < minY) {
    $expand.css({position: "absolute", top: ''});
}

Resulting in this: http://jsfiddle.net/4Ns44/3/
var minY = $('#header').height();
var $expand = $("#expand");

$(window).scroll(function () {

    var top = $(window).scrollTop();

    if($expand.css("position") === "fixed") {

        if(top > expandY) {
            $expand.css({position: "absolute", top: expandY});
        } else if (top < minY) {
            $expand.css({position: "absolute", top: ''});
        }
    }
    else {
        if (top < minY) {
            $expand.css({position: "absolute", top: ''});
        } else if(top < expandY) {
            $expand.css({position: "fixed", top: 0});
        }
    }
});

This is if I understand what you're trying to do...


text:
Q: Error when run flowvisor in Ubuntu 18 to make multiple floodlight controller? I tried to run flowvisor in mininet,

*

*first I create custom topology in mininet

*second I wrote this command
sudo -u flowvisor fvconfig generate /etc/flowvisor /config.json

the error was appeared

sudo :unknown user :flowvisor
sudo :unable to initialize policy plugin


text:
Q: Is "no" omitted in a series of coordinations?
Because of Oklahoma!'s enormous subsequent influence, its novelties—no opening ensemble number, chorus girls in long dresses, dancers who don't appear until late in the first act, the integrated score—have lost some of their original lustre.

Is "no" is omitted for the following juxtapositions? So in fact the sentence could be written as " no opening ensemble number, (no) chorus girls in long dresses, (no) dancers who don't appear until late in the first act, (no) the integrated score"?


text:
Q: Why jest.spyOn does not find my component function? Let's say I have this simple React (TypeScript) component:
function Header(): JSX.Element {
   const initialItemIndex = useInitialItemIndex();
   const [currentItem, setCurrentItem] = useState(initialItemIndex);

   function onChangeFunc(event: Event, itemNum: number): void {
       setCurrentItem(itemNum);
   }

   return (

         <Tabs value={currentTab} onChange={onChangeFunc}>
            <Tab label="A" />
            <Tab label="B" />
         </Tabs>

   );
}

I want to test (Jest, TypeScript) that the Tabs.onChange is calling the onChangeFunc. How should I test it? Something like:
const wrapper = shallow();
const spyFunc = jest.spyOn(Header, 'onChangeFunc');
wrapper.find('Tabs').simulate('change');
expect(spyFunc).toBeCalled();

I'm getting error, about the second parameter in the spyOn:
TS2345: Argument of type '"onChangeFunc"' is not assignable to parameter of type 'never'.

What am I doing wrong?

A: As @jonrsharpe said, the onChangeFunc defined inside the Header SFC, it's private. We can't access it so that we can't spy on it. You should test it by trigger the change event.
E.g.
index.tsx:
import React from 'react';

export const Tabs = ({ onChange, children }) => <select onChange={onChange}>{children}</select>;
const Tab = ({ label }) => <option value={label}>{label}</option>;

export function Header(): JSX.Element {
  function onChangeFunc(event: Event, tab: number): void {
    console.log('onchange');
  }

  return (

      <Tabs onChange={onChangeFunc}>
        <Tab label="A" />
        <Tab label="B" />
      </Tabs>

  );
}

index.test.tsx:
import { Header } from './';
import React from 'react';
import { mount } from 'enzyme';

describe('60927553', () => {
  it('should pass', () => {
    const logSpy = jest.spyOn(console, 'log');
    const wrapper = mount();
    const mEvent = {};
    wrapper.find('select').simulate('change', mEvent);
    expect(logSpy).toBeCalledWith('onchange');
  });
});

unit test results with 100% coverage:
 PASS  stackoverflow/60927553/index.test.tsx (7.617s)
  60927553
    ✓ should pass (57ms)

  console.log node_modules/jest-environment-enzyme/node_modules/jest-mock/build/index.js:866
    onchange

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------|---------|----------|---------|---------|-------------------
All files  |     100 |      100 |     100 |     100 |
 index.tsx |     100 |      100 |     100 |     100 |
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        8.86s, estimated 9s


text:
Q: In android, is it possible to get the current http url when the youtube app is playing video? My goal is to create an app that can know the name of the current video playing in youtube app in android. I have found it is impossible(possible?). So maybe there is a way for me to know the current video's url ( then maybe I can obtain the video id from the url).
Is it possible? I have check the youtube process's proc folder, but I didn't find such information. Because the youtube app doesn't use an browser, is it possible for me to know such information? thx:>


text:
Q: webview activity links not opens in browser inside the webpage of my webview activity their is download link I want the links when clicks open in dfault browser to start download
how to make all links inside the webview activity opens in browser? pls help
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class C13 extends Activity {
    private WebView webView;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_c13);

        webView = (WebView) findViewById(R.id.webc13);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl("https://sites.google.com/site/abdwou/1st-bio");
        webView.setWebViewClient(new WebViewClient());
    }

}

A: WebView webview = (WebView) findViewById(R.id.webview);
webview.loadUrl(http://www.playbuzz.org);

you dont have to include this code // webview.setWebViewClient(new WebViewClient()); instead u need to use d code below
webview.setWebViewClient(new WebViewClient(){
    public boolean shouldOverrideUrlLoading(WebView view, String url) {

        String url2="http://www.playbuzz.org/";
         // all links  with in ur site will be open inside the webview
         //links that start ur domain example(http://www.example.com/)
        if (url != null && url.startsWith(url2)){
            return false;
            }
       // all links that points outside the site will be open in a normal android browser
      else  {
            view.getContext().startActivity(
            new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
            return true;
            }
    }
});


text:
Q: ForeignKeyRawIdWidget, how to implement this functionality in the user model? in django admin there is a functionality for adding, editing and deleting a record in the associated model using ForeignKeyRawIdWidget, how to implement this functionality in the user model?
This is the code that is used in the django admin
from django import forms
from django.urls import reverse
from django.utils.http import urlencode
from django.core.exceptions import ValidationError
from django.urls.exceptions import NoReverseMatch
from django.utils.text import Truncator

def url_params_from_lookup_dict(lookups):
    """
    Convert the type of lookups specified in a ForeignKey limit_choices_to
    attribute to a dictionary of query parameters
    """
    params = {}
    if lookups and hasattr(lookups, 'items'):
        for k, v in lookups.items():
            if callable(v):
                v = v()
            if isinstance(v, (tuple, list)):
                v = ','.join(str(x) for x in v)
            elif isinstance(v, bool):
                v = ('0', '1')[v]
            else:
                v = str(v)
            params[k] = v
    return params

class ForeignKeyRawIdWidget(forms.TextInput):
    """
    A Widget for displaying ForeignKeys in the "raw_id" interface rather than
    in a <select> box.
    """
    template_name = 'admin/widgets/foreign_key_raw_id.html'

    def __init__(self, rel, admin_site, attrs=None, using=None):
        self.rel = rel
        self.admin_site = admin_site
        self.db = using
        super().__init__(attrs)

    def get_context(self, name, value, attrs):
        context = super().get_context(name, value, attrs)
        rel_to = self.rel.model
        if rel_to in self.admin_site._registry:
            # The related object is registered with the same AdminSite
            related_url = reverse(
                'admin:%s_%s_changelist' % (
                    rel_to._meta.app_label,
                    rel_to._meta.model_name,
                ),
                current_app=self.admin_site.name,
            )

            params = self.url_parameters()
            if params:
                related_url += '?' + urlencode(params)
            context['related_url'] = related_url
            context['link_title'] = _('Lookup')
            # The JavaScript code looks for this class.
            context['widget']['attrs'].setdefault('class', 'vForeignKeyRawIdAdminField')
        else:
            context['related_url'] = None
        if context['widget']['value']:
            context['link_label'], context['link_url'] = self.label_and_url_for_value(value)
        else:
            context['link_label'] = None
        return context

    def base_url_parameters(self):
        limit_choices_to = self.rel.limit_choices_to
        if callable(limit_choices_to):
            limit_choices_to = limit_choices_to()
        return url_params_from_lookup_dict(limit_choices_to)

    def url_parameters(self):
        from django.contrib.admin.views.main import TO_FIELD_VAR
        params = self.base_url_parameters()
        params.update({TO_FIELD_VAR: self.rel.get_related_field().name})
        return params

    def label_and_url_for_value(self, value):
        key = self.rel.get_related_field().name
        try:
            obj = self.rel.model._default_manager.using(self.db).get(**{key: value})
        except (ValueError, self.rel.model.DoesNotExist, ValidationError):
            return '', ''

        try:
            url = reverse(
                '%s:%s_%s_change' % (
                    self.admin_site.name,
                    obj._meta.app_label,
                    obj._meta.object_name.lower(),
                ),
                args=(obj.pk,)
            )
        except NoReverseMatch:
            url = ''  # Admin not registered for target model.

        return Truncator(obj).words(14), url

html
{% load i18n static %}

    {{ rendered_widget }}
    {% block links %}
        {% spaceless %}
        {% if not is_hidden %}
        {% if can_change_related %}

        {% endif %}
        {% if can_add_related %}

        {% endif %}
        {% if can_delete_related %}

        {% endif %}
        {% endif %}
        {% endspaceless %}
    {% endblock %}

This is the code I am trying to implement
forms.py
from django import forms

from .models import JournalWork, TypeWork
from django.contrib.admin.sites import site
from django.contrib.admin.widgets import ForeignKeyRawIdWidget

class JournalWorkForm(forms.ModelForm):
    class Meta:
        model = JournalWork
        fields = '__all__'

    widgets = {
            'type': ForeignKeyRawIdWidget(JournalWork._meta.get_field('type').remote_field, site),
        }

views.py
from django.shortcuts import render, redirect

from .models import JournalWork
from .forms import JournalWorkForm

def journal_records(request):
    records = JournalWork.objects.all()
    context = {
        'records': records
    }

    return render(request, 'journals/index.html', context)

def add_record_journal_work(request):
    if request.method == 'POST':
        form = JournalWorkForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('journal:journal')
    else:
        form = JournalWorkForm()

    context = {
        'form_journal_work': form
    }

    return render(request, 'journals/add_form.html', context)

add_form.html
{% extends 'base.html' %}

{% block title %}
    {% if is_edit %}
        Редактировать запись
    {% else %}
        Добавить запись
    {% endif %}
{% endblock %}
{% block content %}

                        {% if is_edit %}
                            Редактировать запись
                        {% else %}
                            Добавить запись
                        {% endif %}

                        {% if form.errors %}
                            {% for field in form %}
                                {% for error in field.errors %}

                                        {{ error|escape }}

                                {% endfor %}
                            {% endfor %}
                            {% for error in form.non_field_errors %}

                                    {{ error|escape }}

                            {% endfor %}
                        {% endif %}

                        <form method="POST" action="{{ request.get_full_path }}">
                            {% csrf_token %}
                            {{ form_journal_work.as_p}}
                            {% comment %} {% for field in form_journal_work %}

                                            {{ field.label }}
                                            {% if field.field.required %}
                                                *
                                            {% endif %}

                                        {{ field }}
                                        {% if field.help_text %}

                                                {{ field.help_text|safe }}

                                        {% endif %}

                            {% endfor %} {% endcomment %}

                                <button type="submit" class="btn btn-primary">
                                {% if is_edit %}
                                    Сохранить
                                {% else %}
                                    Добавить
                                {% endif %}
                                </button>

                        </form>

{% endblock %}

I don't have to use this functionality, I want to implement a similar one using django or write my own I need help


text:
Q: Visualforce Page Input Field Focus jQuery I am trying to set the focus on my visualforce page input field.  I've tried using:
jQuery(document).ready( function() {
var myElement = document.getElementById("{!$Component.caretask.form.op.pb.pbs1.subject}");
 jQuery(myElement).focus();

I've also tried as suggested here set Focus on Visualforce Page :
var myElement = document.getElementById("{!$Component.caretask.form.op.pb.pbs1.subject}");
window.addEventListener("load", function() {
setTimeout(function() {
    document.querySelector(myElement).focus();
}, 100);  // 0.1 seconds after load time.
);

However neither seem to be working.  I'm probably missing something simple?  Below is my page:
<apex:page standardController="Task" extensions="SaveAndReturnTaskExtension" tabStyle="Account" id="caretask">
<apex:form id="form" >
    <apex:outputPanel id="op">
        <apex:pageBlock id = "pb" >
            <apex:pagemessages />
            <apex:pageBlockButtons >
                <apex:commandButton value="Save" action="{!saveAndReturn}"/>
                <apex:commandButton value="Cancel" action="{!cancel}"/>
            </apex:pageBlockButtons>
            <apex:pageBlockSection id="pbs1" columns="2" title="Task Information">
                <apex:inputField id="owner" value="{!Task.OwnerId}" />
                <apex:inputField value="{!Task.WhatId}" />
                <apex:inputField id="subject" value="{!Task.Subject}" />
                <apex:inputField value="{!Task.WhoId}"/>
                <apex:repeat value="{!$ObjectType.Task.FieldSets.CARETaskInformation}"  var="f">
                <apex:inputField value="{!Task[f]}" required="{!OR(f.required, f.dbrequired)}"/>
                </apex:repeat>
                <apex:outputText />
                <apex:inputField value="{!Task.CallDisposition__c}">
                <apex:actionSupport event="onchange" rerender="t1" />
                </apex:inputField>
                <apex:inputField value="{!Task.Description}" style="width: 600px; height: 200px" />
                <apex:inputField value="{!Task.LiveCallVMEmailColdReason__c}" rendered="{!IF( Task.CallDisposition__c == 'Live Call/VM/Email (Cold)', true, false )}" >
                </apex:inputField>
            </apex:pageBlockSection>
            <apex:pageBlockSection title="Appointment">
                <apex:repeat value="{!$ObjectType.Task.FieldSets.Appointment}"  var="apt">
                <apex:inputField value="{!Task[apt]}" required="{!OR(apt.required, apt.dbrequired)}"/>
                </apex:repeat>
            </apex:pageBlockSection>
            <apex:pageBlockSection title="Additional Information">
                <apex:repeat value="{!$ObjectType.Task.FieldSets.AdditionalInformation}"  var="add">
                <apex:inputField value="{!Task[add]}" required="{!OR(add.required, add.dbrequired)}"/>
                </apex:repeat>
            </apex:pageBlockSection>
            <apex:pageBlockSection title="From Template">
                <apex:repeat value="{!$ObjectType.Task.FieldSets.FromTemplate}"  var="tem">
                <apex:inputField value="{!Task[tem]}" required="{!OR(tem.required, tem.dbrequired)}"/>
                </apex:repeat>
            </apex:pageBlockSection>
            <apex:pageBlockSection title="Other Information">
                <apex:repeat value="{!$ObjectType.Task.FieldSets.OtherInformation}"  var="oi">
                <apex:inputField value="{!Task[oi]}" required="{!OR(oi.required, oi.dbrequired)}"/>
                </apex:repeat>
            </apex:pageBlockSection>
            <apex:pageBlockSection title="System Information">
                <apex:repeat value="{!$ObjectType.Task.FieldSets.SystemInformation}"  var="si">
                <apex:outputField value="{!Task[si]}" />
                </apex:repeat>
            </apex:pageBlockSection>
            <apex:pageBlockSection title="Dial Source Info">
                <apex:repeat value="{!$ObjectType.Task.FieldSets.DialSourceInfo}"  var="dsi">
                <apex:inputField value="{!Task[dsi]}" required="{!OR(dsi.required, dsi.dbrequired)}"/>
                </apex:repeat>
            </apex:pageBlockSection>
            <apex:pageBlockSection title="Recurrence">
                <apex:repeat value="{!$ObjectType.Task.FieldSets.Recurrence}"  var="rec">
                <apex:inputField value="{!Task[rec]}" required="{!OR(rec.required, rec.dbrequired)}"/>
                </apex:repeat>
            </apex:pageBlockSection>
            <apex:pageBlockSection title="Reminder">
                <apex:repeat value="{!$ObjectType.Task.FieldSets.Reminder}"  var="rem">
                <apex:inputField value="{!Task[rem]}" required="{!OR(rem.required, rem.dbrequired)}"/>
                </apex:repeat>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:outputPanel>
</apex:form>
<script>
 jQuery(document).ready( function() {
 var myElement = document.getElementById("{!$Component.caretask.form.pb.subject}");
 jQuery(myElement).focus();
</script >

A: Just use and ends with selector
jQuery("[id$=subject]").focus();

Much easier to select that way as long as you are careful no other ids end with subject

A: Have you tried just using "{!$Component.subject}"?
Also you could add an extra data- attribute on the element and query for that instead (it doesn't have to be "role", it can be anything):
<apex:inputField id="subject" value="{!Task.Subject}" html-data-role="subject" />

Then to find it with jQuery:
var myElement = jQuery('[data-role=subject]');

A: I created a simple fiddle HERE that should outline a very simple way to do this. you don't need anything really special just because it is a visual force component, just be sure that you have the id set and be sure that of course no others are similar


text:
Q: Is it possible to add the monitor from the second GPU to the same x screen as the first GPU? Manjaro. Gnome. Nvidia.
I have two GPUs (ASUS 1070 both).

Both GPUs and monitors are detected, but I cannot add the second monitor (the smallest, orange on the screenshot) to the X Screen 0. I can only create new X screen 1, but even if I select X Screen 1, I cannot save settings. (second screenshot)

The current settings cannot be completely applied due to one or more of the following reasons:

*

*The location of an X screen has changed

*The location type of an X screen has changed

*The color depth of an X screen has changed

*An X screen has been added or removed.

*Xinerama is being enabled/disabled.

  For all the requested settings to take effect, you must save the configuration to the X config file and restart the X server.
Apply What Is Possible Cancel

I was trying a lot of things, but nothing seems to help. So, I even have a conclusion that it is not possible. I am not experienced in Xorg, etc. at all, so I think there should be some solution.
My xorg.conf
# nvidia-xconfig: X configuration file generated by nvidia-xconfig
# nvidia-xconfig:  version 410.57

Section "ServerLayout"
    Identifier     "Layout0"
    Screen      0  "Screen0"
    InputDevice    "Keyboard0" "CoreKeyboard"
    InputDevice    "Mouse0" "CorePointer"
EndSection

Section "Files"
EndSection

Section "InputDevice"
    # generated from default
    Identifier     "Mouse0"
    Driver         "mouse"
    Option         "Protocol" "auto"
    Option         "Device" "/dev/psaux"
    Option         "Emulate3Buttons" "no"
    Option         "ZAxisMapping" "4 5"
EndSection

Section "InputDevice"
    # generated from default
    Identifier     "Keyboard0"
    Driver         "kbd"
EndSection

Section "Monitor"
    Identifier     "Monitor0"
    VendorName     "Unknown"
    ModelName      "Unknown"
    HorizSync       28.0 - 33.0
    VertRefresh     43.0 - 72.0
    Option         "DPMS"
EndSection

Section "Device"
    Identifier     "Device0"
    Driver         "nvidia"
    VendorName     "NVIDIA Corporation"
    Option "NoLogo" "1"
EndSection

Section "Screen"
    Identifier     "Screen0"
    Device         "Device0"
    Monitor        "Monitor0"
    DefaultDepth    24
    Option         "MultiGPU" "on"
    Option         "SLI" "off"
    Option         "BaseMosaic" "on"
    SubSection     "Display"
        Depth       24
    EndSubSection
EndSection

Section "Extensions"
    Option         "COMPOSITE" "Enable"
EndSection

Section "InputClass"
    Identifier          "Keyboard Defaults"
    MatchIsKeyboard        "yes"
    Option              "XkbOptions" "terminate:ctrl_alt_bksp"
EndSection