text:
Q: Can't access FileCodeModel from Powershell console in Visual Studio 2017 DTE I'm trying to automate some code-related routines in VisualStudio 2017 using integrated Powershell console and VS Automation model (DTE). When I'm working on Solution/Project/File level, things are ok, e.g.
PS> $dte.ActiveDocument.ProjectItem

IsDirty              : False
FileCount            : 1
Name                 : FeaturesComposition.cs
Collection           : System.__ComObject
Properties           : System.__ComObject
DTE                  : System.__ComObject
Kind                 : {6BB5F8EE-4483-11D3-8BCF-00C04F8EC28C}
ProjectItems         : System.__ComObject
Object               : System.__ComObject
ExtenderNames        : {}
ExtenderCATID        : {610D4615-D0D5-11D2-8599-006097C68E81}
Saved                : True
ConfigurationManager :
FileCodeModel        : System.__ComObject
Document             : System.__ComObject
SubProject           :
ContainingProject    : System.__ComObject

But when I come to the code model of some particular file, there is nothing to work with:
PS> $dte.ActiveDocument.ProjectItem.FileCodeModel | Format-List -Property *
System.__ComObject

PS> $dte.ActiveDocument.ProjectItem.FileCodeModel | gm

PS>

Is it possible to get access to such submodels? Is there any easy way of dispatching EnvDTE.DTE interface to the existing $dte instance? I've tried some ideas below, but without no success.
Add-Type -Path "$env:VSAPPIDDIR\PublicAssemblies\envdte.dll"

PS> # Explicit cast doesn't work
PS> [EnvDTE.DTE]$dte

[ERROR] Cannot convert the "System.__ComObject" value of type "System.__ComObject#{04a72314-32e9-48e2-9b87-a63603454f3e}" to type "EnvDTE.DTE".

PS> # Wrapper works but it's useless
PS> $wrapped = [Runtime.InteropServices.Marshal]::CreateWrapperOfType($dte, [EnvDTE.DTEClass])
PS> $wrapped.ActiveDocument.ProjectItem.FileCodeModel

System.__ComObject

PS> # GetComInterfaceForObject gives the same IntPtr as IUnknown:QueryInterface
PS> # different from the call to GetComInterfaceForObject for example,
PS> # so I hoped to get another casting results. But it is the same.
PS> $contract = [Runtime.InteropServices.Marshal]::GetComInterfaceForObject($dte, [EnvDTE.DTE])
PS> [EnvDTE.DTE][Runtime.InteropServices.Marshal]::GetObjectForIUnknown($contract)

[ERROR] Cannot convert the "System.__ComObject" value of type "System.__ComObject#{04a72314-32e9-48e2-9b87-a63603454f3e}" to type "EnvDTE.DTE".

A: Try this:
 $fileCodeModel = Get-Interface $dte.ActiveDocument.ProjectItem.FileCodeModel ([ENVDTE80.FileCodeModel2])


text:
Q: Rotating progressbar download Can any of you tell me of a place that I can download a fancy rotating progressbar?  Or else to use WPF to develop one?  Problem with that though is I don't have any WPF templates.  I am looking for a quick solution also, with little development required.

A: Basic introduction to templating, has a few examples for ProgressBars as well: MSDN
If you want an indeterminate rotating thing that is fairly easy (e.g. here), but for it to fill up that might be quite difficult.

redpajama_set_name: RedPajamaStackExchange


text:
Q: SQL - Select by level or is parent when null I'm doing a query where I have the following data:

What I want is to get data by level.
That is, if the "User" column is not NULL, I want your Business + Type + Class combination returned.
In turn, if the "User" column is NULL, I want the Business + Type + Class combination to be obtained from the Agency column.
Finally, if the "User" column and the "Agency" column are NULL, I want to return the combination from the "Country" column.
Expected output is green lines:

Can someone help me?
Thanks!

A: This appears to be a prioritization query.  All rows where the user is not null, plus additionally one row per null.  One method is row_number():
select t.*
from (select t.*,
             row_number() over (partition by business, type, agency order by userid desc) as seqnum
      from t
     ) t
where seqnum = 1 or user is not null;

The desc puts the nulls last in the sequence, so they are filtered out by the where.
Another approach uses union all and not exists:
select t.*
from t
where t.user is not null
union all
select t.*
from t
where t.user is null and
      not exists (select 1
                  from t t2
                  where t2.business = t.business and
                        t2.type = t.type and
                        t2.class = t.class and
                        t2.user is not null
                 );

The first version is handy if your results are the result of a query, because the query results are only referenced (and hence calculated) once.


text:
Q: How to Display a Flash Message Immediately from Within a Controller Method flash.now[:class] is supposed to work differently from, e.g. flash.keep[:class] but doesn't seem to for me.  I've got flash.keep messages working all over my jRuby/Rails app but now I want to display a message immediately to assure the user that I'm working to fulfill the request BEFORE my controller method redirects.  Why doesn't flash.now work this way?  I've already followed it with a render instruction but that's not allowed if you also have a redirect_to elsewhere in your controller method, which I need in order to return to the main view.  If not flash.now then what should I use, or is what I'm trying to do just not possible in Rails?
The controller code isn't much more than what's shown above:
 flash.now[:info] = '* * * Working hard to fulfill your request... * * *'
 render :action => 'index'

I added the render instruction in an attempt to make flash.now flash now but the preprocessor didn't like my having both a render and a redirect_to in the same method.  I need the redirect_to further down as part of the normal and typical design of my RESTful application.
But the main point is that flash.now does not flash now.  So how is it different from, e.g. flash.keep or just flash?

A: Don't use flash.now.  You mention that you redirect_to within that action, and flash.now only shows up when you render (the difference being that redirect_to results in a whole 'nother HTTP request, and thus another action; flash.now is only visible in the current action).
So if you want that message to show up when your processing is done, just use the flash normally.
If you want to do it in two stages, though (a confirmation message when you get the HTTP request, and then a redirect when it finishes processing), it's trickier.  You can't create two HTTP responses for a single HTTP request, so you're going to have to fake it with JavaScript.
I'm guessing that since your action takes long enough to process that it needs a "Still Working..." message, it's a result of a form submission.  So make a form submit event handler that displays your message (and/or replaces the submit button with a "working" icon - this keeps impatient users from plugging up your server (and possibly breaking their data) by compulsively submitting again and again).  That lets your users know that you did in fact get their request, and are working on it*.  Then, when your action completes, just redirect or render as you normally would.
Hope that helps!
*Since it's just a JavaScript function, it doesn't know that the server actually got the response, but this is one of those cases where UX trumps technical pedantry.

A: Yes you can redirect_to OR render only once in each action.
Why don't you just use this instead
render :action => 'index', :notice => '* * * Working hard to fulfill your request... * * *'

or
flash[:notice] = '* * * Working hard to fulfill your request... * * *'
render :action => 'index'


text:
Q: Proof via Semantic Equivalence $(p \lor q) \land (q \implies p) \equiv p$
$$(p \lor q) \land (q \implies p) \equiv p$$

Struggling to solve the above with Semantic Equivalence
step 1: implication $( p \lor q ) \land ((\lnot q) \lor p)$
step 2: distributivity
$((p \lor q ) \land \lnot q) \lor ((p \lor q) \land p)$
step 3: absorption.
$((p \lor q ) \land \lnot q)) \lor p$
step 4: distributivity
$((\lnot q \land p) \land  (\lnot q \land q)) \lor p )$
step 5: absorption $((\lnot q \land q) \land p )$
step 6: negation $p \lor T$
Not sure where to go from here? Can $p \lor T$ be resolved to $p$?

A: Step 4 should be $$\begin{align}(4) \quad &\equiv  ((p \land \lnot q) \lor \underbrace{(q\land \lnot q)}_{\text{F}}) \lor p\tag{distrib.}\\ \\  (5)\quad  &\equiv (p \land \lnot q) \lor p \\ \\(6)\quad &\equiv  p\end{align}$$


text:
Q: Magento Flat Rate Shipping only if chart is over a certain amount In Magento 1.7, is there any way to show Flat Rate Shipping only if chart is over a certain amount?
By rule the only option seems to be free shipping, but my goal is to have Flat Rate if sub total in chart is xx (if sub total is lower, normal rates will be used).

A: Not by default. It's easy to extend the flat rate shipping carrier method though to do this. Simply create a new module, extend the flat rate shipping system.xml so that there is a new option for minimum cart price (this will allow you to configure it through admin). Extend the following class Mage_Shipping_Model_Carrier_Flatrate and override the collectRates method to check the cart total vs the admin config value. Return false if the cart value is not enough and it will not show up as an option, otherwise it will return the cost set in the admin.
Edit: Something like the following would do it. Extend the class, don't mod the core!
public function collectRates(Mage_Shipping_Model_Rate_Request $request)
{
    // Get The Minimum Order Value From Admin Config & Compare To Cart Subtotal (Base Prices)
    if (!$this->getConfigFlag('minimum_order') || $request->getBaseSubtotalInclTax() < $this->getConfigFlag('minimum_order')) {
        return false;
    } else {
        return parent::collectRates($request);
    }
}


text:
Q: How to add data label annotation to a single bar based off name in a Seaborn barplot Python I have the following dataframe producing the following plot:
# Import pandas library
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

# initialize list of lists
data = [['tom', 10,1,'a'], ['matt', 15,5,'b'],['nick', 18,2,'b'],['luke', 12,6,'b'],['geoff', 20,10,'a']]

# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['Name', 'Attempts','Score','Category'])
df

# Create plot
f, ax = plt.subplots(figsize=(8.27,11.7,))
df = df.sort_values(['Attempts'],ascending=False)
sns.set_color_codes("muted")
sns.barplot(x="Attempts", y="Name", data=df,
            label="Total", palette=["b" if x!='nick' else 'r' for x in df.Name], ax=ax)

# Annotate every single bar with its value
for p in ax.patches:
    width = p.get_width()
    ax.text(width - 1,
            p.get_y() + p.get_height() / 1 + 0.1,
            '{:1.2f}'.format(width),ha="center")

Seaborn plot
I want to include the data label annotation for only 'Nick'(i.e. in this instance the value 18 on the bar itself) which is the highlighted bar and have no label annotations on the rest of the bars. Is there an easy way to do this? Thanks very much !

A: Create only the labels you want to highlight and set them to 'set_yticklabels()'.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

# initialize list of lists
data = [['tom', 10,1,'a'], ['matt', 15,5,'b'],['nick', 18,2,'b'],['luke', 12,6,'b'],['geoff', 20,10,'a']]

# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['Name', 'Attempts','Score','Category'])

# Create plot
f, ax = plt.subplots(figsize=(8.27,11.7,))
df = df.sort_values(['Attempts'],ascending=False)
sns.set_color_codes("muted")
g = sns.barplot(x="Attempts", y="Name", data=df,
            label="Total", palette=["b" if x!='nick' else 'r' for x in df.Name], ax=ax)

# Annotate every single bar with its value
for p in ax.patches:
    width = p.get_width()
    if width == 18.0:
        ax.text(width - 1, p.get_y() + p.get_height() / 1 + 0.1, '{:1.2f}'.format(width),ha="center")
    else:
        pass

#label = ['','nick','','','']
#g.set_yticklabels(label)

A: Welcome to StackOverflow. Here is my solution:
First I reset the index of your df and then found the index number of the row matching the criteria (in this case nick):
# Create plot
f, ax = plt.subplots(figsize=(8.27,11.7,))
df = df.sort_values(['Attempts'],ascending=False)
#Reset index values
df = df.reset_index(drop=True)
#Return the index number of name required
indexno = df[df['Name'] == 'nick'].index
#Create array
a = np.array(indexno)
a= a[0]
print(a)

Which gives me:
1

(the 2nd row in your df)
Then I found all of the get_width values:
#Plot
sns.set_color_codes("muted")
sns.barplot(x="Attempts", y="Name", data=df,
            label="Total", palette=["b" if x!='nick' else 'r' for x in df.Name], ax=ax)

# Final all width values in plot
values = []
for i in ax.patches:
    values.append(i.get_width())

print(values)

which returns:
[20.0, 18.0, 15.0, 12.0, 10.0]

Now the final loop to display only the values where the criteria match (so the 2nd value in values (18)).
#Final loop to annotate only the row where width equals the value of `nick`
for p in ax.patches:
    width = p.get_width()
    x = values[a]
    if width==x:
        ax.text(width - 1,
                p.get_y() + p.get_height() / 1 + 0.1,
                '{:1.2f}'.format(width),ha="center")
plt.show()

full code:
 # Import pandas library
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

# initialize list of lists
data = [['tom', 10,1,'a'], ['matt', 15,5,'b'],['nick', 18,2,'b'],['luke', 12,6,'b'],['geoff', 20,10,'a']]

# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['Name', 'Attempts','Score','Category'])
df

# Create plot
f, ax = plt.subplots(figsize=(8.27,11.7,))
df = df.sort_values(['Attempts'],ascending=False)
#Reset index values
df = df.reset_index(drop=True)
#Return the index number of name required
indexno = df[df['Name'] == 'nick'].index
#Create array
a = np.array(indexno)
a = a[0]
print((a))

#Plot
sns.set_color_codes("muted")
sns.barplot(x="Attempts", y="Name", data=df,
            label="Total", palette=["b" if x!='nick' else 'r' for x in df.Name], ax=ax)

# Final all width values in plot
values = []
for i in ax.patches:
    values.append(i.get_width())

print(values[a])

#Final loop to annotate only the
for p in ax.patches:
    width = p.get_width()
    x = values[a]
    if width==x:
        ax.text(width - 1,
                p.get_y() + p.get_height() / 1 + 0.1,
                '{:1.2f}'.format(width),ha="center")
plt.show()


text:
Q: Android - How to modify xml file in res I have searched a lot and could not find the solution for that.
The thing is that I am making a Custom Keyboard. I have an XML file for the layout of this custom keyboard, stored in res/xml.
The problem is, that I want to change the keyboard layout from the java code. For that, I need to Open the xml file from res/xml/qwerty.xml and edit it with DOM In the Java Code.
How can I do it? And if it isn't possible how can I build such a keyboard that I can change dynamically through out the java code.
Thanks in advance.

A: Absolutely You can change our keypad dynamically.
But you Must to specify our row and column static.
Try to change key value label in this way and u can also change primaryCode value is same way:
            if (rflag== 1) {
                mQwertyKeyboard.getKeys().get(29).label = "NewTag";
                rflag = 0;
            } else {
                rflag = 1;
                mQwertyKeyboard.getKeys().get(29).label = "OldTag";

            }


text:
Q: Selecting all empty  with specific class and removing the parent  via JavaScript I have a very large HTML table with many rows. The rows are filed in by variables set in javascript from a response from my database. If the database responds with " " the variable is set to " ". I would like to find this and remove an entire parent row if true in JavaScript.
I have tried the below code but I don't think I am selecting the correct cell. I marked all of the rows with the 'row' class and the cell that may be empty with the 'emptytd' class in an effort to make it easier to select. Thanks in advance!
                var something =  "
" +
                                 "AA03	" +
                                 "" + aa03TrainTaskNm + "	" +
                                 "" + aa03DueDt + "
";

$('#something').html(somthing);
$('#myModal').modal("show");
$('td.emptytd:[value=" "]').parents('tr.row').hide();

A: You can loop through them and check their content like so:
   $("td.emptytd").each(function(){
        if($(this).html() === "") $(this).parent().remove();
    })

A: If you want to remove all the offending rows at once, you could do this:
document.querySelectorAll("td").forEach(function(el){
  if(el.innerHTML == " "){
    const row = el.parentNode;
    row.parentNode.removeChild(row);
  }
});

Note that even one "empty" cell in a row will trigger the removal of the entire row. And if the contents of a the cell are anything but a single spacebar character, nothing will happen. (If you want to handle other whitespace characters, you can use "/\s+/" to find any string of 1 or more whitespace characters.)


text:
Q: How to detect when UIviewcontroller becomes active again after pushing a child view? How to detect when UIviewcontroller becomes active again after pushing a child view?  Ie when using Uinavigatipncontroller
Ie which callback method in the parent uiviewcontroleer to use?

A: If this is for an iPhone app, then viewDidAppear: or possibly viewWillAppear: will get called when the child view goes away.


text:
Q: Determining RSS refresh rates Do all RSS feeds support HTTP ETags/last-modified headers for indicating whether the feed has been updated?
For feeds which do not include last-modified headers, what is the best way of determining how often the feed updates?
I'm hoping to tailor the number of requests I send to each feed based on its update frequency to cut down on bandwidth (following ~2k feeds...)

A: No, not all feeds support ETag/If-Modified headers (and unfortunately that does not tell you when to fetch a resource, just that it has not been updated).
There is no general way of determining when a feed has been updated. However, among the most popular methods is the PubSubHubbub protocol, which was designed for that. (It actually goes further and sends you the new content in the feed so you don't even have to fetch it).
The problem is that it's not supported by all feeds out there (up to 30% depending on the types of feeds you're dealing with: blogs, news sites, ecommerce... etc).
Another solution is to check http://superfeedr.Com (disclaimer: I created that beast:p) because we'll do all the dirty work for you and you can just sit and wait for us to send you the data (using open protocols).

A: To find new items compare the items of the retrieved feed with those found earlier. If the items have a GUID use that for the comparison, otherwise you could combine fields like link + title, or keep a MD5 hash of the complete item.
Use this knowledge to adapt the polling interval, like I described in this answer.


text:
Q: Iterate over R dataframe objects and add a column I have a number of dataframes as R objects named with a prefix and a number. Each dataframe has same column names and numbers as row names.
I am trying to add a column based on the object iteration. I am trying the following:
x <- 1
repeat{
get(paste0('prefix', x))$iteration <- x-1
x = x + 1
}

However, I get the following error:
target of assignment expands to non-language object

Could you explain why this does not work and suggest a solution?
Thanks.

A: Get the values of objects that starts with 'prefix' followed by any digits into a list ('lst1'), then use Map to create a new column by subtracting 1 from the numeric part of the object name ('v1'), use list2env to reflect the changes in the original objects in global env
lst1 <- mget(ls(pattern = '^prefix\\d+$'))
v1 <- as.numeric(sub("prefix", "", names(lst1))) -1
lst1 <- Map(cbind, lst1, iteration = v1)
list2env(lst1, .GlobalEnv)


text:
Q: Ajax throwing fail function... But it does what it should do I've got a weird behavior in my PHP/jQuery project.
When I call the Ajax request, it works as intended, but instead of calling the 'done' function, it calls the 'fail' one.
This is my code at the moment.
$("#form").submit(function(){

    var _this = $(this);
    var values = {};
    $.each($('#form').serializeArray(), function(i, field) {
        values[field.name] = field.value;
    });
  //  _this.button('loading');
    $.ajax({
      method: "POST",
      url: "include/ajax/install_ajax.php",
      data: values,
      dataType: 'json'
    })
      .done(function( msg ) {
        console.log( "Done: " + msg );
      })
      .fail(function(xhr, textStatus, errorThrown){
            console.warn('Xhr: ' + xhr.responseText);
            console.warn('textStatus: ' + textStatus);
            console.warn('errorThrown: ' + errorThrown);

      });
});

And this is my install_ajax.php
<?php

// Chiama le funzioni del sito
require('../functions.php');

// Controlla se è una richiesta AJAX.
is_ajax();

    try {

    $args['db_host'] = $_POST['db_host'];
    $args['db_username'] = $_POST['db_username'];
    $args['db_password'] = $_POST['db_password'];
    $args['db_name'] = $_POST['db_name'];
    $args['admin_email'] = $_POST['admin_email'];
    $args['admin_username'] = $_POST['admin_username'];
    $args['admin_password'] = $_POST['admin_password'];

    $structure =
    "-- --------------------------------------------------------

    --
    -- Struttura della tabella `users`
    --

    CREATE TABLE IF NOT EXISTS `users` (
      `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
      `username` text COLLATE utf8mb4_unicode_ci NOT NULL,
      `email` text COLLATE utf8mb4_unicode_ci NOT NULL,
      `name` text COLLATE utf8mb4_unicode_ci NOT NULL,
      `surname` text COLLATE utf8mb4_unicode_ci NOT NULL,
      `password` text COLLATE utf8mb4_unicode_ci NOT NULL,
      `admin` enum('0','1') COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '0',
      `validated` enum('0','1') COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '0',
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci AUTO_INCREMENT=1 ;";

    installDB($args['db_host'],$args['db_username'],$args['db_password'],$args['db_name'],$structure);

    createAdmin($args['db_host'],$args['db_username'],$args['db_password'],$args['db_name'],$args['admin_email'], $args['admin_username'], $args['admin_password']);

    createConfig($args['db_name'],$args['db_username'],$args['db_password'],$args['db_host']);
    $return = array();

    $return['success'] = true;

    return_json($return);

} catch (Exception $e) {
   error_log($e->getMessage() . "\n", 3, "/var/tmp/error.log");
}

?>

The message warn I get on the console is..
core.js:31 Xhr: undefined
core.js:32 textStatus: error
core.js:33 errorThrown: undefined

But the table 'users', the config file and the admin user are created however.
How can I fix it?
I will provide the code of the functions on request.

A: I think that the error that you see is that your code submits 2 times.. try to add this line:
$("#form").submit(function(event){
    event.preventDefault();  //prevent form from submitting, and only do ajax call
    var _this = $(this);
    // etc code..
}

this should work ok now..

A: Try this
$("#form").submit(function(){
    var _this = $(this);
    var values = {};
    $.each($('#form').serializeArray(), function(i, field) {
        values[field.name] = field.value;
    });
  //  _this.button('loading');
    $.ajax({
      method: "POST",
      url: "include/ajax/install_ajax.php",
      data: values,
      dataType: 'json',
      success: function(response){
        alert(response);
      },
      error: function(error){
        alert(error);
      }
    });
});

A: try to return your output using
return json_encode($return);

instead of
return_json($return);

A:     In PHP
    in try
    statement add echo json_encode(array('success'=>'1')); die;

and in Catch statement add echo json_encode(array('failed'=>'1')); die;

    replace your jquery submit code with below

    $("#form").submit(function(submitEvent){
        submitEvent.preventDefault();
        var _this = $(this);
      //  _this.button('loading');
        $.ajax({
          method: "POST",
          url: "include/ajax/install_ajax.php",
          data: _this.serializeArray(),
          dataType: 'JSON',
          success: function(response){
            console.log(response);
          },
          error: function(error){
            console.warn(error);
          }
        });
    });

and check browser console


text:
Q: laravel testing how to remove some failed output? I am testing some apis with laravel 8.
When a test is OK, I see this result :

It is clear, concise. Perfect !
When a test is KO, I  would like to have an equivalent result, without the detail of the problem :

I tried a lot of options (--quiet, -v -vv -vvv) without success. Is it possible to obtain this kind of result ?

A: Add  $this->withoutExceptionHandling(); on top your testmethods.


text:
Q: Lack of color displaying composite video I'm attempting to output video from a TMS9118 VDP to a television's composite video port.  Right now the result I'm getting is grey scale (whereas the background should be green), and I have no idea why.  I have compared the output from the TMS9118 comvid line to output from a DVD player on my oscilloscope, and the signals are somewhat different in quality.
The yellow signal is the dvd player.  The blue signal is the VDP.
Following is what the VDP produces on the television screen:

The TV displays the DVD player signal perfectly.  In summary, what is wrong with the signal coming out of the TMS9118 comvid line?

A: It  would appear that you have significant ground current noise between the two systems or some other large CM noise.
The VDP scale is 1/4 of the DVD yellow scale to see that same size sync tip and chroma burst. The amplitude must be double amplitude for a 75Ohm source and load and the same as the DVD player.
The output level for chroma sync if too low or noisy would disable chroma video from being displayed in the VDT.
The VDT shows a LOT of pixel clock noise on the display.
Shields up and improve grounds.


text:
Q: Google sheet Script Error I have a form which submits various scores (numbers) and N/A (where the score is not applicable) , to a sheet. After each submission, I would like to change all the N/A entries in the most recent submission to null (or empty cell). That is, I would like to iterate over the most recent row (the last row) only, and do the changes.
I have a trigger to run the script below when the form is submitted, but it does not work. How do I fix this issue?
function mySetValues() {

 var targetSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses");

 var lr = targetSheet.getLastRow();
 var lc = targetSheet.getLastColumn();

 var range = targetSheet.getRange(lr,2, lr, lc)

  for(var i = 0; i < range.length; i++){

    if(range[0][i] == "N/A" ){
     range[0][i].setValue(null);
    }
}
}


text:
Q: Components Render then Disappear I have a relatively simple component which renders properly on iOS but not Android. The component appears to render then the top 1/2 of the screen fades away. I'm sure the component is rendered but it appears the subcomponents are fading out or being covered by something. Given that the animation which occurs (quickly) looks like a fade, I think the components are still there.
The component is instantiated by a component which is created by react-navigation as a tab. This component has native-base components. The navigation.push() instantiates a react-native based component. All of the data required to render is in this.state object. Debugging reveals nothing.
Switching to another tab then back resolves the problem. Forcing re-rendering() in the event handler when the tab is focused has no effect.
I'm stumped.
This is the code:
import React, { Component } from 'react';

import {
  Image,
} from 'react-native';

import {
  Container,
  Content,
  Body,
  Header,
  Left,
  Right,
  Thumbnail,
  ListItem,
  List,
  Text,
  Button,
  Footer,
  FooterTab,
  Card,
  CardItem,
} from 'native-base';

import QRCode from 'react-native-qrcode';

export default class UnitDetailScreen extends Component {

  static navigationOptions = ({ navigation }) => {
    return {
      title: 'Unit Details',
      headerRight: <Button onPress={
        () => {
          navigation.navigate(
            'UnitInstallation',
            { item: navigation.getParam('item') }
          )
        }
      }>
        <Text>Edit</Text>
      </Button>,
    }
  };

  state = {
  };

  componentDidMount() {
    const navigation = this.props.navigation;
    const item = navigation.getParam('item');
    this.setState({ item: item, navigation: navigation });
  }

  getBatteryImage(item) {
    return { uri: 'battery-green.png' };
  }

  render() {
    if (this.state.item === undefined) {
      return <Text>loading...</Text>;
    }

    // ok, now this is really wierd... the item is actually pointing to a row when this method called so we can't use getParam('item')
    const rowStyle = {
      flex: 1,
      flexDirection: 'row',
      justifyContent: 'flex-start',
      marginLeft: 10,
      marginRight: 10,
      padding: 10,
      borderBottomColor: '#888'
    };

    const noPhoto = { uri: 'no-photo.png' }

    return <Container>
      <Content>
        <Card>
          <CardItem>
            <Left>
              <Thumbnail source={noPhoto} />
              <Body>
                <Text>Big Bad Machine</Text>
                <Text note>The Lab</Text>
              </Body>
            </Left>
          </CardItem>
        </Card>
        <Card>
          <CardItem bordered>
            <Image style={{
              flex: 1,
              height: 30,
              width: undefined,
              resizeMode: 'contain'
            }} source={this.getBatteryImage(this.state.item)} />
          </CardItem>
          <CardItem>
            <Left><Text style={{ fontWeight: 'bold' }}>Installed</Text></Left>
            <Right><Text>{this.state.item.unit.installDate}</Text></Right>
          </CardItem>
          <CardItem>
            <Left><Text style={{ fontWeight: 'bold' }}>Model</Text></Left>
            <Right><Text>The model</Text></Right>
          </CardItem>
          <CardItem>
            <Left><Text style={{ fontWeight: 'bold' }}>Serial</Text></Left>
            <Right><Text>{this.state.item.unit.serialNumber}</Text></Right>
          </CardItem>
          <CardItem>
            <Left><Text style={{ fontWeight: 'bold' }}>Purchased</Text></Left>
            <Right><Text>{this.state.item.unit.purchaseDate}</Text></Right>
          </CardItem>
          <CardItem>
            <Left><Text style={{ fontWeight: 'bold' }}>Installation</Text></Left>
            <Right>
              <Thumbnail square source={noPhoto} />
            </Right>
          </CardItem>
          <CardItem>
            <Left><Text style={{ fontWeight: 'bold' }}>QR Code</Text></Left>
            <QRCode
              value={this.state.item.unit.id}
              size={80}
            />
          </CardItem>
          <CardItem>
            <Left><Text style={{ fontWeight: 'bold' }}>Serial</Text></Left>
            <Right><Text>{this.state.item.unit.serialNumber}</Text></Right>
          </CardItem>
          <CardItem>
            <Left><Text style={{ fontWeight: 'bold' }}>ID</Text></Left>
            <Right><Text>{this.state.item.unit.id}</Text></Right>
          </CardItem>
        </Card>
      </Content>
      <Footer>
        <FooterTab>
          <Button bordered light>
            <Text>Photos/Notes</Text>
          </Button>
          <Button bordered light>
            <Text>Installation Media</Text>
          </Button>
        </FooterTab>
      </Footer>
    </Container>
  }
}

Initial render:

Navigate away:

Navigate back:

A: I fixed the problem using the SVG version of the component:
npm install react-native-qrcode-svg --save

The props to supply are the same for my application. This solved the problem.


text:
Q: Can javascript running inside an iframe affect the main page? Partial Code:
My below code pulls a query from my DB and then uses inner.HTML = to display the data inside a div. It works fine in it original use....
However the below version is called inside a iFrame as it is used to update the page.
The page has no errors and the JavaScript fires however the last line does not work...
I have just realized that perhaps since it is loading in the hidden iFrame it is trying to set the innerHTML of a div inside the iFrame and that of course will not work.
Is this what is happening? It doesn't make sense because I have another script that calls JavaScript at the end of it in the same manner and it works fine.
<?php
    while ($row = mysql_fetch_array($result))
    {
        $p = $p.'

';
        $p = $p.'

'.$row[artist].' - '.$row['title'].'

'.$row['message'].'
';
        $p = $p.''.$row[username].' '.$row[date].'
';
        $p = $p.'

';
        $p = $p.'

';
    }

    $p = addslashes($p);
?>

A: You can do it! Read here for more info
You can affect the document with contains the iframe by setting and getting variables from the window element:
// normally you use...
var whatever = "value";

// use the window object instead, which is shared
// between the iframe and the parent
window.whatever = "value";

The other thing you should know is that you can access the main document via the parent object
inside the iframe you can use...
parent.someattr;

// or try this
parent.getElementById('some_element');

A: I think what you want is:
parent.getElementById('posts').innerHTML = 'why doth this faileth?';

A: The part in the iframe isn't considered the same document.

A: you have to use parent.


text:
Q: Proof verification: rational solutions to $x^y=y^x$ I am trying to find rational solutions to the equation $x^y=y^x$, but I'm unsure if my solution is right (especially the first paragraph below). Here is my attempted solution (I've excluded the trivial case $x=y$).

We first show that any rational root must also be an integral root. To do so, consider $\mathcal F_b(x)=x^a-a^b$ for a parameter $b$ and
  constant $a$. By the rational root theorem, if $x=p/q$, $(p,q)=1$ is a
  rational root, then $q\mid 1$, hence $q=\pm 1$, and any root of
  $\mathcal F_b$ is integral, regardless of $b$. Since $x^y-y^x=\mathcal F_x(x)$, this conclusion applies as well.
Now we consider the case where $x,y>0$. Note that $x^y=y^x$ exactly when $y\ln x=x\ln y$ and $y/\ln y=x/\ln x$. Let $f(x)=x/\ln
x$, so we have $f(x)=f(y)$. The derivative of this function is
  $f'(x)=(\ln x-1)/(\ln x)^2$, whose unique root is $x=e$. Thus on the
  open interval $(0,e)$, $f$ is monotonously decreasing, and on
  $(e,\infty)$ it is increasing. It is immediate that we cannot have
  $f(x)=f(y)$ if both $x$ and $y$ are on $(e,\infty)$ or $(0,e)$, thus
  exactly one of them is on $(0,e)$. Since they are positive integers,
  without loss of generality assume that $x>y$, so $y=1$ or $y=2$. If
  $y=1$ then $x=1$ but $x\neq y$, a contradiction. If $y=2$ then $x=4$.
  Likewise we also have the solutions $y=4$, $x=2$.
Then, we consider
  $x,y<0$. Then let us make the change of coordinates $x=-x'$ and
  $y=-y'$ with $x',y'>0$ to obtain  $$ x^y=y^x\iff
> (-x')^{-y'}=(-y')^{-x'} \iff (-x')^{y'}=(-y')^{x'}.$$  If exactly one
  of $x',y'$ is odd, then the signs on both sides are different, a
  contradiction. Hence they have the same parity. If both are even, then
  $(x',y')=(2,4),(4,2)$ since the equation reduces to the previous case;
  and hence $(x,y)=(-2,-4),(-4,-2)$. If both are odd, the same thing
  occurs, but neither of our two roots satisfy the supposition that both
  $x,y$ are odd. Hence there is no solution in this case.
Finally, we
  consider $x>0>y$ (the case $y>0>x$ is identically discussed).
  Considering signs at both sides of the equation $x^y=y^x$, we
  immediately have that $x$ is even. Make the change of coordinates
  $y=-y'$, and use that $x$ is even to get $x^{-y'}=(y')^x$. Notice that
  $(y')^x$ is a positive integer, hence $x^{-y'}$ is a positive integer
  as well. Thus $x^{-y'}\geq1\implies x^{y'}\leq 1$, and since $x,y'$
  are positive integers, we must have $x=1$ or $y'=y=0$. If $x=1$, we
  have $1^y=y^1$, hence $y=1$. But $x\neq y$, a contradiction. If $y=0$,
  then $x^0=0^x$ and $1=0$, a contradiction. So there is no solution in
  this case.
Combining the three cases, our solutions are $(2,4),(-2,-4),(4,2),(-4,-2)$.

A: I'll restrict my comments to the first paragraph, which has a substantial gap.  The rational root theorem applies to polynomials, requiring that powers of the variable be nonnegative integers.  You can address this by inserting a step.
"Suppose $x = p/q$, $y = u/v$, with $p,q,u,v \in \mathbb{Z}$ and both $(p,q) = 1$ and $(u,v) = 1$, is a solution to $x^y = y^x$.  Then $p,q,u,v$ are a solution to $((p/q)^{u/v})^{qv} = ((u/v)^{p/q})^{qv}$.  More simply, $(p/q)^{qu} = (u/v)^{pv}$."
Now the exponents are rational, but we aren't quite done converting entirely to integers.
"Then we clear denominators: $q^{qu} v^{pv} (p/q)^{qu} = q^{qu} v^{pv} (u/v)^{pv}$, so $v^{pv} p^{qu} = q^{qu} u^{pv}$ has a solution in integers if $x^y = y^x$ has a solution in rationals."
You can attempt to continue as you have.  The additional variables make it likely that you can find the rest of the many, many rational solutions.  Note that at most one of $x$ or $y$ is negative, which allows you to place constraints on the signs of $p,q,u,v$ to ensure that $v^{pv} p^{qu} = q^{qu} u^{pv}$ has a non-negative power on whichever variable you choose to make the variable of your polynomial.  (There will be a few cases, but not too many.)  Skimming your argument, you will have to make several subsequent adjustments and I haven't dug into the details enough to see if your method can complete the argument.

A: There are infinitely many rational solutions.  You can find an analysis at https://www.maa.org/sites/default/files/Sved50816668.pdf


text:
Q: Not unlocking locked mutex Hello I am new to this and I would like to know what I am understanding wrong. I have a program:
#include <pthread.h>

pthread_mutex_t lock;
pthread_mutexattr_t att;

int main () {

    pthread_mutexattr_init (&att);
    pthread_mutexattr_settype (&att, PTHREAD_MUTEX_RECURSIVE);
    pthread_mutex_init (&lock, &att);

    pthread_mutex_lock (&lock);
    pthread_mutex_lock (&lock);
    pthread_mutex_unlock (&lock);

}

PTHREAD_MUTEX_RECURSIVE means that the lock remembers how many times has been locked. But this program still finishes without any errors. Even when I don't call unlock at all ... I would expect some error that I have still locked lock or something like that or something...Does it somehow unlock automatically?  (I compile my code as gcc main.c -pthread )

A:
I would expect some error that I have still locked lock

Nope. Nothing prevents the process from terminating or will complain about the process terminating while the lock still is locked. That would be like expecting an error because you malloc()d an object, but didn't free it before the process terminated. Like expecting an error because you opened a file but didn't close it.
The lock—like the virtual memory occupied by the malloc()d object, like the open file handle—is a resource that belongs exclusively to the process, and when you kill the process, all such resources are automatically destroyed/released/freed/etc.

P.S., This could be a good reason to move toward C++ and, in particular, the RAII design pattern that is enabled by C++. RAII is a way to guarantee that open files, allocated objects, locked locks, etc. won't be forgotten.

A:
Even when I don't call unlock at all ... I would expect some error that I have still locked lock or something like that or something

Why?
It is not inherently erroneous for a program to terminate while it holds a mutex locked.  Moreover, C does not guarantee any runtime diagnostics even when the program does something genuinely wrong.  Sometimes you do get diagnostics under such circumstances, but often you do not.

...Does it somehow unlock automatically?

No, but that does not matter in the example presented because the mutex itself is destroyed when the program terminates.
If it were a process-shared mutex to which another process also had access then it would be a semantic error for a process to terminate while holding it locked.  But probably still not one that you could expect a diagnostic about.


text:
Q: Chrome extension that runs only once I'm trying to make an extension that activates when I visit facebook. Up to this part all is good, however then it starts running my code indefinitely.
What I want is to run the content.js script only the first time I visit Facebook and then never run it again.
My current approach is this, but it doesn't work:
background.js
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
  if (request.storage) {
    if (typeof request.value != 'undefined') {
      localStorage[request.storage] = request.value;
    }
    sendResponse({storage: localStorage[request.storage]});
  } else {
    sendResponse({});
  }
});

content.js
var status;
chrome.extension.sendRequest({storage: 'status'}, function(response) {
  status = response.storage;
});

if(status != '1')
{
   chrome.extension.sendRequest({storage: 'status', value: '1'});
   //  do my stuff here but only 1 time
}

manifest.json
   "content_scripts": [ {
      "js": [ "js/jquery.js", "content.js" ],
      "matches": [ "https://facebook.com/" ]
   } ],

Basically my idea is to run content.js when I visit Facebook, then after the script is done, I add a status variable and then next time I check if the status is 1 which means that the code had already run before.
How can I accomplish this?
Thank you.

A: 1) You are making the standard async JavaScript mistake.
var status;
chrome.extension.sendRequest({storage: 'status'}, function(response) {
  status = response.storage; // <--+
});                          //    | This code didn't execute yet
                             //    |
if(status != '1') // --------------+
{
   chrome.extension.sendRequest({storage: 'status', value: '1'});
   //  do my stuff here but only 1 time
}

2) You are using a very old and deprecated version of Messaging. extension.sendRequest/onRequest need to go, replacement is runtime.sendMessage/onMessage.
3) It's best to not use Messaging here at all; chrome.storage API is made specifically for this purpose. Again, maybe you're using some very old tutorial.


text:
Q: Arabic characters in python I'm reading data from sql using my python script and upload it to Solr, but i'm facing an issue with the arabic letters,the script cannot upload the arabic letters properly, it shows me random characters and question marks in Solr(???????? ???).
This is a part of the script where i'm adding the return value from sql to the field in Solr:
["FIRSTNAME": ""+str(row[26].encode("windows-1256", 'strict'))+"",]
-FIRSTNAME is the field name in Solr
-row[26] is the return value from sql (it has some arabic letters)
i tried windows-1256,cp720,utf-8... but got the same error
How can i solve this problem?


text:
Q: Unforecasted versus unexpected Is unforecasted correct English? Or should one use unexpected or some other form?
The relevant sentence would be :
Parties short longevity are financially hurt by unforecasted increases in life expectancy

A: I'd go for 'unprojected', 'unanticipated' or 'unforeseen'. Although 'unexpected' may be best.
NB: 'Parties short longevity' means parties that have a financial short-position in (or short-exposure to) longevity. They are effectively betting on longevity decreasing (perhaps for sub-populations), but were then wrong-footed when, for example, HIV/AIDS-medicine was developed. Or pension funds. It's finance lingo.

A: "Unforecasted" works with budgets and forecast, where you are trying to indicate that something was not included in the forecast. for instance.

The covid pandemic has resulted in an unexpected increase in demand for read to eat products.

However if it should have been known,

The April budget for the new year did not include an unforecasted increase in ready to products.

A: It could be either.  "Unforecasted" implies that there has been some forecasting of increases in life expectancy, and the actual increase in life expectancy doesn't match the forecasts.
If there haven't been any forecasts of this type, then we shouldn't say "unforecasted".
"unexpected" is more simple and doesn't need any further explanation in this context, beyond its dictionary definition.

A: Unforecasted can be used to suggest that there has been a failure in the matter of forecasting.  The increase in life expectancy should have been forecast, but wasn't.  Unexpected works, but it has less suggestion of a failure and more suggestion of anomaly.  So it depends on what you want.
It's another topic, but there are problems with Parties short longevity are as well.  Is there a 'with' or 'of' missing after Parties?

A: Both:

...are financially hurt by unforecasted increases in life expextancy.

and

... are financially hurt by unexpected increases in life expextancy.

are fine. Obviously, there is a difference in meaning between unforecasted and unexpected. The former implies some systematic attempt to predict whilst the latter is merely against our intuitive expectations.
What is strange to me is the first part of the sentence:

Parties short longevity ...

What on earth does this mean?


text:
Q: Pandas dataframe slicing problems in combination with pyplot I have problems with using pandas for pyplot.
On the one hand the scale is wrong, since the value 10 on the y axis shows before 1.
On the other hand I get the error message:
TypeError: unsupported operand type(s) for -: 'str' and 'str'
When using yerr.
import matplotlib.pyplot as plt
import numpy as np
import matplotlib
import pandas as pd

df=pd.read_table('TI_attachment.dat', header=0, sep='\s+')

fig, ax=plt.subplots(figsize=(20,10))
ax.errorbar(x=df.iloc[:, 0:1], y=df.iloc[:, 1:2], yerr=df.iloc[:, 2:3], color='black')
ax.set_xlabel('Simulation Time per window [ns]', size=25)
ax.set_ylabel('Free energy of binding [kcal/mol]', size=25)

ax.tick_params(axis='both', labelsize=25)
plt.tight_layout()
#plt.savefig('PMF.png', format='png')
#plt.show()

This is what TI_attachment.dat looks like:
#Weight of restraints (%), Accumulative work (in kcal/mol), SEM (in kcal/mol)
0.0000      0.00000      0.00000
0.0040      3.23161      0.78401
0.0080      3.76232      0.79356
0.0160      4.50989      0.82542
0.0240      4.86168      0.82490
0.0400      5.48672      0.82894
0.0550      6.02476      0.82931
0.0865      6.73611      0.83116
0.1180      7.20339      0.83305
0.1810      7.69373      0.83432
0.2440      8.16010      0.83487
0.3700      8.87930      0.83952
0.4960      9.25889      0.84035
0.7480      9.83864      0.84071
1.0000     10.28260      0.84107

A: I solved it by selecting the columns in a different way:
 ax.errorbar(x=df.iloc[:, 0], y=df.iloc[:, 1], yerr=df.iloc[:, 2], color='black')


text:
Q: Javafx: Recovering the text of a label contained within a pane through pane.getChildren().get(index) This is a problem I've been trying to deal with for a good hour now, so I figured I might as well ask this question. My goal/question is about the behaviour of the list supplied by pane.getChildren(). To explain better, here's a bit of example code.
VBox pane1 = new VBox();
Label label1 = new Label("a");
Label label2 = new Label("b");
pane1.getChildren().addAll(label1,label2);
System.out.println(pane1.getChildren().size());
for (int i=0; i<pane1.getChildren().size(); i++) {
    System.out.println(i + pane1.getChildren().get(i).(??????????)
}

The list pane1.getChildren() is of a size 2, but the pane1.getChildren().get(i) doesn't allow me to use Label related methods (such as getText(), which is the one I'm interested in accessing). What exactly is happening here, why isn't pane1.getChildren().get(i) acknowledged as a Label?
Also worth adding, that if i run
for (int i=0; i<pane1.getChildren().size(); i++) {
    System.out.println(i + pane1.getChildren().get(i).getClass().getName());
}

the console output says, that the name of the class is "javafx.scene.control.Label".
I'd love some clarification on this little problem, and thank you in advance!

A: Pane.getChildren() returns an ObservableList<Node>, so pane1.getChildren().get(i) has a compile-time type of Node, not Label.
It's not clear why you need to do this: you already have the references to the labels without iterating through the pane's list of children. So you can just do
Stream.of(label1, label2).map(Label::getText).forEach(text -> {
  // whatever you need to do with the text...
});

If you really want to get this from the pane's children list, just do the obvious downcast:
for (Node n : pane1.getChildren()) {
   String text = ((Label) n).getText();
   // ...
}

or
pane1.getChildren().stream()
    .map(Label.class::cast)
    .map(Label::getText)
    .forEach(text -> {
        // whatever you need to do with text...
    });

but of course this will not work (without extra checks) if you put something in the pane that is not a label.

A: If you need to downcast it can be done in a stream:
pane1.getChildren()
     .stream()
     .filter(Label.class::isInstance)
     .map(Label.class::cast)
     .forEach(label -> System.out.println(label.getText()));

This filters all children to just be labels, then maps them as such.


text:
Q: Localize iOS 14 dynamic widget configuration I am trying to load different configuration for the widgets depending on the app language, but when I use something like:
Locale.preferredLanguages
Bundle.main.preferredLocalizations
Bundle.main.localizations

all of them are returning "en" only in IntentExtensionTarget.
here is an example where I am using the code:
extension IntentHandler: ReciterAndSurahIntentHandling {

    func provideSurahOptionsCollection(for intent: ReciterAndSurahIntent, with completion: @escaping (INObjectCollection<NSString>?, Error?) -> Void) {

        Locale.preferredLanguages
        Bundle.main.preferredLocalizations
        Bundle.main.localizations
        // All of them return "en" only, and I have multiple localization for the app.
    }
}

A: You get EN only, because localization in description and widget names is based on device language. If you would try to set device language to a different one, localization should work. As for now, it is not possible to use in-app language on widget description and name localization.

A: There is a simple solution:

*

*Add AppGroups capability for both Parent App and the widget.

*Create simple UserDefaults
 let SharedGroupName = "group.pl.blueworld.fieldservice"
 let PreferredLanguageKey = "PreferredLanguageKey"
 extension UserDefaults {
     static let shared = UserDefaults(suiteName: SharedGroupName)!
 }

*Save current language in shared UserDefaults.
 func applicationDidBecomeActive(_ application: UIApplication) {
     UserDefaults.shared.setValue(Locale.preferredLanguages[0].prefix(2), forKey: PreferredLanguageKey)
 }

*Access value inside Widget View:
 struct MyView: View {
     var language: String {
         return UserDefaults.shared.string(forKey: PreferredLanguageKey) ?? "en"
     }
 }


text:
Q: Issues inserting values in datasource using groovy script in SOAP UI I tried the following code to insert values into the data store using groovy in SOAP UI.
The problem is it inserts only one row into the data store.
import groovy.json.JsonSlurper
def utils = new com.eviware.soapui.support.GroovyUtils( context );
def project = testRunner.testCase.testSuite.project ;
def tcase = project.testSuites["MyTestSuite"].testCases["MyTestCase"] ;
def tstep = tcase.getTestStepByName("GetShops");
def JSONresponse = tstep.getPropertyValue("response");
def slurper = new JsonSlurper()
def jsonElements = slurper.parseText(JSONresponse)

for ( value in jsonElements.shopId ) {
    log.info value
     result["IDS"] = value
}

Even though the log shows multiple values only the last one is getting inserted into datastore IDS column.
What am I missing here ?

A: I guess result is a Map or some map-like object, so each iteration through the loop
for ( value in jsonElements.shopId ) {
    log.info value
    result["IDS"] = value
}

replaces the value stored in this map under the "IDS" key.

A: The parseText function returns a data structure of lists and maps. Do a log.info to see what the json actually looks like. When you use jsonElements.shopId what you get back will be map(s). You should access that as a Map.
Try the below code to loop through the json response.
import groovy.json.JsonSlurper

def jsonResp = context.expand('${CitiesJSON - Request 1#Response}')

def jsonElements = new JsonSlurper().parseText(jsonResp)

for ( value in jsonElements.geonames ) {
    value.each{
            log.info "${it.key}:${it.value}"
    }
}

I made use of the geonames web service and CitiesJSON - Request 1 is the name of my rest test request.
/*This code returns the below data
Thu Apr 10 17:29:50 ADT 2014:INFO:fcodeName:capital of a political entity
Thu Apr 10 17:29:50 ADT 2014:INFO:toponymName:Mexico City
Thu Apr 10 17:29:50 ADT 2014:INFO:countrycode:MX
Thu Apr 10 17:29:50 ADT 2014:INFO:fcl:P
Thu Apr 10 17:29:50 ADT 2014:INFO:fclName:city, village,...
Thu Apr 10 17:29:50 ADT 2014:INFO:name:Mexico City
Thu Apr 10 17:29:50 ADT 2014:INFO:wikipedia:en.wikipedia.org/wiki/Mexico_City
Thu Apr 10 17:29:50 ADT 2014:INFO:lng:-99.12766456604
Thu Apr 10 17:29:50 ADT 2014:INFO:fcode:PPLC
Thu Apr 10 17:29:50 ADT 2014:INFO:geonameId:3530597
Thu Apr 10 17:29:50 ADT 2014:INFO:lat:19.428472427036
Thu Apr 10 17:29:50 ADT 2014:INFO:population:12294193
Thu Apr 10 17:29:50 ADT 2014:INFO:fcodeName:capital of a political entity
Thu Apr 10 17:29:50 ADT 2014:INFO:toponymName:Manila
Thu Apr 10 17:29:50 ADT 2014:INFO:countrycode:PH
Thu Apr 10 17:29:50 ADT 2014:INFO:fcl:P
Thu Apr 10 17:29:50 ADT 2014:INFO:fclName:city, village,...
Thu Apr 10 17:29:50 ADT 2014:INFO:name:City of Manila
Thu Apr 10 17:29:50 ADT 2014:INFO:wikipedia:en.wikipedia.org/wiki/Manila
Thu Apr 10 17:29:50 ADT 2014:INFO:lng:120.9822
Thu Apr 10 17:29:50 ADT 2014:INFO:fcode:PPLC
Thu Apr 10 17:29:50 ADT 2014:INFO:geonameId:1701668
Thu Apr 10 17:29:50 ADT 2014:INFO:lat:14.6042
Thu Apr 10 17:29:50 ADT 2014:INFO:population:10444527
Thu Apr 10 17:29:50 ADT 2014:INFO:fcodeName:capital of a political entity
Thu Apr 10 17:29:50 ADT 2014:INFO:toponymName:Dhaka
Thu Apr 10 17:29:50 ADT 2014:INFO:countrycode:BD
Thu Apr 10 17:29:50 ADT 2014:INFO:fcl:P
Thu Apr 10 17:29:50 ADT 2014:INFO:fclName:city, village,...
Thu Apr 10 17:29:50 ADT 2014:INFO:name:Dhaka
Thu Apr 10 17:29:50 ADT 2014:INFO:wikipedia:en.wikipedia.org/wiki/Dhaka
Thu Apr 10 17:29:50 ADT 2014:INFO:lng:90.40743827819824
Thu Apr 10 17:29:50 ADT 2014:INFO:fcode:PPLC
Thu Apr 10 17:29:50 ADT 2014:INFO:geonameId:1185241
Thu Apr 10 17:29:50 ADT 2014:INFO:lat:23.710395616597037
Thu Apr 10 17:29:50 ADT 2014:INFO:population:10356500
Thu Apr 10 17:29:50 ADT 2014:INFO:fcodeName:capital of a political entity
Thu Apr 10 17:29:50 ADT 2014:INFO:toponymName:Seoul
Thu Apr 10 17:29:50 ADT 2014:INFO:countrycode:KR
Thu Apr 10 17:29:50 ADT 2014:INFO:fcl:P
Thu Apr 10 17:29:50 ADT 2014:INFO:fclName:city, village,...
Thu Apr 10 17:29:50 ADT 2014:INFO:name:Seoul
Thu Apr 10 17:29:50 ADT 2014:INFO:wikipedia:en.wikipedia.org/wiki/Seoul
Thu Apr 10 17:29:50 ADT 2014:INFO:lng:126.9784
Thu Apr 10 17:29:50 ADT 2014:INFO:fcode:PPLC
Thu Apr 10 17:29:50 ADT 2014:INFO:geonameId:1835848
Thu Apr 10 17:29:50 ADT 2014:INFO:lat:37.566
Thu Apr 10 17:29:50 ADT 2014:INFO:population:10349312
Thu Apr 10 17:29:50 ADT 2014:INFO:fcodeName:capital of a political entity
Thu Apr 10 17:29:50 ADT 2014:INFO:toponymName:Jakarta
Thu Apr 10 17:29:50 ADT 2014:INFO:countrycode:ID
Thu Apr 10 17:29:50 ADT 2014:INFO:fcl:P
Thu Apr 10 17:29:50 ADT 2014:INFO:fclName:city, village,...
Thu Apr 10 17:29:50 ADT 2014:INFO:name:Jakarta
Thu Apr 10 17:29:50 ADT 2014:INFO:wikipedia:en.wikipedia.org/wiki/Jakarta
Thu Apr 10 17:29:50 ADT 2014:INFO:lng:106.84513092041016
Thu Apr 10 17:29:50 ADT 2014:INFO:fcode:PPLC
Thu Apr 10 17:29:50 ADT 2014:INFO:geonameId:1642911
Thu Apr 10 17:29:50 ADT 2014:INFO:lat:-6.214623197035775
Thu Apr 10 17:29:50 ADT 2014:INFO:population:8540121
Thu Apr 10 17:29:50 ADT 2014:INFO:fcodeName:capital of a political entity
Thu Apr 10 17:29:50 ADT 2014:INFO:toponymName:Tokyo
Thu Apr 10 17:29:50 ADT 2014:INFO:countrycode:JP
Thu Apr 10 17:29:50 ADT 2014:INFO:fcl:P
Thu Apr 10 17:29:50 ADT 2014:INFO:fclName:city, village,...
Thu Apr 10 17:29:50 ADT 2014:INFO:name:Tokyo
Thu Apr 10 17:29:50 ADT 2014:INFO:wikipedia:en.wikipedia.org/wiki/Tokyo
Thu Apr 10 17:29:50 ADT 2014:INFO:lng:139.69171
Thu Apr 10 17:29:50 ADT 2014:INFO:fcode:PPLC
Thu Apr 10 17:29:50 ADT 2014:INFO:geonameId:1850147
Thu Apr 10 17:29:50 ADT 2014:INFO:lat:35.6895
Thu Apr 10 17:29:50 ADT 2014:INFO:population:8336599
Thu Apr 10 17:29:50 ADT 2014:INFO:fcodeName:capital of a political entity
Thu Apr 10 17:29:50 ADT 2014:INFO:toponymName:Taipei
Thu Apr 10 17:29:50 ADT 2014:INFO:countrycode:TW
Thu Apr 10 17:29:50 ADT 2014:INFO:fcl:P
Thu Apr 10 17:29:50 ADT 2014:INFO:fclName:city, village,...
Thu Apr 10 17:29:50 ADT 2014:INFO:name:Taipei
Thu Apr 10 17:29:50 ADT 2014:INFO:wikipedia:en.wikipedia.org/wiki/Taipei
Thu Apr 10 17:29:50 ADT 2014:INFO:lng:121.531846
Thu Apr 10 17:29:50 ADT 2014:INFO:fcode:PPLC
Thu Apr 10 17:29:50 ADT 2014:INFO:geonameId:1668341
Thu Apr 10 17:29:50 ADT 2014:INFO:lat:25.047763
Thu Apr 10 17:29:50 ADT 2014:INFO:population:7871900
Thu Apr 10 17:29:50 ADT 2014:INFO:fcodeName:capital of a political entity
Thu Apr 10 17:29:50 ADT 2014:INFO:toponymName:Bogotá
Thu Apr 10 17:29:50 ADT 2014:INFO:countrycode:CO
Thu Apr 10 17:29:50 ADT 2014:INFO:fcl:P
Thu Apr 10 17:29:50 ADT 2014:INFO:fclName:city, village,...
Thu Apr 10 17:29:50 ADT 2014:INFO:name:Bogotá
Thu Apr 10 17:29:50 ADT 2014:INFO:wikipedia:en.wikipedia.org/wiki/Bogot%C3%A1
Thu Apr 10 17:29:50 ADT 2014:INFO:lng:-74.08175468444824
Thu Apr 10 17:29:50 ADT 2014:INFO:fcode:PPLC
Thu Apr 10 17:29:50 ADT 2014:INFO:geonameId:3688689
Thu Apr 10 17:29:50 ADT 2014:INFO:lat:4.609705849789108
Thu Apr 10 17:29:50 ADT 2014:INFO:population:7674366
Thu Apr 10 17:29:50 ADT 2014:INFO:fcodeName:capital of a political entity
Thu Apr 10 17:29:50 ADT 2014:INFO:toponymName:Beijing
Thu Apr 10 17:29:50 ADT 2014:INFO:countrycode:CN
Thu Apr 10 17:29:50 ADT 2014:INFO:fcl:P
Thu Apr 10 17:29:50 ADT 2014:INFO:fclName:city, village,...
Thu Apr 10 17:29:50 ADT 2014:INFO:name:Beijing
Thu Apr 10 17:29:50 ADT 2014:INFO:wikipedia:en.wikipedia.org/wiki/Beijing
Thu Apr 10 17:29:50 ADT 2014:INFO:lng:116.397228240967
Thu Apr 10 17:29:50 ADT 2014:INFO:fcode:PPLC
Thu Apr 10 17:29:50 ADT 2014:INFO:geonameId:1816670
Thu Apr 10 17:29:50 ADT 2014:INFO:lat:39.9074977414405
Thu Apr 10 17:29:50 ADT 2014:INFO:population:7480601
Thu Apr 10 17:29:50 ADT 2014:INFO:fcodeName:capital of a political entity
Thu Apr 10 17:29:50 ADT 2014:INFO:toponymName:Hong Kong
Thu Apr 10 17:29:50 ADT 2014:INFO:countrycode:HK
Thu Apr 10 17:29:50 ADT 2014:INFO:fcl:P
Thu Apr 10 17:29:50 ADT 2014:INFO:fclName:city, village,...
Thu Apr 10 17:29:50 ADT 2014:INFO:name:Hong Kong
Thu Apr 10 17:29:50 ADT 2014:INFO:wikipedia:en.wikipedia.org/wiki/Hong_Kong
Thu Apr 10 17:29:50 ADT 2014:INFO:lng:114.157691001892
Thu Apr 10 17:29:50 ADT 2014:INFO:fcode:PPLC
Thu Apr 10 17:29:50 ADT 2014:INFO:geonameId:1819729
Thu Apr 10 17:29:50 ADT 2014:INFO:lat:22.2855225817732
Thu Apr 10 17:29:50 ADT 2014:INFO:population:7012738
*/

If you want to access individual datasets you could probably try something like this...
for ( value in jsonElements.geonames ) {
    log.info value["name"]
}

/*this returns
Thu Apr 10 17:33:41 ADT 2014:INFO:Mexico City
Thu Apr 10 17:33:41 ADT 2014:INFO:City of Manila
Thu Apr 10 17:33:41 ADT 2014:INFO:Dhaka
Thu Apr 10 17:33:41 ADT 2014:INFO:Seoul
Thu Apr 10 17:33:41 ADT 2014:INFO:Jakarta
Thu Apr 10 17:33:41 ADT 2014:INFO:Tokyo
Thu Apr 10 17:33:41 ADT 2014:INFO:Taipei
Thu Apr 10 17:33:41 ADT 2014:INFO:Bogotá
Thu Apr 10 17:33:41 ADT 2014:INFO:Beijing
Thu Apr 10 17:33:41 ADT 2014:INFO:Hong Kong
*/

What do you mean by data store? Also, you know you can shorten your code by making it more groovy.

A: As i see it, you want to store in a properties step type and you can do the following
def idsObjectStored = context.expand( '${Properties#ids}' )
def slurper = new JsonSlurper()
idsObjectStored = slurper.parseText(idsObjectStored)

for ( value in jsonElements.shopId ) {
    log.info value
    idsObjectStored.add(value)
}

Create an entry in this property i.e. idsObjectStored with [] as initial content.
jsonSlurper will convert that in an object
idsObjectStored = slurper.parseText(idsObjectStored)

Now you only have to iterate and add all this values


text:
Q: import html to python, recognize python variable inside the html file text I have set up a webserver with Micropython as decribed here.
In the tutorial, there is an html variable that I am trying to externalize into a separate file and then read it in like so:
import codecs
with codecs.open("main.html", 'r') as f:
    html = f.read()

In principle this works nicely, there is just one flaw.
The html variable declaration has a variable called gpio_state inside it, like this:
html = """---html code stuff---""" + gpio_state + """---more html stuff---"""

The gpio_state variable resolves into ON or OFF when I have this in the .py file directly as intended.
When the html is in a different file and imported with the above method it is read as a string instead.
I see gpio_state and the """ characters in my browser.
Is it possible to import an html file with a variable in the python script?
Sorry - I probably lack some python vocabulary here and could have expressed the problem more concisely!

A: This would probably be described as reading a template, and replacing the variable parts in it. There are probably some libraries to do templating, but in MicroPython a small solution is probably enough for you.
After reading the file into a variable, you have a string, so you can use the built-in string methods such as replace(look-for, replace-with). Eg:
html2 = html.replace("gpio_state", gpio_state)

You probably shouldn't have the """ string delimiters at the start and end of the file, since this is not part of the html. Typically, in templating systems, some special character sequence is used to delimit the variable parts from the html, eg <?gpio_state?>, but if you prefer you can keep to """ + gpio_state + """, if this is unlikely to occur in the real html part.


text:
Q: CSS2 not matching as expected I have a css rule. its job is to place the left column of my site template in it's correct position.  I'm trying to optimize my css.
* html #left { left:220px }

I would expect that the below css would work the same...It does not in Chrome or IE9
#left {left:220px}

However, explicitly defining the whole path as below...works correctly.
html body div div #left

Only CSS being used on page. Verified in Chrome inspector.
html {
margin-left:auto;
margin-right:auto;
font-size:80%;
width:100%;
}

.ie7 {
font-size:80%;
width:100%;
}

.ie8 {
font-size:80%;
width:100%;
}

.ie9 {
font-size:80%;
width:100%;
}

body
{
position:relative;
text-align:center;
font: .95em "Arial","Helvetica","Trebuchet MS","Verdana","Times New Roman","Sans-Serif";
min-width:960px;
max-width:960px;
margin: 0px auto auto auto;
padding:0px 10px;
}

        #header
        {
            text-align:left;
        }

        #container {
            padding-left: 220px;      /* LC width */
            padding-right: 30px;     /* RC width */
            overflow: hidden;
            min-height:100%;
            padding-bottom:300px;
            background-color:White;
        }

        #container .column {
            position: relative;
            float: left;
            padding-bottom: 20010px;  /* X + padding-bottom */
            margin-bottom: -20000px;  /* X */
        }

        #left {
            width: 200px;             /* LC width */
            padding:0 10px;
            right: 260px;             /* LC width */
            margin-left: -100%;

        }

    /*  #right {
            width: 200px;
            padding:0px 10px;
            margin-right: -290px;
        }
        */

                #center {
            width: 100%;
            background-color:#fff;
            padding: 10px 20px;
        }

        #footer-wrapper
        {
            background-color:#fff;
        }

        #footer {
            clear: both;
            position: relative;
            background-color:#163748;
            color:white;
            padding:0;
            text-align:center;
            /*border-top:1px solid #9fa8ac;*/
            height:150px;
            padding-top:10px;
        }
        #footer p
        {
            text-align:center;
        }

#footer a
{
    color:White;

}

.clear
{
    clear: both;
}

#left
{
    left:220px;
}

A: The CSS you're trying to optimise is this:
* html #left { left:220px }

The reason you're having problems with is it because it's actually a CSS hack, designed to work with specific browsers.
In a standards-compliant browser, there are no elements above html in the DOM, and therefore * html is meaningless and will not select anything.
However in certain versions of IE, this did actually work. Therefore, using * html in a selector is a CSS hack for code that you only want to work in those versions of IE.
From memory, this particular hack only worked in IE6, which means that the person who wrote that code was trying to fix a problem in IE6 that didn't appear in other browsers by hacking around it. You'll likely find that there's another line setting the left property to something different for other browsers.
Clearly this isn't code that you're going to want to be run in IE9.
If you're lucky, you don't need to support IE6 any more, in which case you can throw this hack away entirely.
If you're unlucky, and you need to continue supporting IE6, then just keep the code as is. It isn't hurting anyone.
Hope that helps.

A: Without seeing the actual code, my guess is that this is a CSS specificity issue.
Here's a couple of articles on the topic that you might find enlightening:
http://css-tricks.com/specifics-on-css-specificity/
http://coding.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/


text:
Q: How to fit a GLM to a dataset estimating "only the post hoc values for the random effects"? My goal is to implement a cross-validation procedure for linear mixed models. Let me start with what I want to do (which is described here), and already tell you that I get stuck at step 4. The goal:

*

*Fit a GLM to the data with one subject removed (leave-one-out crossvalidation)

*Fix the model's parameter values to the estimates of this fitted model

*Fit the same model again to all data (now including the removed subject), without any major iterations estimating only the post hoc values of the random effects

*Calculate predicted values for the previously-left-out subject i Use the post hoc estimate of the random effects for this subject

*... the rest is not important for my question ...
I am struggling with point number 4. Spedfically (1) what exactly it means to estimate only the post hoc values of the random effects and (2) how I would implement that using the ´lmer´ command.
Here is an example with where I get stuck
# Lets assume we wanna do this in the inbuilt dataset sleepstudy
library(lme4)
# First, we quickly look at the data structure
str(sleepstudy)
 # 'data.frame':   180 obs. of  3 variables:
 # $ Reaction: num  250 259 251 321 357 ...
 # $ Days    : num  0 1 2 3 4 5 6 7 8 9 ...
 # $ Subject : Factor w/ 18 levels "308","309","310",..: 1 1 1 1 1 1 1 1 1 1 ...

# Then we do the cross-validation (to illustrate, for one subject only)
# Leave the following subject out
i   <- "308"
# 1.)2.)3.) Fit a model to all but this subject, fix the effects by storing it in fm1
fm1 <- lmer(Reaction ~ Days + (Days | Subject), data = sleepstudy[sleepstudy$Subject!=i,])
# 4.) Now I should estimate for all data but with zero iterations. How?

# 5.) Then I can hopefully predict values for the previously-left-out subject i
pr1 <- predict(fm1, sleepstudy[sleepstudy$Subject==i], allow.new.levels=T) #we need to allow new levels as i is not in the levels of the random effects which we fitted

Anyone having an idea or done something similar?
Thanks a lot!
JBJ


text:
Q: Update Action Trouble this is my Update Action :
        public void etat(string id)
    {

            Models.J2VEntities entity = new Models.J2VEntities();

            Models.user model = (from p in entity.user
                                 where p.iduser == id
                                 select p).SingleOrDefault();

            model.IsActive = !(model.IsActive);
            entity.user.AddObject(model);
            entity.ObjectStateManager.ChangeObjectState(model, System.Data.EntityState.Modified);
            entity.SaveChanges();
            RedirectToAction("Index", "Admin");
    }

When i excutet i got this error :

System.InvalidOperationException: An object with the same key already exists in ObjectStateManager. The existing object is in state Modified. An object can be added back to ObjectStateManager if it is added in the state.

at this line :entity.user.AddObject(model);

A: Try this instead:
public void etat(string id){
 using( var entity = new Models.J2VEntities()){
    Models.user model = (from p in entity.user
                             where p.iduser == id
                             select p).SingleOrDefault();
    model.IsActive = !(model.IsActive);
    entity.user.Attach(model);
    entity.Entry(model).State = EntityState.Modified;
    entity.SaveChanges();
 }
}

The using will ensure that your connection is disposed and closed properly to make sure you do not have memory leaks or unwanted open connections.

A: Sloved with in this way :
using (var entity = new Models.J2VEntities())
            {
                Models.user model = (from p in entity.user
                                     where p.iduser == id
                                     select p).SingleOrDefault();
                model.IsActive = !(model.IsActive);
                entity.user.ApplyCurrentValues(model);
                entity.SaveChanges();
            }


text:
Q: Transition in Corona SDK How to give transition for changing color in corona sdk.
I have tried like this, but it's not working
transition.to (show_text, {time=1000,color="rgb(0,0,0)"});

A: The following trick works.  Unfortunately it doesn't allow for very sophisticated color manipulations without using multiple transitions:
local function modify(text)
    local mt = {
        r = 0,
        g = 0,
        b = 0,
        __index = function(t, k)
            if k == "r" or k == "g" or k == "b" then
                return getmetatable(t)[k]
            end
        end,
        __newindex = function(t, k, v)
            getmetatable(t)[k] = v
            if k == "r" or k == "g" or k == "b" then
                t:setTextColor(math.round(t.r or 0), math.round(t.g or 0), math.round(t.b or 0))
            end
        end
    }
    local originalSetTextColor = text.setTextColor
    text.setTextColor = function(self,r,g,b)
        mt.r = r
        mt.g = g
        mt.b = b
        originalSetTextColor(self, r,g,b)
    end
    setmetatable(text, mt)

end

local show_text = display.newEmbossedText("I am the very model of a modern major general", display.screenOriginX,0, native.systemFont, 30);
modify(show_text)
show_text:setTextColor(255,0,255)

transition.to (show_text, {time=1000,r=0,})
transition.to (show_text, {time=1000,g=255})
transition.to (show_text, {time=1000,b=0})

A: Color is not supported in Corona's transition API at the moment. You might try to use...
show_text:setTextColor( red, green, blue )

...inside a loop and just draw and erase the text object as you alter the color values.

A: here is link use this,it works fine
http://developer.coronalabs.com/code/color-transition-wrapper


text:
Q: Center of circle on a stereographic projection (forgive my drawing skills, everything is out of scale, and I wish my sphere looked more like a sphere)
If I hava a circle on a sphere, and then map the sphere to a plane using a stereographic projection, the circle will still be a circle on the projection.
The blue thing below is the sphere.

Then projected to a plane from the point opposite to the circle center:

But depending on the projection point I choose on the sphere, the resulting circle is scaled and its original center is no longer the circle center in the projection:

So, given the circle in a radius 1 sphere (I have the position of the center in a rotation matrix, and the arc radius in radians), how can I find the center of the circle in the projection plane?

A: Intersect the spherical circle with a meridian of the sphere that passes through its center. Find the two intersection points (if you have the location of the center in spherical coordinates, that is just a matter of adding and subtracting the radius from the polar coordinate/latitude/zenith distance). Project the two intersection points to the plane. By symmetry they have to be diametrically opposite points of the image circle, so the apparent center of the image circle is halfway between them.


text:
Q: How to use .some() for all values in an array with different objects For example I have this array:
const ageArr = [{tom: 24}, {jack: 20}, {anna: 30}]

How can I use .some() to search all of the values without specifying the name?
Expected:
if (ageArr.some((el) => el > 19)) {
  console.log('Some of them are older than 19')
}
//Output: People are older than 19

A: You could use the Object.values function to get the values of the objects:

const ageArr = [{tom: 24}, {jack: 20}, {anna: 30}]

if (ageArr.some((el) => Object.values(el)[0] > 19)) {
  console.log('People are older than 19')
}

Here are some examples of what Object.values does:

[
  {tom: 24},
  {foo: 'bar', baz: 'qux'},
  {}
].forEach(x => console.log(`Object.values(${JSON.stringify(x)}) ==`, Object.values(x)))

A: @cherryblossom provided the best way of solving this problem using the function Object.values
If you're concerned about browser compatibility, keep in mind that the functions some and Object.keys works even on Internet Explorer, while Object.values doesn't
if (ageArr.some((el) => el[Object.keys(el)[0]] > 19)) {
  console.log('People are older than 19')
}

I would expand the arrow function like this:
ageArr.some((el) => {
    const key = Object.keys(el)[0];
    const value = el[key];
    return value > 19;
}


text:
Q: Can I create a new branch for an old commit in BitBucket (Mercurial)? I have tried locating the commit I want to branch from but I cant see any options to create a branch.
I also tried creating a branch but I can't see any way to select an old commit.
This question is related to my question about pushing a new branch

A: TL;DR
Use hg update -r <rev> to check out the revision you want to become the parent of the new branch.  Then, at any time before the next hg commit, use hg branch <new-branch-name> to record the name of the branch you want to create.  Make whatever changes you intend, then run hg commit to create a new commit that creates the branch.  The new commit will be the only commit in the new branch, and will be the head (singular) of that branch.
Longer description
(Note: I can only answer questions about command line options since I do not use the fancy GUIs.)
In Mercurial, you create a branch by:

*

*Using hg branch with the branch name:
hg branch newbranch

Mercurial will reply with:
marked working directory as branch newbranch
(branches are permanent and global, did you want a bookmark?)

(the second sentence is omitted if there are already open branches other than default).

*Making a new commit.
Until you execute step 2, the branch you "made" with hg branch does not exist: it's simply the idea of a branch.  This idea is saved along with the state of the working-tree.
Note that whenever you create a new commit, the new commit has a parent commit (or occasionally two parents, when concluding a merge).  The ID of the parent of the new commit is the ID of the current commit, i.e., revision ..  This is why you must first update to the desired revision.
The work-tree is, in effect, a proposed commit.  Until you make it differ from the current commit, though, there's no change-set to commit.  (If you are familiar with Git, this is similar to its internals, though there are some key differences.  In Git, the current revision is named HEAD rather than ., and instead of the work-tree being the proposed commit, Git uses its "index" as the proposed commit.  More critically, in Git, a commit is on some number of different branches simultaneously, so except for two special cases, Git creates the branch name immediately, rather than later once there's a commit for it.  This is because the new branch and old branch share all the old branch's commits—a peculiar sort of madness, though it all works out in the end.)
This shows up in the output of hg summary, which describes:

*

*the ID of the parent your new changeset would have if you made the commit now, i.e., the revision ID of revision .;

*the name of the current branch (the branch itself may not exist yet);

*the work-tree state as compared to revision .;

*the distance . has from the current head(s) of the current branch (the branch containing .);

*the number of draft and secret phase commits, if there are any;

*and a few optional additional bits of information.

A head in Mercurial is any commit with no descendant commits in the same branch.  Updating to an old revision that is not itself a head, then creating a new commit, will automatically create a new head, increasing the number of heads by one.  If that new head is in an existing branch, the existing branch's number of heads likewise increases by one.  If that new head results in the creation of a new branch, the new branch now springs into existence and has one commit, which is a head commit.
To create a new named branch, this last is just what you want.  So you need to update to the starting revision—this can be an existing branch head, if you like—and then switch to the new branch, which does not actually exist yet.  You can then make a commit to create the branch, whose single revision is the new branch's head.  (If the previous commit was a, or the, head of the old branch, it remains a head.)


text:
Q: Object is possibly 'undefined' when using array values with styled-components I'm building a Skeleton component that accepts a prop called circleSizes, which is an array of numbers to set the width and height of the Skeleton.
This is the component:
export const SkeletonHandler: React.FC<SkeletonHandlerProps> = ({
  count = 1,
  circle = false,
  circleSizes = [50, 50],
}) => {
  return (
    <SkeletonWrapper count={count} circleSizes={circleSizes}>
      <Skeleton count={count} circle={circle} />
    </SkeletonWrapper>
  );
};

My types.ts:
export type SkeletonHandlerProps = {
  count?: number;
  circle?: boolean;
  circleSizes?: Array<number>;
};

I know that if I remove the ?, the error will go away but I don't want this property to be required.
And my styled-components file:
export const SkeletonWrapper = styled.div<SkeletonHandlerProps>`
  width: ${(circle) => (circle ? 'fit-content' : '100%')};
  ${({ circle, circleSizes }) =>
    circle &&
    css`
      .react-loading-skeleton {
        width: ${circleSizes[0]};
        height: ${circleSizes[1]};
      }
    `}
`

Image error:
What I have tried:

*

*Putting a default value for the circleSizes array at props, e.g: circleSizes = [50, 50]

*Putting a default value on types.ts, e.g: circleSizes?: Array<number> | [50, 50];

*Converting circleSizes to number on the styled-components file, e.g: width: ${Number(circleSizes[0])};
What I'm doing wrong?

A: it complains because you are using the brackets operand on a variable that might be undefined so try adding a validity check before circleSizes && circleSized[1]


text:
Q: Web deploy from Visual Studio 2015 fails with no errors I'm trying to publish a web project to an Azure App Service site.  The compile runs and then the publish routine immediately fails with no error messages.  The Error List window in Visual Studio 2015 is displayed, but there's nothing there.
The Output window contains the following:
========== Build: 1 succeeded, 0 failed, 1 up-to-date, 0 skipped ==========
========== Publish: 0 succeeded, 1 failed, 0 skipped ==========

I've tried resetting the publish profile, via the Azure Portal.  That allowed me to publish one time.  I tried to publish again and received the same, Publish failed message in the footer bar of Visual Studio:

There are no other indications of an error or any clues as to what the problem might be.
I have several other web projects in the solution that I'm using and they all seem to be working.  I have no idea what's different about this project that it is so problematic with trying to publishing.  It's just a standard ASP.NET MVC project.
Update:
I've discovered that if I rebuild the project (not just build) that I can publish successfully every time.  I'm not sure what that does, as I'm usually only pushing *.js files.

A: Sometimes there are some locks on the app pool on Azure that prevents publishing, try recycle the app service, download the publisher profile and publish.

A: I had faced a similar issue and fixed it by installing the latest SDK. Install it from here: https://azure.microsoft.com/en-in/downloads/, redownload the publishing profile and then re-try the operation.


text:
Q: How to use fgets and feof when dealing with stdin stream and EOF? below is a piece of code in my textbook:
#define MAXLINE  8192

int main()
{
    char cmdline[MAXLINE];

    fgets(cmdline, MAXLINE, stdin);

    if (feof(stdin))
    {
       exit(0);
    }

    printf("the string is %s", cmdline);

    exit(0);
}

and the definition of fgets is

reads a line from the specified stream and stores it into the string pointed to by str. It stops when either (n-1) characters are read, the newline character is read, or the end-of-file is reached, whichever comes first.

My questions are:
Q1-if I run this program in shell and start to type, how to I indicate EOF to stdin? I have tried Ctrl + D, but I can still keeping on typing until I hit Enter, so Enter is more like EOF to stdin?
Q2-why it need to use feof to test the EOF indicator for stdin? we can just get rid of if (feof(stdin))  exit(0); the output is the same.

A:
Q1-if I run this program in shell and start to type, how to I indicate EOF to stdin? I have tried Ctrl + D, but I can still keeping on typing until I hit Enter, so Enter is more like EOF to stdin?

Why do I need to type Ctrl-D twice to mark end-of-file?

Q2-why it need to use feof to test the EOF indicator for stdin? we can just get rid of if (feof(stdin))  exit(0); the output is the same.

The output is the same because code has not been tested with an immediate end-of-file.
When fgets() returns NULL, it is due to end-of-file or rare input error.
Testing feof(stdin) is a poor approach to test if cmdline has valid data in it.  It simple reports that end-of-file was detected.  When true, cmdline may or may not has valid data in it.  When false, cmdline has valid data if an input error had not just occurred.  When false and an input error had just occurred, cmdline[] are indeterminate.
In any case, it is an insufficient test.  Better to test the return value of fgets().
#define MAXLINE  8192

int main()    {
    char cmdline[MAXLINE];
    if (fgets(cmdline, MAXLINE, stdin) == NULL) {
      // end-of-file or rare input error occurred
      exit(0);
    }

    printf("the string is `%s`", cmdline);
    exit(0);
}


text:
Q: What are the likely pain points to upgrade an application to Spring 3.0 Given an application using Spring 2.5, when migrating to Spring 3.0 what are the likely areas that will be pain points, i.e. things that the development team will have to spend time on to get things working. Assume the team would not try to take advantage of new Spring features as part of the upgrade, but just get the application to the state where it works as it did on 2.5. Taking advantage of 3.0 features would be the next steps to consider.
Edit: I have revised the question to focus on the pain points of the upgrade, which is what I'm really after.

A: Probably the biggest change in Spring 3.0 is that it now requires J2SE 5.0.
One of the Spring developers reply for a compatibility question in this blog entry.

Spring 3.0 aims to be 99% backwards
  compatible with Spring 2.5. The core
  APIs and SPIs will remain stable in
  order to keep existing extensions (and
  of course also existing application
  code) working. Introducing generics
  and varargs, as we've done in M1 and
  M2, should still preserve binary
  compatibility. That said, we generally
  recommend rebuilding your applications
  for Spring 3.0, in order to catch
  potential API issues early. This will
  also allow you to get the maximum
  benefit from Spring 3.0's Java 5 API
  refinements.

A: If you're lucky, then nothing will need changing, it should all just work. The Spring guys are very careful to retain backwards compatibility.
The biggest reason I can think of for it not working is if you're using code that was deprecated in 2.5, and marked for removal in 3.0  You can find that list here.


text:
Q: What is the best way to call SOAP web service with Android? I need some advices.
I've a WSDL and I need to call some services.
For you, What is the best way to callSOAP web service with Android?
I know that we can:

*

*use the library Ksoap 2

*create xml templates and send them by a simple http protocol.

*Or i can do something like:

  public class AppelService {

  private static final String NAMESPACE = "http://my-website.com";
  private static final String URL = "http://mon-example-web-services/wsdl.WSDL";
  private static final String SOAP_ACTION = "getWeather";
  private static final String METHOD_NAME = "getWeather";

  private String getWeather(String city) {

    try {
      SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
      request.addProperty("city", city);

      SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
      envelope.setOutputSoapObject(request);

      AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(URL);
      androidHttpTransport.call(SOAP_ACTION, envelope);

    } catch (Exception e) {
      Log.e("getWeather", "", e);
    }
  }
}

From your own experience, what do you think is the best way to do it ?
any help is appreciated.
Thanks.

A: I would definitely advocate using ksoap2-android libary. I have done this very research, and nothing beats using this library in terms of versatility.
The code you have provided is ksoap2.
From the ksoap2-android website:

The ksoap2-android project provides a lightweight and efficient SOAP
  library for the Android platform.
It is a fork of the kSOAP2 library that is tested with the Android
  platform in mind. It also has a bunch of more features and
  enhancements and takes in bug fixes and contributions and releases
  regularly. It is also easily available for Maven and Ant users alike.

A: I personally use ksoap2-android because it is pretty straightforward for parsing response object...
If you are comfortable with it, ,why would you use something else ?
A bientôt ;)
Edit : I mean ksoap2 -android of course


text:
Q: TFS checkout failing in jenkins TFS checkout is failing in Jenkins. It is giving below error. Previously It worked fine,but from past 4 days I am getting this error. Few file are checking out and getting this error:

FATAL: java.lang.RuntimeException:
  com.microsoft.tfs.core.clients.versioncontrol.exceptions.VersionControlException:
  com.microsoft.tfs.core.exceptions.TECoreException: Server was unable
  to process request. ---> Object reference not set to an instance of an
  object. com.microsoft.tfs.core.ws.runtime.exceptions.SOAPFault: Server
  was unable to process request. ---> Object reference not set to an
  instance of an object.

I have tried with different versions of TFS plugins. Currently I have installed  TFS 5.142 version  and Jenkins version 2.176.2


text:
Q: Linux c++ error: undefined reference to 'dlopen' I work in Linux with C++ (Eclipse), and want to use a library.
Eclipse shows me an error:
undefined reference to 'dlopen'

Do you know a solution?
Here is my code:
#include <stdlib.h>
#include <stdio.h>
#include <dlfcn.h>

int main(int argc, char **argv) {
    void *handle;
    double (*desk)(char*);
    char *error;

    handle = dlopen ("/lib/CEDD_LIB.so.6", RTLD_LAZY);
    if (!handle) {
        fputs (dlerror(), stderr);
        exit(1);
    }

    desk= dlsym(handle, "Apply");

    if ((error = dlerror()) != NULL)  {
        fputs(error, stderr);
        exit(1);
    }

    dlclose(handle);
}

A: @Masci is correct, but in case you're using C (and the gcc compiler) take in account that this doesn't work:
gcc -ldl dlopentest.c

But this does:
gcc dlopentest.c -ldl

Took me a bit to figure out...

A: The topic is quite old, yet I struggled with the same issue today while compiling cegui 0.7.1 (openVibe prerequisite).
What worked for me was to set: LDFLAGS="-Wl,--no-as-needed"
in the Makefile.
I've also tried -ldl for LDFLAGS but to no avail.

A: you can try to add this
LIBS=-ldl CFLAGS=-fno-strict-aliasing

to the configure options

A: You needed to do something like this for the makefile:
LDFLAGS='-ldl'
make install

That'll pass the linker flags from make through to the linker. Doesn't matter that the makefile was autogenerated.

A: You have to link against libdl, add

-ldl

to your linker options

A:
this doesn't work:
gcc -ldl dlopentest.c

But this does:
gcc dlopentest.c -ldl

That's one annoying "feature" for sure

I was struggling with it when writing heredoc syntax and found some interesting facts. With CC=Clang, this works:
$CC -ldl -x c -o app.exe - << EOF
#include <dlfcn.h>
#include <stdio.h>
int main(void)
{
  if(dlopen("libc.so.6", RTLD_LAZY | RTLD_GLOBAL))
    printf("libc.so.6 loading succeeded\n");
  else
    printf("libc.so.6 loading failed\n");
  return 0;
}
EOF

./app.exe

as well as all of these:

*

*$CC -ldl -x c -o app.exe - << EOF

*$CC -x c -ldl -o app.exe - << EOF

*$CC -x c -o app.exe -ldl - << EOF

*$CC -x c -o app.exe - -ldl << EOF
However, with CC=gcc, only the last variant works; -ldl after - (the stdin argument symbol).

A: I was using CMake to compile my project and I've found the same problem.
The solution described here works like a charm, simply add  ${CMAKE_DL_LIBS} to the target_link_libraries() call

A: I met the same problem even using -ldl.
Besides this option, source files need to be placed before libraries, see undefined reference to `dlopen'.

A: In order to use dl functions you need to use the -ldl flag for the linker.
how you do it in eclipse ?

Press Project --> Properties --> C/C++ build --> Settings --> GCC C++ Linker --> Libraries -->
  in the "Libraries(-l)" box press the "+" sign --> write "dl" (without the quotes)-> press ok --> clean & rebuild your project.

A:  $gcc -o program program.c -l <library_to_resolve_program.c's_unresolved_symbols>

A good description of why the placement of -l dl matters
But there's also a pretty succinct explanation in the docs
From $man gcc

   -llibrary
   -l library
       Search the library named library when linking.  (The second
       alternative with the library as a separate argument is only for POSIX
       compliance and is not recommended.)

       It makes a difference where in the command you write this option; the
       linker searches and processes libraries and object files in the order
       they are specified.  Thus, foo.o -lz bar.o searches library z after
       file foo.o but before bar.o.  If bar.o refers to functions in z,
       those functions may not be loaded.

A: Try to rebuild openssl (if you are linking with it) with flag no-threads.
Then try to link like this:
target_link_libraries(${project_name} dl pthread crypt m ${CMAKE_DL_LIBS})

A: In earlier versions(~2.7) of GNU tool chain, glibc did not have direct interface to link loader(dlopen and dlsym functions), so you had to provide -ldl(libdl) at compile time. You don't have to do that anymore with latest glibc version. Just include <dlcfn.h> and you are good to go.


text:
Q: Create groups of functions with same name within single module without classes I am writing a card game simulator. During play, I want different players to have different strategies. My idea is to have 2 functions specified for a given agent than can be imported. These functions would have the same signatures. I know how to do this with classes and inheritance, but I'm trying to code this project entirely functionally. Here is what I have if I were to do it with classes:
class Agent:
  def __init__(self,position):
    self.pos = position

  def flip_two(self,gs):
    pass

  def regular_move(self,gs):
    pass

class Random_Agent(Agent):
  def flip_two(self,gs):
    #some code that alters gs randomly

  def regular_move(self,gs):
    #some code that alters gs randomly

class etc_Agents(Agent):
  .
  .
  .

The best answer I can think of so far is to put each agent in a new file, since modules would be a way to group the functions.
Thanks for any insight!

A: If you wish to group related functions, you could place them in a dictionary like so:
options = {
    'a' : {'sameName' : lambda x: x*2},
    'b' : {'sameName' : lambda x: x**2}
    }
print(options['a']['sameName'](5))
print(options['b']['sameName'](5))


text:
Q: Bash script; Cause processB to exit when processA exits Say I have a bash script that runs two separate processes together, like this:
trap "kill 0" EXIT

./processA &
./processB &

wait

This works great if all I ever need is to hit ctrl+c to exit both. However, if processA exits, processB continues to run.
What I need is a way to run processB that will cause processB to exit as soon as processA exits. (I don't need it to work the other way around though).

A: While the comment of "oguz ismail" is working with me when I tested it, I'd like to make an easier to follow alternative:
trap "kill -9 0" EXIT

./processA &
P1=$!  # to save process ID to P1

./processB &
P2=$!  # to save process ID to P2

wait $P1  # assuming A will finish first, so wait for P1


text:
Q: How to modify the size of Flash stage programmatically Initially I set the stage width 500 and height 400. After make a file, now I want it to be  700*500 and I want to show  all content in stage. How can I achieve this?
Any help will be appreciated.

A: If it's a website you're creating you can programmatically control its size via call through a class called ExternalInterface which in turn calls JavaScript-functions. JavaScript can then be used to resize the embedded flash object.
You can find another post about this here: How can I resize a swf during runtime to have the browser create html scrollbars?