text:
Q: Create global variable in utils.js file in node.js Hi I'm currently trying to figure it out how to properly define global variable in node.js. I know it is not a good practice to do this, but in this particular screnario it's the only way to do this without using connection to database.
I'm getting data from github API to display some information, I'm trying to store them in the global variable. It should allow me to e.g pass specific object from first global list to new global list that display only chosen items.
I have file called utils.js that have this two empty arrays that should be global:
let repoItems = [];
let bookmarkedItems = [];

exports.repoItems = repoItems;
exports.bookmarkedItems = bookmarkedItems;

Then I have another file that fetch and should assign items to the first global variable, but it looks like it doesn't. Because in the moment I'm trying to chose one item & push it into second empty array it's impossible, I'm getting empty array. I'm not sure if the mistake is taken because of bad implementation of global variable from other file, or something else :/
Below I include the fetching part of code, with bold part that I'm confused with:
let utils = require('../utils');

let {
    repoItems,
} = utils;

router.get('/', async (req, res) => {
    try {
        const result = await fetchGithubAPI(`searching word`);
        const urls = result.map(url => url);
        console.log(urls);
        res.render('repositories.ejs', {
            'data': urls
        });
    } catch (e) {
        console.log(e);
    }
});

async function fetchGithubAPI(search) {
    const response = await fetch(`https://api.github.com/?q=${search}`, {
        method: 'GET',
        headers: {
            'Accept': 'application/vnd.github.v3+json',
            'Content-Type': 'application/json',
        },
    });
    const data = await response.json();
    **repoItems = data.items.map(item => item);**
    return repoItems;
}

A: Try:
let repoItems = require('./utils').repoItems
instead of
let {
    repoItems,
} = utils;

A: if you remove
let {
repoItems,

} = utils;
you can try using
utils.repoItems = data.items.map(item => item)
I tried an example setup for it
--utils.js
module.exports.someValue = 3;
module.exports.setSomeValue = (value) => {someValue = value}
--index.js
const utils = require('./utils');

console.log(utils.someValue);// 3
utils.someValue = 5
console.log(utils.someValue);// 5

Update after knowing about getter and setter methods in Js
You can refer to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set
this is another way to change value of any private properties in JS


text:
Q: Why is place.address_components always undefined? (Maps API v.3) I have a simple search feature on my website and I'm attempting to access the address_components of the place result object. But it's always undefined.
Essentially what I'm try to retrieve is the postcode for displaying in the infowindow for each marker. I've previously used formatted_address for each place but it doesn't contain the postcode. I'm assuming that either long_name or short_name may contain the postcode but I don't know how to retrieve it.
This is the code I have so far:
function initialize() {

    var markers = [];
    var map = new google.maps.Map(document.getElementById('admin-map-canvas'), {
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });
    var vges = new google.maps.LatLng(x, y);

    var defaultBounds = new google.maps.Circle({center: vges, radius: 2000}).getBounds();
    map.fitBounds(defaultBounds);

  // Create the search box and link it to the UI element.
  var input = /** @type {HTMLInputElement} */(
    document.getElementById('pac-input'));
  map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

  var searchBox = new google.maps.places.SearchBox(
    /** @type {HTMLInputElement} */(input));

  // Listen for the event fired when the user selects an item from the
  // pick list. Retrieve the matching places for that item.
  google.maps.event.addListener(searchBox, 'places_changed', function() {
    var places = searchBox.getPlaces();

    for (var i = 0, marker; marker = markers[i]; i++) {
        marker.setMap(null);
    }

    var infowindow = new google.maps.InfoWindow({
        content:"",
        maxWidth: 300
      });

    // For each place, get the icon, place name, and location.
    markers = [];
    var bounds = new google.maps.LatLngBounds();
    for (var i = 0, place; place = places[i]; i++) {
        var image = {
            url: place.icon,
            size: new google.maps.Size(71, 71),
            origin: new google.maps.Point(0, 0),
            anchor: new google.maps.Point(17, 34),
            scaledSize: new google.maps.Size(25, 25)
        };

      // Create a marker for each place.
      var marker = new google.maps.Marker({
        map: map,
        title: place.name,
        position: place.geometry.location
      });

      if(typeof place.address_components=='undefined'){
        address= "foo";
      }

      else{
        address= place.address_components[0];
      }

      markers.push(marker);

      bindInfoWindow(marker,map,infowindow,place.name,address);

      bounds.extend(place.geometry.location);
  }

  function bindInfoWindow(marker,map,InfoWindow,strDescription,Address){

    google.maps.event.addListener(marker, 'click', function() {
        infowindow.setContent(strDescription + ", " + Address);
        infowindow.open(map,marker);
    });

  }

  map.fitBounds(bounds);
});

  // Bias the SearchBox results towards places that are within the bounds of the
  // current map's viewport.
  google.maps.event.addListener(map, 'bounds_changed', function() {
    var bounds = map.getBounds();
    searchBox.setBounds(bounds);
  });
}

$(document).ready(function(){
    google.maps.event.addDomListener(window, 'load', initialize);
});

A: EDITED: address_components are only available in the results of a Place Details request, not a Place Search request. So you'll need to pass the reference ID of each place through a Place Details request in order to get the postal_code.

@Tuco has a good answer here: Retrieving Postal Code with Google Maps Javascript API V3 Reverse Geocode
The code is:
var address = place.address_components;
var code = address[address.length -1].long_name;

This works because the postal code is always the last item in the address_components array.
EDIT: You mentioned address_components always being undefined; your code uses address_component (without the s) in the typeof check, so it's always undefined.

A: place.postal_code doesn't exist.
bindInfoWindow(marker,map,infowindow,place.name,place.postal_code);

perhaps you were looking for place.formatted_address?

redpajama_set_name: RedPajamaStackExchange


text:
Q: grep file content from piped content My dummy file looks like this
cat dummy_file
    Tom
    Jerry

My piped content looks like this
COMMAND |
    Tom Cat
    Jerry Mouse
    Spike Dog

I want to grep only those piped lines that are in dummy_file.
I can do this by creating intermediate file.
COMMAND > intermediate_file
grep -w -F -f dummy_file intermediate file
    Tom Cat
    Jerry Mouse

How can I achieve this without creating an intermediate file and just grep'ing piped content?
Tried this, but it doesn't work:
COMMAND |
    xargs -I {} grep -w -F -f dummy_file -- NO RESULT

Or this:
COMMAND |
    xargs -I {} grep {} -w -F -f dummy_file -- ALL LINES ARE PRINTED

A: grep accepts input from stdin. Just do
COMMAND | grep -w -F -f dummy_file

A: You could use join command ;)
join --nonocheck-order -j1 <(COMMAND|sort) <(cat dummy_file|sort)|cut -d -f1
# -j1 indicates the column to join in the two commands output
# it's equivalent to -11 -11 (first and second output)
# cut to print only the first column which is common to two orders

See man join for more details.


text:
Q: Autofit columns XSLT FO to PDF - Altova StyleVision I created a XLST-FO transformation with Altova StyleVision. The HTML output looks really fine, but if I transform my XML to PDF via Apache FOP 1.1, the (nested) table columns don't autofit like they did when using the HTML output, but have all the same size which totally screws my output. Any ideas how to realize this with XLST 1.0 ?

Thanks in advance!

A: FOP does not support automatic table layout ("autofit" tables) yet.
If the fo:table doesn't have fo:table-column children (or they don't have the column-width property), the available width is equally parted between the columns.
This is what is happening with you table:

*

*each column of the outermost table, including the one with the nested tables, is given 1/3 (33.3%) of the available width

*the first nested tables has 4 columns, each of which is given 1/4 * 1/3 (8.3%) of the available width

*each column of the innermost table is given 1/3 * 1/4 * 1/3 (2.8%) ot the available space

In order to create a better looking PDF, you have to modify you xsl stylesheet so that your fo:table elements contain fo:table-column elements with a column-width property, either expressed as a length or a percentage.


text:
Q: Troubleshoot Unity not building in Travis CI I've set up Travis CI with my GitHub repo, which holds my Unity project, and it currently automatically attempts to build my projects, but has so far not succeeded once. After much fiddling, research and troubleshooting, it now reaches the point where Travis successfully downloads and installs the files needed (Yay! Progress), but it gets stuck in the build.
This is the ouput
Attempting to build GodGame for Windows

No output has been received in the last 10m0s, this potentially indicates a stalled build or something wrong with the build itself.

Check the details on how to adjust your build configuration on: https://docs.travis-ci.com/user/common-build-problems/#Build-times-out-because-no-output-was-received

The build has been terminated

My .travis.yml has
language: objective-c
osx_image: xcode8.1
rvm:
- 2.2
before_install:
- chmod a+x ./Script/install.sh
- chmod a+x ./Script/build.sh
install:
- ./Script/install.sh
script:
- ./Script/build.sh

My install.sh has
#!/bin/sh

BASE_URL=http://netstorage.unity3d.com/unity
HASH=46dda1414e51
VERSION=2017.2.0f3

download() {
  file=$1
  url="$BASE_URL/$HASH/$package"

  echo "Downloading from $url: "
  curl -o `basename "$package"` "$url"
}

install() {
  package=$1
  download "$package"

  echo "Installing "`basename "$package"`
  sudo installer -dumplog -package `basename "$package"` -target /
}

# See $BASE_URL/$HASH/unity-$VERSION-$PLATFORM.ini for complete list
# of available packages, where PLATFORM is `osx` or `win`

install "MacEditorInstaller/Unity-$VERSION.pkg"
install "MacEditorTargetInstaller/UnitySetup-Windows-Support-for-Editor-$VERSION.pkg"
install "MacEditorTargetInstaller/UnitySetup-Mac-Support-for-Editor-$VERSION.pkg"
install "MacEditorTargetInstaller/UnitySetup-Linux-Support-for-Editor-$VERSION.pkg"

And my build.sh has
#!/bin/sh

project="GodGame"

echo "Attempting to build $project for Windows"
/Applications/Unity/Unity.app/Contents/MacOS/Unity
  -batchmode
  -nographics
  -silent-crashes
  -logFile $(pwd)/unity.log
  -projectPath $(pwd)
  -buildWindowsPlayer "$(pwd)/Build/windows/$project.exe"
  -quit

echo "Attempting to build $project for OS X"
/Applications/Unity/Unity.app/Contents/MacOS/Unity
  -batchmode
  -nographics
  -silent-crashes
  -logFile $(pwd)/unity.log
  -projectPath $(pwd)
  -buildOSXUniversalPlayer "$(pwd)/Build/osx/$project.app"
  -quit

echo "Attempting to build $project for Linux"
/Applications/Unity/Unity.app/Contents/MacOS/Unity
  -batchmode
  -nographics
  -silent-crashes
  -logFile $(pwd)/unity.log
  -projectPath $(pwd)
  -buildLinuxUniversalPlayer "$(pwd)/Build/linux/$project.exe"
  -quit

echo 'Logs from build'
cat $(pwd)/unity.log

echo 'Attempting to zip builds'
zip -r $(pwd)/Build/linux.zip $(pwd)/Build/linux/
zip -r $(pwd)/Build/mac.zip $(pwd)/Build/osx/
zip -r $(pwd)/Build/windows.zip $(pwd)/Build/windows/

If it helps, here is my .gitignore. Is there maybe a line in here I need to remove?
###
# Unity folders and files
###
[Aa]ssets/AssetStoreTools*
[Bb]uild/
[Ll]ibrary/
[Ll]ocal[Cc]ache/
[Oo]bj/
[Tt]emp/
[Uu]nityGenerated/
# file on crash reports
sysinfo.txt
# Unity3D generated meta files
*.pidb.meta

###
# VS/MD solution and project files
###
[Ee]xportedObj/
*.booproj
*.csproj
*.sln
*.suo
*.svd
*.unityproj
*.user
*.userprefs
*.pidb
.DS_Store

###
# OS generated
###
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
Icon?
ehthumbs.db
Thumbs.db

Note that it does build on my local machine when I try straight from Unity.
Thanks in advance for anyone who can help. Keep in mind, I've never used CI before, so this is me also trying to learn. I'm also open to any suggestions for other CI solutions. Something free, preferably something that doesn't need my project to be open source (Private repo), and (preferably) cloud-based.

A: You are missing \ in your build commands. Add it for separate lines, because right now it's not getting the flags. For example:
echo "Attempting to build $project for OS X"
/Applications/Unity/Unity.app/Contents/MacOS/Unity \
  -batchmode \
  -nographics \
  -silent-crashes \
  -logFile $(pwd)/unity.log \
  -projectPath $(pwd) \
  -buildOSXUniversalPlayer "$(pwd)/Build/osx/$project.app" \
  -quit


text:
Q: Skip processing files during Gradle build I'm in the process of migrating my build system from ANT to Gradle (as ANT/ADT is now no longer supported by Google) and I ran into an issue in one of the test packages. There is a test that works with an empty png (as if somebody ran 'touch empty.png') and a corrupted png. These png files are in our res/drawable-hdpi folder, as they should be. When building though, Gradle uses libpng to do some sort of processing and it errors on these two files.
My question is: can I tell Gradle to skip processing on these two files, or is there another way to get around this issue?
BTW, on a whim I tried to rename the files to .xml (the only other allowed format) and, still, it wouldn't parse.

A: To give an answer to others who find this question, I used horatius' answer and made the /res/raw directory and put my corrupted and empty png files in there.  Gradle didn't try and process them and they still get indexed by R.java.


text:
Q: White square on area with scrollbar I have a custom Scroll bar style, but it has this annoying little white square. I want to remove it, any ideas how?
Annoying Little White Square:

Edit: it might be a repeat button, I think

A: The problem is clearly related to your style.
And how to answer your question without seeing this style?
Based on my attempt to guess what you might have in the style, but I assume that you do not change the default ScrollViewer template, you only set values for its properties.
If you look at the default template, there is a rectangle x:Name="Corner" in the corner between the ScrollBar's.
<ControlTemplate x:Key="ScrollViewerControlTemplate.Default"
                    TargetType="{x:Type ScrollViewer}">
    <Grid x:Name="Grid" Background="{TemplateBinding Background}">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="Auto"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Rectangle x:Name="Corner"
                    Grid.Column="1" Grid.Row="1"
                    Fill="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/>
        <ScrollContentPresenter x:Name="PART_ScrollContentPresenter"
                                Grid.Column="0" Grid.Row="0"
                                CanContentScroll="{TemplateBinding CanContentScroll}"
                                CanHorizontallyScroll="False" CanVerticallyScroll="False"
                                ContentTemplate="{TemplateBinding ContentTemplate}"
                                Content="{TemplateBinding Content}"
                                Margin="{TemplateBinding Padding}"/>
        <ScrollBar x:Name="PART_VerticalScrollBar"
                    Grid.Column="1" Grid.Row="0"
                    AutomationProperties.AutomationId="VerticalScrollBar"
                    Cursor="Arrow"
                    Maximum="{TemplateBinding ScrollableHeight}" Minimum="0"
                    Visibility="{TemplateBinding ComputedVerticalScrollBarVisibility}"
                    Value="{Binding VerticalOffset, Mode=OneWay, RelativeSource={RelativeSource TemplatedParent}}"
                    ViewportSize="{TemplateBinding ViewportHeight}"/>
        <ScrollBar x:Name="PART_HorizontalScrollBar"
                    AutomationProperties.AutomationId="HorizontalScrollBar"
                    Cursor="Arrow"
                    Grid.Column="0" Grid.Row="1"
                    Maximum="{TemplateBinding ScrollableWidth}"
                    Minimum="0"
                    Orientation="Horizontal"
                    Visibility="{TemplateBinding ComputedHorizontalScrollBarVisibility}"
                    Value="{Binding HorizontalOffset, Mode=OneWay, RelativeSource={RelativeSource TemplatedParent}}"
                    ViewportSize="{TemplateBinding ViewportWidth}"/>
    </Grid>
</ControlTemplate>

The background color of this rectangle is set by DynamicResource with key {x:Static SystemColors.ControlBrushKey}.
Therefore, all you can do without changing the template is to create a new resource with the same key, but with a different color.
The resource can be set in the same place where you set your style.
An example of defining this resource:
    <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}"
                     Color="Red"/>

If you do change the template, then you can simply delete this rectangle, then this corner will be the background color of the ScrollViewer.
You can also, after removing it, stretch one of the ScrollBars to this corner.


text:
Q: auto auto function template in DLang From https://dlang.org/library/std/typecons/nullable.html:
auto auto nullable(T) (
  T t
);

What is this "double auto"?

A: It's a bug in the Ddox documentation generator. You can use Ddoc: https://dlang.org/phobos/std_typecons
Ddoc (DMD's built-in documentation generator) was there in the beginning and is the older system. Ddox was intended to be a replacement and thus both version are online, so that Ddox could be battle-tested. However, it still has a few issues which is why it hasn't replaced DMD's built-in documentation generator so far.


text:
Q: Plugin is too old, please update to a more recent version, or set ANDROID_DAILY_OVERRIDE "some number" today when i start new  project an error occured said plugin is too old.
 and i click fix plugin version and fix project but the same error is still there after fixing plugin. Here is my application gradle file.
'

buildscript {
     repositories {
         jcenter()
     }
    dependencies {
         classpath 'com.android.tools.build:gradle:2.2.0-alpha6'
   // NOTE: Do not place your application dependencies here; they belong
   // in the individual module build.gradle files

}
  }
allprojects {
     repositories {
        jcenter()
     }
  }'
task clean(type: Delete) {
     delete rootProject.buildDir
  }

A: Just set new ANDROID_DAILY_OVERRIDE value using terminal
launchctl setenv ANDROID_DAILY_OVERRIDE <your-value-on-error-message>
Need to do this every day


text:
Q: Having issues using SuperWebSocket NuGet V0.9.0.0 and SuperSocket NuGet V1.6.6.1 together I am upgrading to latest versions of SuperWebSocket v0.9.0.0 and SuperSocket v1.6.6.1.
But having issues as SuperWebSocket is failing to load any v1.6.6.1 assemblies coming from SuperSocket NuGet package and keeps looking for 1.6.0.4 versions of these assemblies that are there in SuperWebSocket v0.9.0.0 NuGet package.
Is there a way I can use SuperSocket NuGet dlls v1.6.6.1 compiled against .Net 4.5 with SuperWebSocket v0.9.0.0 compiled against .Net 4.0?


text:
Q: Library, Framework, or Platform to dynamically build workflows (DAG) and validate input/output of tasks before running? I am searching for a framework, platform or library that will allow me to implement a set of atomic tasks or operations and store them in a repository. Afterwards, I want to dynamically combine or compose them into larger jobs in the form of directed acyclic graphs. An example could look like the following: Task 1 and Task 2 each produce an output, both of which are consumed by Task 3, and Task 3's output is processed by Task 4.
task 1 |
       |--> task 3 --> task 4
task 2 |

I've done some digging and there seems to be a flood of different tools that would fit the example above. Apache Airflow, Dagster, Luigi, Spring Cloud Data Flow, etc. among others.
However, so far I have not been able to see how the following use case could be addressed with these tools. I would like to verify that the inputs and outputs of each task match and a meaningful workflow is built before I start executing the workflow. An example that I would like to dynamically compose and validate could look like this:
task 1<None, Int> |
                  |--> task 3<(Int, Int), Int> --> task 4<Int, None>
task 2<None, Int> |

This job/workflow should validate without problems, since the inputs and outputs of the individual tasks match and the job can be run without problems. Since the job was successfully validated without any problems, it can now be executed.
task 1<None, Int>    |
                     |--> task 3<(Int, Int), Int> --> task 4<Int, None>
task 2<None, String> |

However, this job/workflow should throw a warning or error before even starting with the execution, since the ouputs of task 1 and task 2 do not match the required input of task 3.
I've seen that many tools support runtime checking of parameters, but this would mean that task 1 and task 2 would already have been executed. Which is something that I would like to avoid. Is it possible to validate the workflow before execution using any of the tools mentioned above or a comparable framework? As the programming languages Java or Python would be preferred, but this is not a strict requirement.
Thanks for your help!

A: I have been working with dagster for quite sometime now and it has become a de-facto tool for data-pipeline orchestrations. Yes, you are absolutely right.  the type checking happens at run-time only i.e. before and after the execution of the op/solid. Here is an example dagster snippet (python).

from dagster import In, Out, graph, op
@op(out={"out_1": Out(dagster_type=int)}) def op_1(_):
return 10
@op(out={"out_2": Out(dagster_type=str)}) def op_2(_):
return str(20)
@op(
ins={"arg_1": In(dagster_type=int), "arg_2": In(dagster_type=int)},
out={"result": Out(dagster_type=int)}, ) def op_3(_, arg_1, arg_2):
result = arg_1 + arg_2
return result
@graph def test_graph():
op_1_result = op_1()
op_2_result = op_2()
op_3(op_1_result, op_2_result)
test_job = test_graph.to_job() test_job.execute_in_process()

*

*As shown in this example, what I would strongly suggest is to explicitly declare the types of the input and outputs of the ops. This helps in showing informative errors although the type-checking happens only during op execution.

*Each op in this dagster job/pipeline represents a single logical unit operation and ideally I would expect this operation to be a deterministic operation (some sort of data transformation logic) that would yield an output (or data) according to the type defined in the output definition.

*Therefore it is good practice to write ops that perform tasks yielding data of a particular type/schema, rather than having tasks return data that changes types on different runs.

*In this kind of setup, the only time that you'd probably end up re-running the whole dagster pipeline a couple of times due to mismatching types would be probably during the initial setup. Later after the pipeline is developed, it is usually re-run based on a schedule or a sensor in such a way that the code remains the same but the only data changes on each run, however still the ops (if they have deterministic operations) would yield results that conform with type/schema.


text:
Q: How to append data in delta table? Following is code which I've tried so far
import json
import csv

with open('/dbfs/mnt/costtransparency/HealthPlans/UHC/2022-11/2022-11-01_United-HealthCare-Services--Inc-_Third-Party-Administrator_Winstead_CSP-903-C746_in-network-rates.json.gz') as f:
    d=json.load(f)
employee_data = d['in_network']#d['provider_references']

# now we will open a file for writing
data_file = open('/dbfs/FileStore/data_file.csv', 'w')

# create the csv writer object
csv_writer = csv.writer(data_file)

# Counter variable used for writing
# headers to the CSV file
count = 0

for emp in employee_data:
    if count == 0:

        # Writing headers of CSV file
        header = emp.keys()
        csv_writer.writerow(header)
        count += 1

    # Writing data of CSV file
    csv_writer.writerow(emp.values())

data_file.close()

here is problem is currently I'm storing csv file into storage but I want to store it into delta table.
can anyone please help me to do this

A:
How to append data in delta table?

If you want to append the data into delta table use this following code:
First Read your Data frame:
df = spark.read.format("csv").option("header", "true").load("dbfs:/FileStore/vm_name3.csv")

Then , append data into delta table by using write method at particular table.
permanent_table_name = "demo123" #Table name
df.write.mode("append").format("delta").saveAsTable(permanent_table_name)

Or
If you want to save delta table in particular location use this code.
permanent_table_name = "dbfs:/user/hive/del"
df.write.mode("append").format("delta").save(permanent_table_name)


text:
Q: Import Google search results using ImportXML I want to use Google Sheets to grab Google search results's number.
My formula is:
=ImportXML(URL,"//div[@id='resultStats']")

=IMPORTXML("https://www.google.it/search?q=seo+prova";"//div[@id='resultStats']")

Google Sheets always returns #N/A, is there something wrong with the formula?
I think the problem is in the url, but I don't have solution.


text:
Q: Java JRE does not uninstall or reinstall I need to update to the latest version of Java, but it tells me that Java has already been installed. When I try to reinstall it, it says that Java is not installed.
Revo Uninstall, CCleaner and manual removal all fail.

A: Use JavaRA, to remove Java even if there are issues. It will even install the latest version automatically.


text:
Q: Code to ask confirmation before Delete pictures I code to delete all the images that are in the column "A1:A40". I would like to add code so that confirmation is asked before the photographs are deleted.
The idea is to prevent a mistake on the button from immediately deleting all the photographs in this column.
I have two codes that work. I want to combine one with the other?
I tried to insert the second code in the first one. When the text box appears, clicking on the "Yes" or "No" button, the code deletes all the photos.
The first code:
Sub DeletePic()
    Dim xPicRg As Range
    Dim xPic As Picture
    Dim xRg As Range
    Application.ScreenUpdating = False
    Set xRg = Range("A1:A40")
    For Each xPic In ActiveSheet.Pictures
        Set xPicRg = Range(xPic.TopLeftCell.Address & ":" & xPic.BottomRightCell.Address)
        If Not Intersect(xRg, xPicRg) Is Nothing Then xPic.Delete

    Next
    Application.ScreenUpdating = True

    Range("A2:A36").Select
    ActiveWindow.ScrollRow = 33
    ActiveWindow.ScrollRow = 32
    ActiveWindow.ScrollRow = 31
    ActiveWindow.ScrollRow = 30
    ActiveWindow.ScrollRow = 29
    ActiveWindow.ScrollRow = 28
    ActiveWindow.ScrollRow = 27
    ActiveWindow.ScrollRow = 26
    ActiveWindow.ScrollRow = 25
    ActiveWindow.ScrollRow = 24
    ActiveWindow.ScrollRow = 23
    ActiveWindow.ScrollRow = 22
    ActiveWindow.ScrollRow = 21
    ActiveWindow.ScrollRow = 20
    ActiveWindow.ScrollRow = 19
    ActiveWindow.ScrollRow = 18
    ActiveWindow.ScrollRow = 17
    ActiveWindow.ScrollRow = 16
    ActiveWindow.ScrollRow = 15
    ActiveWindow.ScrollRow = 14
    ActiveWindow.ScrollRow = 13
    ActiveWindow.ScrollRow = 12
    ActiveWindow.ScrollRow = 11
    ActiveWindow.ScrollRow = 10
    ActiveWindow.ScrollRow = 9
    ActiveWindow.ScrollRow = 8
    ActiveWindow.ScrollRow = 7
    ActiveWindow.ScrollRow = 6
    ActiveWindow.ScrollRow = 5
    ActiveWindow.ScrollRow = 4
    ActiveWindow.ScrollRow = 3
    ActiveWindow.ScrollRow = 2
    ActiveWindow.ScrollRow = 1
    Selection.ClearContents
End Sub

This final part of the code (ActiveWindows.ScrollRow = A2:A36) is a little bigger because I made it recording a macro for this part of the code.
The second code that I want to insert in the first:
Dim Msg, Style, Title, Response, MyString
Msg = "Deseja continuar ?"
Style = vbYesNo
Title = "Esta operação apagará todas as fotografias"

Response = MsgBox(Msg, Style, Title)
If Response = vbYes Then
    MyString = "Yes"
Else
    MyString = "No"
End If

A: If you want to ask the user to confirm that they want to run DeletePic you need to add your second block of code at the top of DeletePic (anywhere before the For Each loop)
Your second block of code currently doesn't really do anything with the result.
You can simplify it to something like the following:
Dim Result As VbMsgBoxResult
' ask if they want to continue
Result = MsgBox("Delete Pictures?", vbYesNo, "Confirm")
' if they do not, then exit out otherwise continue
If Result = vbNo Then Exit Sub


text:
Q: How can I add progressDialog or spinner to already finished app? I have to update some application. It is already in use, so I don't want to make big changes...
I want to add a progress dialog or a spinner every time when new activity is loaded. I read some articles and questions here like I have to use AsyncTask and so on. But I want to know if there is any easier way. Maybe something like creating some function which will showing spinner/progressDailog until new layout is loaded.
If you know what I want, can you tell me, if it is possible? Thanks
EDIT: I have one idea. Could I create layout with spinner, which would overlay the current layout? If yes, how?
EDIT two: AsyncTask
private ProgressDialog progressDialog;
    @Override
    protected void onPreExecute (){
        progressDialog = new ProgressDialog(mContext);
        progressDialog.setMessage("Loading...");
        progressDialog.setCancelable(false);
        progressDialog.setIndeterminate(true);
        progressDialog.show();
    }

   //  Some code here

@Override
    protected void onPostExecute(CustomAsyncTaskResult<User> result) {
        progressDialog.dismiss();
        ((LoginActivity)mContext).getResult(result);
    }

A: The simple answer is - no, there is no simple way.  If you want to display a spinner while an activity is loading, you need to create an asynctask (or any other separate thread).  The good news is that you can create one asynctask and reuse it in all of your activities.  The bad new is that you don't have any choice but to modify every one of your activities where you want to add the spinner.

A: The reason using AsyncTask is suggested is because ProgressBar would otherwise be displayed using the UI thread which you do not want to do as it would block other operations the UI thread would have to do. You need to delegate the ProgressBar display to a background thread. So no, you can't do this.


text:
Q: How many certificates are necessary for a secure Service Fabric cluster I'm trying to wrap my brain around how many certificates I'm going to need for service fabric. I've read quite a bit from the product team and that's been really helpful, now I'm trying to distill that down to what I actually need given the following goals:

*

*Create a secure cluster with AAD authentication (I'm good with the AAD part)

*Enable communication over HTTPS/SSL for self-hosted web api that will reside on the cluster

*Access service fabric explorer over HTTPS without certificate errors

In order to create a secure cluster I'll need a valid certificate which will require a custom domain name.
Create a Service Fabric cluster in Azure using Azure Resource Manager

*

*The certificate must contain a private key.

*The certificate must be created for key exchange, exportable to a
  Personal Information Exchange (.pfx) file.

*The certificate's subject name must match the domain used to access
  the Service Fabric cluster. This matchng is required to provide SSL
  for the cluster's HTTPS management endpoints and Service Fabric
  Explorer. You cannot obtain an SSL certificate from a certificate
  authority (CA) for the .cloudapp.azure.com domain. You must acquire a
  custom domain name for your cluster. When you request a certificate
  from a CA, the certificate's subject name must match the custom
  domain name used for your cluster.

Based on that, would it be correct to assume that I only need one cert and a custom domain to achieve the goals outlined above?
I'd like to follow any best practices on this, so if I'm in error, please provide feedback.

A: AAD takes care of your client-to-node security, so the only certificate you'll need would be a Server certificate for node-to-node security. This is what they seem to recommend here as well, so you should be on the right track.


text:
Q: Simple Circle Problem An elegant circle problem. It goes by many names. This is my version.

*

*Dog 1 is tied to a post by a leash 1 unit long.

*He shares half of his land with Dog 2 tied to a post 1 unit away from his own.

*How long is Dog 2's leash?

A: An idea with analytic geometry:
We can assume the first dog's land is the canonical unit circle $\;S:\;x^2+y^2=1\;$ , and then the second dog's post is at $\;(0,1)\;$ , say.
The question can then be rephrased as: what has to be the radius $\;R\;$ of the circle $\;T:\;x^2+(y-1)^2=R^2\;$ so that $\;Area(S)\cap Area(T)=\frac\pi2\;$ ?
Hint:
Using integration and symmetry, we have that
$$\frac\pi4=2\int\limits_0^{x_0}\left[\sqrt{1-x^2}-\left(1+\sqrt{R^2-x^2}\right)\right]dx$$
with $\;x_0\;$ the abscissa of the intersection point of both circles in the first quadrant.
Clearly, $\;0<R\le 2\;$ (why?)


text:
Q: Cannot unmount unconnected transport endpoint because of chdir failure I try to unmount an unconnected endpoint (created by mount.posixovl), but when I try to unmount the endpoint using fusermount -u I get a failed to chdir.
» fusermount -zu ./overlaydir
fusermount: failed to chdir to /home/nfs/hwalinga/mounts: Permission denied

I tried -u and -zu

A: All directories in the path leading up to the mount point need to be executable. I my case my home folder was not executable.
chmod +x /home/nfs/hwalinga

This solves it.


text:
Q: Can I create a document styled java classes from RPC style WSDL? I am trying to generate client from a hosted wsdl. wsdl is in rpc style format but i want classes that are generated to be in document style format. How to do the same ?

A: You can download the WSDL and modify it to document style before using it to generate code. But that may not be helpful as the server hosting the service might still expect RPC style request.


text:
Q: Find program's code address at runtime? When I use gdb to debug a program written in C, the command disassemble shows the codes and their addresses in the code memory segmentation. Is it possible to know those memory addresses at runtime? I am using Ubuntu OS. Thank you.
[edit] To be more specific, I will demonstrate it with following example.
#include <stdio.h>

int main(int argc,char *argv[]){
    myfunction();
    exit(0);
}

Now I would like to have the address of myfunction() in the code memory segmentation when I run my program.

A: If you know the function name before program runs, simply use
void * addr = myfunction;

If the function name is given at run-time, I once wrote a function to find out the symbol address dynamically using bfd library. Here is the x86_64 code, you can get the address via find_symbol("a.out", "myfunction") in the example.
#include <bfd.h>
#include <stdio.h>
#include <stdlib.h>
#include <type.h>
#include <string.h>

long find_symbol(char *filename, char *symname)
{
    bfd *ibfd;
    asymbol **symtab;
    long nsize, nsyms, i;
    symbol_info syminfo;
    char **matching;

    bfd_init();
    ibfd = bfd_openr(filename, NULL);

    if (ibfd == NULL) {
        printf("bfd_openr error\n");
    }

    if (!bfd_check_format_matches(ibfd, bfd_object, &matching)) {
        printf("format_matches\n");
    }

    nsize = bfd_get_symtab_upper_bound (ibfd);
    symtab = malloc(nsize);
    nsyms = bfd_canonicalize_symtab(ibfd, symtab);

    for (i = 0; i < nsyms; i++) {
        if (strcmp(symtab[i]->name, symname) == 0) {
            bfd_symbol_info(symtab[i], &syminfo);
            return (long) syminfo.value;
        }
    }

    bfd_close(ibfd);
    printf("cannot find symbol\n");
}

A: To get a backtrace, use execinfo.h as documented in the GNU libc manual.
For example:
#include <execinfo.h>
#include <stdio.h>
#include <unistd.h>

void trace_pom()
{
    const int sz = 15;
    void *buf[sz];

    // get at most sz entries
    int n = backtrace(buf, sz);

    // output them right to stderr
    backtrace_symbols_fd(buf, n, fileno(stderr));

    // but if you want to output the strings yourself
    // you may use char ** backtrace_symbols (void *const *buffer, int size)
    write(fileno(stderr), "\n", 1);
}

void TransferFunds(int n);

void DepositMoney(int n)
{
    if (n <= 0)
        trace_pom();
    else TransferFunds(n-1);
}

void TransferFunds(int n)
{
    DepositMoney(n);
}

int main()
{
    DepositMoney(3);

    return 0;
}

compiled

gcc a.c -o a -g -Wall -Werror -rdynamic

According to the mentioned website:

Currently, the function name and offset only be obtained on systems that use the ELF
  binary format for programs and libraries. On other systems, only the hexadecimal return
  address will be present. Also, you may need to pass additional flags to the linker to
  make the function names available to the program. (For example, on systems using GNU
  ld, you must pass (-rdynamic.)

Output

./a(trace_pom+0xc9)[0x80487fd]
./a(DepositMoney+0x11)[0x8048862]
./a(TransferFunds+0x11)[0x8048885]
./a(DepositMoney+0x21)[0x8048872]
./a(TransferFunds+0x11)[0x8048885]
./a(DepositMoney+0x21)[0x8048872]
./a(TransferFunds+0x11)[0x8048885]
./a(DepositMoney+0x21)[0x8048872]
./a(main+0x1d)[0x80488a4]
/lib/i686/cmov/libc.so.6(__libc_start_main+0xe5)[0xb7e16775]
./a[0x80486a1]

A: About a comment in an answer (getting the address of an instruction), you can use this very ugly trick
#include <setjmp.h>

void function() {
    printf("in function\n");
    printf("%d\n",__LINE__);
    printf("exiting function\n");

}

int main() {
    jmp_buf env;
    int i;

    printf("in main\n");
    printf("%d\n",__LINE__);
    printf("calling function\n");
    setjmp(env);
    for (i=0; i < 18; ++i) {
        printf("%p\n",env[i]);
    }
    function();
    printf("in main again\n");
    printf("%d\n",__LINE__);

}

It should be env[12] (the eip), but be careful as it looks machine dependent, so triple check my word. This is the output
in main
13
calling function
0xbfff037f
0x0
0x1f80
0x1dcb
0x4
0x8fe2f50c
0x0
0x0
0xbffff2a8
0xbffff240
0x1f
0x292
0x1e09
0x17
0x8fe0001f
0x1f
0x0
0x37
in function
4
exiting function
in main again
37

have fun!

A: Above answer is vastly overcomplicated.   If the function reference is static, as it is above, the address is simply the value of the symbol name in pointer context:
void* myfunction_address = myfunction;

If you are grabbing the function dynamically out of a shared library, then the value returned from dlsym() (POSIX) or GetProcAddress() (windows) is likewise the address of the function.
Note that the above code is likely to generate a warning with some compilers, as ISO C technically forbids assignment between code and data pointers (some architectures put them in physically distinct address spaces).
And some pedants will point out that the address returned isn't really guaranteed to be the memory address of the function, it's just a unique value that can be compared for equality with other function pointers and acts, when called, to transfer control to the function whose pointer it holds.  Obviously all known compilers implement this with a branch target address.
And finally, note that the "address" of a function is a little ambiguous.  If the function was loaded dynamically or is an extern reference to an exported symbol, what you really get is generally a pointer to some fixup code in the "PLT" (a Unix/ELF term, though the PE/COFF mechanism on windows is similar) that then jumps to the function.


text:
Q: LibGDX - TexturePacker2 doesn't generate/pack images I'm currently reading a book on LibGDX Game Development - Learning LigbGDX Game Development.
In the book, we use TexturePacker2 to generate a .png and .pack file to pack a half dozen textures into a texture atlas. I followed the code exactly, but it does not generate anything into the destination folder.
Here is the code in my desktop project folder:
package com.packtpub.libgdx.canyonbunny;

import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.badlogic.gdx.tools.imagepacker.TexturePacker2;
import com.badlogic.gdx.tools.imagepacker.TexturePacker2.Settings;

public class Main {
    private static boolean rebuildAtlas = true;
    private static boolean drawDebugOutline = false;

    public static void main (String[] args) {
        if (rebuildAtlas) {
            Settings settings = new Settings();
            settings.maxWidth = 1024;
            settings.maxHeight = 1024;
            settings.debug = drawDebugOutline;
            TexturePacker2.process(settings, "assets-raw/images", "../CanyonBunny-android/assets/images", "canyonbunny.pack");
            TexturePacker2.process(settings, "assets-raw/images-ui", "../CanyonBunny-android/assets/images", "canyonbunny-ui.pack");
            rebuildAtlas = false;
        }

        LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();
        cfg.title = "CanyonBunny";
        cfg.useGL20 = false;
        cfg.width = 800;
        cfg.height = 480;

        new LwjglApplication(new CanyonBunnyMain(), cfg);
    }
}

But when I run this, nothing is generated into my CanyonBunny-android/assets/images folder. The only way I can get my textures to load is to download the sources for the book and put the already generated .png and .pack folder in the correct folder. I followed the book exactly, so I'm not sure what the issue is. I get the logging message that it is generating a 1024x1024 texture atlas, so the code is being executed. Is there something I'm missing?
Here is what the console says when I start the application(with the already-generated files)
Packing.........
Writing 1024x1024: ../CanyonBunny-android/assets/images/canyonbunny.png
Packing......
Writing 1024x1024: ../CanyonBunny-android/assets/images/canyonbunny-ui.png
game.Assets: # of assets loaded: 2
game.Assets: asset: images/canyonbunny.pack
game.Assets: asset: images/canyonbunny.png

Without the already-generated files:
Packing.........
Writing 1024x1024: ../CanyonBunny-android/assets/images/canyonbunny.png
Packing......
Writing 1024x1024: ../CanyonBunny-android/assets/images/canyonbunny-ui.png
game.Assets: Couldn't load asset 'images/canyonbunny.pack'
com.badlogic.gdx.utils.GdxRuntimeException: File not found: images/canyonbunny.pack (Internal)
    at com.badlogic.gdx.files.FileHandle.read(FileHandle.java:127)
    at com.badlogic.gdx.graphics.g2d.TextureAtlas$TextureAtlasData.<init>(TextureAtlas.java:97)
    at com.badlogic.gdx.assets.loaders.TextureAtlasLoader.getDependencies(TextureAtlasLoader.java:59)
    at com.badlogic.gdx.assets.loaders.TextureAtlasLoader.getDependencies(TextureAtlasLoader.java:34)
    at com.badlogic.gdx.assets.AssetLoadingTask.handleSyncLoader(AssetLoadingTask.java:103)
    at com.badlogic.gdx.assets.AssetLoadingTask.update(AssetLoadingTask.java:92)
    at com.badlogic.gdx.assets.AssetManager.updateTask(AssetManager.java:399)
    at com.badlogic.gdx.assets.AssetManager.update(AssetManager.java:314)
    at com.badlogic.gdx.assets.AssetManager.finishLoading(AssetManager.java:337)
    at game.Assets.init(Assets.java:38)
    at com.packtpub.libgdx.canyonbunny.CanyonBunnyMain.create(CanyonBunnyMain.java:17)
    at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:125)
    at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:108)
game.Assets: # of assets loaded: 0
Exception in thread "LWJGL Application" com.badlogic.gdx.utils.GdxRuntimeException: java.lang.NullPointerException
    at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:111)
Caused by: java.lang.NullPointerException
    at com.badlogic.gdx.utils.ObjectMap.get(ObjectMap.java:278)
    at com.badlogic.gdx.assets.AssetManager.get(AssetManager.java:103)
    at game.Assets.init(Assets.java:45)
    at com.packtpub.libgdx.canyonbunny.CanyonBunnyMain.create(CanyonBunnyMain.java:17)
    at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:125)
    at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:108)

A: *

*Check if the files are actually created in the correct folder using file explorer (not eclipse).
If you can't find, try searching it and make it appear in the correct folder first.
The log suggests that the file is being generated, I suppose it should be.

*However, eclipse does not recognize the newly generated files. You have to hit refresh in the eclipse project folder before using them.
Check it it works first.

*Now you won't be able to pack them at each run. I had the same issue, so I created a different project (to be used as a tool) which would do packing (and automate many other little things). Whenever I changed assets, I'd run the tool once before testing.
Hope this helps.
Good luck.

A: Looks like you are using an old version of libgdx — right? TexturePacker2 isn't there anymore, there's just the TexturePacker now (and it works flawlessly, by the way). I'd recommend you updating first.

A: I had the same problem.  It worked with drawDebugOutline = true, but when I changed it to false it crashed.
It is an Eclipse thing...
The solution as hinted at above is to refresh the project.  Eclipse is not seeing the new packed texture file until you refresh.  Right click on the Android project and click "Refresh" which will cause Eclipse to find the new file.


text:
Q: Closures as solution to data merging idiom I'm trying to wrap my head around closures, and I think I've found a case where they might be helpful.
I have the following pieces to work with:

*

*A set of regular expressions designed to clean state names, housed in a function

*A data.frame with state names (of the standardized form that the function above creates) and state ID codes, to link the two (the "merge map")

The idea is, given some data.frame with sloppy state names (is the capital listed as "Washington, D.C.", "washington DC", "District of Columbia", etc.?), to have a single function return the same data.frame with the state name column removed and only the state ID codes remaining.  Then subsequent merges can happen consistently.
I can do this in any number of ways, but one way that seems to be particularly elegant would be to house the merge map and the regular expression and the code process everything inside a closure (following the idea that a closure is a function with data).
Question 1: Is this a reasonable idea?
Question 2: If so, how do I do it in R?
Here's a stupid simple clean state names function that works on the example data:
cleanStateNames <- function(x) {
  x <- tolower(x)
  x[grepl("columbia",x)] <- "DC"
  x
}

Here's some example data that the eventual function will be run on:
dat <- structure(list(state = c("Alabama", "Alaska", "Arizona", "Arkansas",
"California", "Colorado", "Connecticut", "Delaware", "District of Columbia",
"Florida"), pop08 = structure(c(29L, 44L, 40L, 18L, 25L, 30L,
22L, 48L, 36L, 13L), .Label = c("1,050,788", "1,288,198", "1,315,809",
"1,316,456", "1,523,816", "1,783,432", "1,814,468", "1,984,356",
"10,003,422", "11,485,910", "12,448,279", "12,901,563", "18,328,340",
"19,490,297", "2,600,167", "2,736,424", "2,802,134", "2,855,390",
"2,938,618", "24,326,974", "3,002,555", "3,501,252", "3,642,361",
"3,790,060", "36,756,666", "4,269,245", "4,410,796", "4,479,800",
"4,661,900", "4,939,456", "5,220,393", "5,627,967", "5,633,597",
"5,911,605", "532,668", "591,833", "6,214,888", "6,376,792",
"6,497,967", "6,500,180", "6,549,224", "621,270", "641,481",
"686,293", "7,769,089", "8,682,661", "804,194", "873,092", "9,222,414",
"9,685,744", "967,440"), class = "factor")), .Names = c("state",
"pop08"), row.names = c(NA, 10L), class = "data.frame")

And a sample merge map (the actual one links FIPS codes to states, so it can't be trivially generated):
merge_map <- data.frame(state=dat$state, id=seq(10) )

EDIT Building off of crippledlambda's answer below, here's an attempt at the function:
prepForMerge <- local({
  merge_map <- structure(list(state = c("alabama", "alaska", "arizona", "arkansas",  "california", "colorado", "connecticut", "delaware", "DC", "florida" ), id = 1:10), .Names = c("state", "id"), row.names = c(NA, -10L ), class = "data.frame")
  list(
    replace_merge_map=function(new_merge_map) {
      merge_map <<- new_merge_map
    },
    show_merge_map=function() {
      merge_map
    },
    return_prepped_data.frame=function(dat) {
      dat$state <- cleanStateNames(dat$state)
      dat <- merge(dat,merge_map)
      dat <- subset(dat,select=c(-state))
      dat
    }
  )
})

> prepForMerge$return_prepped_data.frame(dat)
        pop08 id
1   4,661,900  1
2     686,293  2
3   6,500,180  3
4   2,855,390  4
5  36,756,666  5
6   4,939,456  6
7   3,501,252  7
8     591,833  9
9     873,092  8
10 18,328,340 10

Two problems remain before I'd consider this question solved:

*

*Calling prepForMerge$return_prepped_data.frame(dat) is painful each time.  Any way to have a default function such that I could just call prepForMerge(dat)?  I'm guessing not given how it's implemented, but perhaps there's at least a convention for the default fxn....

*How do I avoid mixing the data and code in the merge_map definition?  Ideally I'd clean merge_map elsewhere, then just grab it inside the closure and store that.

A: I may be missing the point of your question, but this is one way in which you can use a closure:
> replaceStateNames <- local({
+   statenames <- c("Alabama", "Alaska", "Arizona", "Arkansas",
+                   "California", "Colorado", "Connecticut", "Delaware",
+                   "District of Columbia", "Florida")
+   function(patt,newtext) {
+     statenames <- tolower(statenames)
+     statenames[grepl(patt,statenames)] <- newtext
+     statenames
+   }
+ })
>
> replaceStateNames("columbia","DC")
 [1] "alabama"     "alaska"      "arizona"     "arkansas"    "california"
 [6] "colorado"    "connecticut" "delaware"    "DC"          "florida"
> replaceStateNames("alaska","palincountry")
 [1] "alabama"              "palincountry"         "arizona"
 [4] "arkansas"             "california"           "colorado"
 [7] "connecticut"          "delaware"             "district of columbia"
[10] "florida"
> replaceStateNames("florida","jebbushland")
 [1] "alabama"              "alaska"               "arizona"
 [4] "arkansas"             "california"           "colorado"
 [7] "connecticut"          "delaware"             "district of columbia"
[10] "jebbushland"
>

But to generalize, you can replace statenames with your data frame definition, and return a function (or list of functions) which uses this data frame without having to pass it as an argument to the function call. Example (but note I've used the ignore.case=TRUE argument in grepl):
> replaceStateNames <- local({
+   statenames <- c("Alabama", "Alaska", "Arizona", "Arkansas",
+                   "California", "Colorado", "Connecticut", "Delaware",
+                   "District of Columbia", "Florida")
+   list(justreturn=function(patt,newtext) {
+     statenames[grepl(patt,statenames,ignore.case=TRUE)] <- newtext
+     statenames
+   },reassign=function(patt,newtext) {
+     statenames <<- replace(statenames,grepl(patt,statenames,ignore.case=TRUE),newtext)
+     statenames
+   })
+ })

Just like the first example:
> replaceStateNames$justreturn("columbia","DC")
 [1] "Alabama"     "Alaska"      "Arizona"     "Arkansas"    "California"
 [6] "Colorado"    "Connecticut" "Delaware"    "DC"          "Florida"

Just returns the lexically-scoped value of statenames to check that the original values are unchanged:
> replaceStateNames$justreturn("shouldnotmatch","anythinghere")
 [1] "Alabama"              "Alaska"               "Arizona"
 [4] "Arkansas"             "California"           "Colorado"
 [7] "Connecticut"          "Delaware"             "District of Columbia"
[10] "Florida"

Do the same thing, but make the change "permanent":
> replaceStateNames$reassign("columbia","DC")
 [1] "Alabama"     "Alaska"      "Arizona"     "Arkansas"    "California"
 [6] "Colorado"    "Connecticut" "Delaware"    "DC"          "Florida"

And note that the value of statenames attached to these functions has changed.
> replaceStateNames$justreturn("shouldnotmatch","anythinghere")
 [1] "Alabama"     "Alaska"      "Arizona"     "Arkansas"    "California"
 [6] "Colorado"    "Connecticut" "Delaware"    "DC"          "Florida"

In any case, you can replace statenames with a data frame, and these simple functions with a "merge map" or any other mapping you desire.
Edit
Speaking of "merge", is this what you're looking for? An implementation of first ?merge example using a closure:
> authors <- data.frame(surname = I(c("Tukey", "Venables", "Tierney", "Ripley", "McNeil")),
+                       nationality = c("US", "Australia", "US", "UK", "Australia"),
+                       deceased = c("yes", rep("no", 4)))
> books <- data.frame(name = I(c("Tukey", "Venables", "Tierney",
+                       "Ripley", "Ripley", "McNeil", "R Core")),
+                     title = c("Exploratory Data Analysis",
+                       "Modern Applied Statistics ...",
+                       "LISP-STAT",
+                       "Spatial Statistics", "Stochastic Simulation",
+                       "Interactive Data Analysis",
+                       "An Introduction to R"),
+                     other.author = c(NA, "Ripley", NA, NA, NA, NA,
+                       "Venables & Smith"))
>
> mergewithauthors <- with(list(authors=authors),function(books)
+   merge(authors, books, by.x = "surname", by.y = "name"))
>
> mergewithauthors(books)
   surname nationality deceased                         title other.author
1   McNeil   Australia       no     Interactive Data Analysis         <NA>
2   Ripley          UK       no            Spatial Statistics         <NA>
3   Ripley          UK       no         Stochastic Simulation         <NA>
4  Tierney          US       no                     LISP-STAT         <NA>
5    Tukey          US      yes     Exploratory Data Analysis         <NA>
6 Venables   Australia       no Modern Applied Statistics ...       Ripley

Edit 2
To read file into an object which will be lexically bound, you can either do
fn <- local({
  data <- read.csv("filename.csv")
  function(...) {
    ...
  }
})

or
fn <- with(list(data=read.csv("filename.csv")),
     function(...) {
       ...
     }
   })

or
fn <- with(local(data <- read.csv("filename.csv")),
     function(...) {
       ...
     }
   })

and so on. (I assume the function(...) will have to do with your "merge_map"). You can also use evalq in place of local. To "bring in" objects residing in the global space (or enclosing environment), you can just do the following
globalobj <- value      ## could be from read.csv()
fn <- local({
  localobj <- globalobj ## if globalobj is not locally defined,
                        ## R will look in enclosing environment
                        ## in this case, the globalenv()
  function(...) {
    ...
  }
})

then modifying globalobj later will not change localobj attached to the function (since almost(?) everything in R follows pass-by-value semantics). You can also use with instead of local as shown in examples above.


text:
Q: unable to curl on ip address however localhost is working fine If i do curl on localhost then its working fine.However if i replace with system ip address its giving error.
I have entry for ip address in etc/hosts
curl -v https://<ip address>:9200
* About to connect() to <ip address> port 9200 (#0)
*   Trying <ip address>... Connection refused
* couldn't connect to host
* Closing connection #0
curl: (7) couldn't connect to host

my /etc/host/
127.0.0.1 localhost
<ip address> Load-testing-1-4

A: The "Connection refused" should mean there is nothing listening to port 9200 on the address. I think the OP is asserting that <ip address> is an address for the local machine, and that curl -v https:localhost:9200 works but that curl -v https://Load-testing-1-4:9200 (maybe replacing Load-testing-1-4 with the ip address from /etc/hosts) doesn't.
If that is the case then you need to look at the thing that curl is trying to connect to, and make sure it is listening on all the addresses associated with the machine, or at least the one for Load-testing-1-4. Using 0.0.0.0 as the address will usually do this for IPv4 rather than an explicit address such as 127.0.0.1.
If I have misunderstood and Load-testing-1-4 is a different machine, then you need to look on that machine for the program that curl is trying to connect to.
An added complication is the https, I would suggest using http first to get things going before beefing up the security.


text:
Q: Need to iterate over queryset of student answers and provide individual "feedback" form field for each one I am building a homework database application that will make answering, grading and correcting homework simpler than it is now.
To do this I have forms for students to fill in an answer to a question that has been assigned to them, the question is then marked as ready to be graded and the teacher's view can then see all the questions that are ready to be graded per assignment.
The trouble that I am having is inserting a form field into each answer where feedback could be given; I suppose the simplest way would be to load one question and its answer per page and have a feedback form field there, but what I would like to do is to iterate over all the questions that have been answered on a given assignment and display them all on one page so that they can be graded quickly.
I have tried to insert just a form field into the for loop, and had some success, but when I submit I can't pull the question id out of the loop to populate the (required) foreign key pointing from the feedback model to the original question-answer.
I've toyed with multiple forms on a page, I've tried to create a forum type answer and response, I've tried to grab the original answer id from inside the for loop and send it back to the form, but I'm starting to wonder if I'm just not seeing some simple thing that is happening behind the scenes to stop it from working.
@login_required
@teacher_required
def list_ungraded_assignment_questions_by_scheduled_assignment(request, scheduled_assignment):
        need_to_be_evaluated_student_assignment_questions = StudentAssignmentQuestion.objects.filter(student_scheduled_class_assignment=scheduled_assignment).filter(needs_to_be_reviewed_by_teacher=True)
        need_to_be_evaluated_student_assignment_question_ids = []
        for assignment_question in need_to_be_evaluated_student_assignment_questions:
            need_to_be_evaluated_student_assignment_question_ids.append(assignment_question.id)

        student_assignment_question_answers = StudentAssignmentQuestionAnswer.objects.filter(student_assignment_question__in=need_to_be_evaluated_student_assignment_question_ids)

        context = {"need_to_be_evaluated_student_assignment_questions": need_to_be_evaluated_student_assignment_questions, "student_assignment_question_answers": student_assignment_question_answers}
        return render(request, "accelegraded/list_ungraded_assignment_questions_by_scheduled_assignment.html", context)

{% for student_assignment_question_answer in student_assignment_question_answers %}
                {% if student_assignment_question_answer.student_assignment_question.id == need_to_be_evaluated_student_assignment_question.id %}

ANSWER: {{ student_assignment_question_answer }}

Answered On: {{ student_assignment_question_answer.date_created }}

                    {% for student_assignment_question_answer_evaluation in student_assignment_question_answer_evaluations %}
                        {% if student_assignment_question_answer_evaluation.student_assignment_question_answer.id == student_assignment_question_answer.id %}

RESPONSE: {{ student_assignment_question_answer_evaluation }}

BY: {{ student_assignment_question_answer_evaluation.answer_evaluation_by }}

AT: {{ student_assignment_question_answer_evaluation.answer_evaluation_by }}

                        {% endif %}
                    {% endfor %}

                Correct
                Partial
                Incorrect

                    <form method="POST">
                        {% csrf_token %}
                        <fieldset class="form-group">
                            <legend class="border-bottom mb-4">Teacher Response</legend>
                            {{ form|crispy }}
                        </fieldset>

                            <button class="btn btn-outline-info" type="submit">Submit</button>

                    </form>

                {% endif %}
            {% endfor %}

The error that I get when I try to save input in the form is that a default value of the question-answer is not being returned and I have no idea how to return it back to the form to populate the model.

A: You should take advantage of the relationship between your models.
questions = StudentAssignmentQuestion.objects.filter(
    student_scheduled_class_assignment=scheduled_assignment,
    needs_to_be_reviewed_by_teacher=True,
).prefetch_related(
    'studentassignmentquestionanswer_set', # Or StudentAssignmentQuestionAnswer.question.related_name
)

Then you can iterate over the list as such:
for question in questions:
    for answer in question.studentassignmentquestionanswer_set.all():
        print(answer)

Side note, I think your member names are a bit too verbose. For example needs_to_be_reviewed_by_teacher could be needs_review or if you need to distinguish that it's only relevant for a teacher and not an admin, then needs_teacher_review.


text:
Q: Creating Accordians in Wordpress Theme I am creating a wordpress theme in which there is a section "HUMOUR". In this section i've created accordians, in which the 1st accordian is in class="active" and rest don't.
for e.g

                                What are Benifits ?

lorem ipsumdolor sitamet consectetur adipisicing elitseddo eiusmod tempor incididunt lorem ipsum dolor sitamet consectetur adipisicing elit seddo eiusmod

                                CAN I OPT OUT ?

lorem ipsumdolor sitamet consectetur adipisicing elitseddo eiusmod tempor incididunt lorem ipsum dolor sitamet consectetur adipisicing elit seddo eiusmod

                                IS MY CAPITAL SAFE ?

lorem ipsumdolor sitamet consectetur adipisicing elitseddo eiusmod tempor incididunt lorem ipsum dolor sitamet consectetur adipisicing elit seddo eiusmod

                                WHAT IS THE RISK ?

lorem ipsumdolor sitamet consectetur adipisicing elitseddo eiusmod tempor incididunt lorem ipsum dolor sitamet consectetur adipisicing elit seddo eiusmod

This is required Accordian

While creating same in wordpress its not displaying 1st post in class="active". Also, its not working as expected.
i.e

WHAT IS THE RISK ?

                        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam facilisis nisi in ligula semper rutrum. Aliquam placerat sapien dolor, non tristique massa ultrices sit amet.

IS MY CAPITAL SAFE ?

                        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam facilisis nisi in ligula semper rutrum. Aliquam placerat sapien dolor, non tristique massa ultrices sit amet.

CAN I OPT OUT ?

                        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam facilisis nisi in ligula semper rutrum. Aliquam placerat sapien dolor, non tristique massa ultrices sit amet.

This is my preview

I've used custom post type to display accordians in which there is title and an excerpt. This is my code.

 HUMOUR ON INDIAN INVESTMENT

                <?php
                $args = array(
                    'post_type' => 'humour'
                    );
                $humour_query = new WP_Query($args);
                if ($humour_query->have_posts()) : while($humour_query->have_posts()) : $humour_query->the_post();
                ?>
                <dt id="post-<?php the_ID(); ?>">

<?php the_title(); ?>

                        <img src="<?php print IMAGES; ?>/arrowdown.png" class="arrow" id="down"/>
                        <img src="<?php print IMAGES; ?>/arrowup.png" class="arrow" id="up"/>

                        <?php
                            $excerpt = get_the_excerpt();
                            echo string_limit_words($excerpt,25);
                        ?>

                <?php endwhile; endif; ?>

I want when user publish any post then it will check if its 1st post or not and if it is 1st post i.e current latest post then it will add class="active" to it and will leave rest posts as it is. I don't know exactly what should i do to achieve this task. Anybody please help..

A: As per you described, What I have got is you want to add class active to last published post by the user.
By seeing your output and HTML, It seems that active class is missing.
So to achieve that, we will add one dummy condition that will print class="active". I would also suggest that modify your $arg and make in DESC order to get last published post first.
Your final code will be something like this :

 HUMOUR ON INDIAN INVESTMENT

            <?php
                $args = array(
                        'post_type' => 'humour',
                        'order'     => 'DESC' //Add order to get post in DESC order
                        );
                $humour_query = new WP_Query($args);
                $i=0; //Take variable and assign it 0
                if ($humour_query->have_posts()) : while($humour_query->have_posts()) : $humour_query->the_post();
            ?>
            <?php
                if($i==0): //This condition will be true only once as I have added increament at the end
                    echo "
";
                else:
            ?>
            <dt id="post-<?php the_ID(); ?>">
            endif;

<?php the_title(); ?>

                    <img src="<?php print IMAGES; ?>/arrowdown.png" class="arrow" id="down"/>
                    <img src="<?php print IMAGES; ?>/arrowup.png" class="arrow" id="up"/>

                    <?php
                        $excerpt = get_the_excerpt();
                        echo string_limit_words($excerpt,25);
                    ?>

            <?php
            $i++; //Incremented that variable so class wont be added from second post
            endwhile;
            endif; ?>

NOTE: I have assumed that accordion is working with class active.


text:
Q: Argument 2 of FormData.append is not an object in mozila firefox sending the file to back end with help of formData.append()(appending the document details).It is working fine in google chrome.but i having facing issue in mozila and safari with this error.

Service Code:
  manageSingleDataWithChildModel(url: string, data: any, childData: any, docRefArea: string = ''): Observable<any> {
        this._spinnerService.show();
        this.refreshSession();
        var formData: FormData = new FormData();
        formData.append('docReferenceArea', docRefArea);
        childData.forEach((data: any) => {
            if (data.DocumentDetails != null && data.DocumentDetails.DocContent != null && data.DocumentDetails.DocContent != "") {
                data.FileIdentifier = data.DocumentDetails.FileIdentifier;
                formData.append('files', data.DocumentDetails.DocContent, data.DocumentDetails.FileIdentifier);
                data.DocumentDetails.DocContent = null;
            }
        });
        formData.append('dataModel', JSON.stringify(data));

        let headers = new Headers(
            {
                'enctype': 'multipart/form-data',
                'method': 'POST',
                'Authorization': 'Bearer ' + localStorage.getItem('BearerToken'),
            });
        let options = new RequestOptions({ headers: headers });
        return this._http.post(url, formData, options)
            .map((res: Response) => { this._spinnerService.hide(); return HttpHelper.json(res) })
            .catch(error => this.handleError(error));
    }

A: docRefArea you are specifying it as string . But it is actually an object containing file details.
Try it by changing first line of your code to
manageSingleDataWithChildModel(url: string, data: any, childData: any, docRefArea: any = ''): Observable<any> {


text:
Q: Shared memory segment shared between a 32 and 64 bit processes Is it possible to create a shared memory segment that can be accessed by both 32 and 64 bit processes. The flag'TPF_IPC64' to support 64 bit addressing is as below
shmget(key,100,IPC_CREAT|TPF_IPC64);

Will this be accessible from a 32 bit Linux process?
Edit: It seems like the flag 'TPF_IPC64' is not supported in a normal Linux OS call to shmget. I think it is some proprietary to IBM ( my bad). I took it from this link
http://pic.dhe.ibm.com/infocenter/tpfhelp/current/index.jsp?topic=%2Fcom.ibm.ztpf-ztpfdf.doc_put.cur%2Fgtpc2%2Fcpp_shmget.html

A: man shmget(2)

If IPC_CREAT is set in shmflg the shared memory segment created can
  only be shared by processes of the same executable type. That is, an
  application compiled as a 32-bit process will be able to share the
  same memory segment with other 32-bit processes, and an application
  compiled as a 64-bit process will be able to share the same memory
  segment with other 64-bit processes. If a 64-bit bit process want to
  create a shared memory segment which can also be shared with 32-bit
  processes, the 64-bit process must specify IPC_SHARE32 in addition to
  IPC_CREAT in shmflg . The 32-bit process does not need to specify
  IPC_SHARE32 .On Itanium(R)-based platforms, if the Adaptive Address
  Space feature is being used, then additional rules may apply. See the
  section below on Adaptive Address Space.

A: From IBM's document
TPF_IPC64
    Specifies that 64-bit addressing is supported. If you specify this flag, 64-bit system heap is used to satisfy the request if there is enough heap available. If there is no 64-bit system heap space available, 31-bit system heap will be used. Specify this flag only if all the users of this shared memory area can support 64-bit addresses.
The last sentence has mentioned that all the process has to support 64-bit address. So process with 32-bit address cannot access it.
However, I don't what is the behavior if you tried to access it with 32-bit process.


text:
Q: Why can't a program be multiplatform when it only needs to be compiled on each platform it is to run on? You may find the answer a bit obvious, and part of it is to me too.
But I'm wondering what parts of the code of a project usually need to be specifically designed for a specific platform, whether it was written in a high or a low level programming language?
If the question sounds a bit vague, please feel free to edit it.

A: Example could be the OS kernel methods, such as reading from files/network/memory. For example Windows provides different functionality/privileges than Linux when it comes to I/O and memory access.
Also, the machine/assembly code to which the code translates to depends on the underlying processor. So a C code must be recompiled sometimes to run on a newer version on Intel processor such as MEC.
Another reason could be a commercial version. Windows could make a C# code run on a MAC, by creating a .NET framework and a visual studio for MAC, but they chose not to do so, so that you are forced to write C# on Windows.

A: The question is general, so I will answer rather generally.
1) Like the previous post mentioned, anything that hooks into the essence of the OS needs to be code that works for that OS.
2) The lowest level code would be machine language / or assembly. This kind of code is not very crossplatform as it is code which will only run correctly on the machine that it was written for. That is an advantage of C, which is considered a low level language. Of course if you write C code for specific hardware, such as for instance a seven segment LED panel, that code will only work on another system if there is a corresponding seven segment LED panel in the target system.
One of the beauties of higher level programming languages is that you can generally write cross platform code which really only needs to be recompiled for the target system to run.
Then we could talk about interpreted languages such as Python, Ruby, or virtual machines like Java, Smalltalk, etc. If the target platform has an interpreter, such as "Python", as long as the source code is valide, it should run unaltered on a similar Python interpreter (I mean similar because you may have  version issue, or you may have graphical addon libraries, or other libraries).
As I type away, I realize that to do this question justice, one could write and write. Hmmm, maybe this question is TOO GENERAL???
CHEERS (of course I've left a lot of the story out)


text:
Q: Toggle the selection on and off using only keyboard shortcuts in Excel 2013 I want to remove duplicates in excel using keyboard only. After pressing Alt+A+M, how does one select/deselect the required columns with keyboard. There must be some way to do this using keyboard only, so how to toggle the selection on/off?
(In the image below, I used the mouse to select column B. how could it have been done using the keyboard)

A: This sequence works for me in Excel 2010 (I'd expect it to work in 2013 as well):

*

*Press ALT+a

*Press ALT+m

*Press Tab 4 times

*Press Down to reach the desired column

*Press Space to toggle columns on/off as required

*Press Enter to confirm selection


text:
Q: Адаптирование сайта У меня сайт www.bakunights.ml я хочу адаптировать этот сайт под устройствам смартфоны т.д как это сделать чтоб когда вошли с смартфона по-другому сайт отображалась для устройства думаю поняли помогите?

A: Тут есть море вариантов...

*

*
        Сделать адаптивный шаблон

*

*FlexBox

*FlexBox + Smartgrid (рекомендую)

*Bootstrap

*Сделать определение устройства на сервере (mobile detect в помощь) и для каждого устройства отдавать свой шаблон (очень рекомендую для больших проектов)

Вы также можете найти еще варианты, которые будут Вам по душе)))

A: 1) В head добавьте <meta name="viewport" content="width=device-width, initial-scale=1">
2)Добавьте медиазапросы


text:
Q: Simulink save final state leads to compile error I have a simpe simulink model

It compiles fine unless I try to save output states:

Then I face with this error when I try to compile it:

Saving the complete set of the SimState is only supported for the model running in Normal or Accelerator mode, and for Model blocks running in Normal mode.

Why does it happen and how to get around that?
Update:
My model is set to fixed step and it is set to normal mode:

A: As mentioned in the comments, "building" the model is only for the purpose of generating code/executables, and saving final states is not supported for code generation. If you just want to run the model, just press the "Run" button, not the "Build" button and it should work. See the Simulink documentation for more details on how to run a model.


text:
Q: jquery not working while implemented in html header of Wordpress I'm trying to use jquery in my pages on a wordpress install, and nothing seems to work.
it is called via php line (if i got it right) :
wp_enqueue_script('jquery');
I am assuming some jquery scripts are working (the ones coming together with the theme i'm using) but for some reason no single other script that i'd like to add will function.
I tried implementing it/them in the header of my index page, or in a js file, but none of these methods seem to work.
here is the link : http://selectedworx.com
thank you for any hint on how to get it working... it's driving me nuts :/

A: Try to add <?php wp_head();?> inside your header and inside your footer <?php wp_footer();?> Also add no-conflict mode for your Jquery:
jQuery(document).ready(function($){

    alert('This is a alert!!');
    //So now you can call your functions with $ !
            $('.someclass').hide();//for example
    });

A: DEMO: http://jsfiddle.net/7uAUg/
Your code seems to be working fine, the $ operator is likely being assigned to a different meaning.  This is likely happening in one of the 40+ includes that happen in your page.
Uncaught TypeError: Property '$' of object [object Object] is not a function

is the only exception you are experiencing so instead of
<script type="text/javascript">
$(document).ready(function(){
     $("div").css("border", "3px solid red");
});
</script>

use
<script type="text/javascript">
$(document).ready(function(){
     jQuery("div").css("border", "3px solid red");
});
</script>

as stated by @wirey


text:
Q: Maven Project to build additional jar compiled by different java version My main project is using java 1.6 and I need to provide an client jar to an system that can only run on java 1.5.  The client jar is an separate module so I am able to specify the java version in the maven-compiler-plugin.  However, the client jar is dependent on an core jar, which is on 1.6.  One way to
I have used "test-jar" goal in maven-jar-plugin to generate an test jar for other module to use.  I am hoping to do something similar and use it in my client module with the following dependency:
<dependency>
    <groupId>org.mygroup</groupId>
    <artifactId>module-core</artifactId>
    <classifier>java1_5</classifier>
</dependency>

A: Why do your client projects depends on core?
If it uses the code from the core, you apparently need to compile core JAR for 1.5 as well. You have several options here:

*

*Set the the target globally to 1.5 and make sure you are not using 1.6 JDK stuff in your code (at least, in the part of the code invoked by the client on JDK 1.5).

*Use the profiles + classifiers to generate artifacts for different JDKs (see this question). You have to run the built multiple times, though. Actually, each build will compile everything using the same -target version, so this approach is only a little improvement of 1), allowing you to publish your artifact for multiple JDK versions.

If client code actually does not use core (for example, it uses only WSDLs from the core or some other non-Java stuff), you can remove this dependency by moving stuff to separate "shared" module.


text:
Q: Django + postgresql: log how long a query took to execute? Beginner question, and it's probably a duplicate, sorry! But I can't find the answer by Googling or by searching on here.
My Django/postgres application is slow. I know how to log the queries being executed on postgres, so I'm doing that.
Now, how do I identify which of them are slow... short of typing them all in myself, and using a stopwatch?
In short: is there a way to log how long each query took to execute, using Django ORM & a postgres database?

A: You need django-debug-toolbar. Thanks me later.
Or if you want to do it manually then:
import time

start = time.time()
# execute your query here
stop = time.time() - start
print stop # or log this time

A: log all slow queries
set log_min_duration_statement = 200ms in postgresql.conf file
http://www.postgresql.org/docs/9.2/static/runtime-config-logging.html

A: I have used pgFouine to analyse my postgres logs - see http://pgfouine.projects.pgfoundry.org/tutorial.html for how to set up logging and how to analyse them with pgFouine.


text:
Q: Rails nested form In rails how would i build a nested form, similar to the type of form that can be built with the nested_form gem. But instead of nesting a model, i need to nest an attribute of the model which is stored as an array within the model. (it is a text array which is serialized into an array

A: If I understand your question correctly, I think what you want is to define a virtual attribute on the model. Then you can treat it like any other attribute.
http://railscasts.com/episodes/16-virtual-attributes
http://railscasts.com/episodes/167-more-on-virtual-attributes
also, this post has some good examples:
Rails: Virtual attributes and form values


text:
Q: Draw a cloned element vertically I'm trying to draw a shape multiple times using java script, in my case i am drawing a circle. I made a function that duplicate my element based on my selector, but when it draw the shape again to the screen, It draws it horizontally, I want to make it draw vertically.
I think the problem is the function is appending the element in the same place every time so that's why it draw it horizontally (correct me if i'm wrong)
This is my code :

function duplicateCircle() {
    //let num =1
    let clone = document.querySelector('.circle').cloneNode( true );
    //clone.setAttribute( 'id', `cmt${++num}`)
    document.querySelector('#grph').appendChild( clone );
}
.container{
    display: grid;
    width: 100%;
    height: 45vw;
    margin: auto;
    gap: 25px;
    border: 2px solid red;

    grid-template-columns: repeat(2);
    grid-template-rows: repeat(6,1fr);

    grid-template-areas:
    "cmd cmd  grph grph grph grph "
    "cmd cmd  grph grph grph grph "
    "cmd cmd  grph grph grph grph "
    "cmd cmd  grph grph grph grph "
    "cmd cmd  grph grph grph grph "
    "write write grph grph grph grph";

}

.box{
    display: flex;
    /*flex-direction: row;*/
    justify-content: center;
    border: 5px solid black;
}

.circle {
    height: 50px;
    width: 50px;
    background-color: blueviolet;
    border-radius: 50%;
    border: 3px solid black;
  }

  #command {grid-area: cmd;}
  #grph{grid-area: grph;}
  #write{grid-area: write;}
<!DOCTYPE html>

    <link rel="stylesheet" href="/style/style.css">

            <button id="draw" onclick="duplicateCircle()">Draw</button>

A: Use display:flex; with flex-direction:column.Apply this css:
#grph {
grid-area: grph;
display: flex;
flex-direction: column;
align-items:center;
justify-content: flex-start;
}

A: Try changing this
.box {
  display-direction: column;
  align-items: center;
}


text:
Q: Synchronize two multiselect box, select by value I am new to JS and Jquery and I am using Eric Hynds jquery-ui-multiselect-widget
Here's a very good demo:
http://jsfiddle.net/PKypd/11/
In this demo the second select box has its values checked by position depending on which option was selected on the first select box.
The example also says that:
"you can easily swap out .eq() for another .filter() to choose checkboxes by value instead of their position."
But I haven't been able to do so and can not find any documentation on how to do it.
Could you guys help me do this? Just can't figure out how to do the .filter() condition to select the options on the second select box by its value. Thanks in advance.
EDIT:
Here's what I've done so far:
http://jsfiddle.net/PKypd/54/
In that example I set the same values for both select boxes. When I click on Canada I'm expecting to select bar on the second box, which has the same value, but it selects all the options. I feel that I'm missing something really simple but can't figure it out.

A: In your filter, this is your test:
return (ui.value == 'can');

ui refers to the checkbox in the first list that you had clicked.  When you click the Canada checkbox, ui.value == 'can' will always be true.
This is what you want for your filter instead:
return this.value == ui.value;

This means to compare the current value of the item being inspected in the filter (this) with the value of the item that was clicked (ui).


text:
Q: Cannot npm install for angular-phonecat tutorial : Cannot find module 'update-notifier' I am having issues running npm install in the angular-phonecat directory. I am assuming this may be an issue with my paths but not sure. Any insight would be much appreciated. I keep getting Error: Cannot find module 'update-notifier'. If i install this individually i will just get another missing module.
$ which node
/usr/local/bin/node

$ which npm
/Users/Ashton/.node/bin/npm

export PATH="/usr/local/bin/node:$PATH"
export PATH="$HOME/.node/bin:$PATH"

$ npm install

> angular-phonecat@0.0.0 postinstall /Users/Ashton/Dropbox/Learning Projects/angular-phonecat
> bower install

module.js:340
    throw err;
          ^
Error: Cannot find module 'update-notifier'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object. (/Users/Ashton/Dropbox/Learning Projects/angular-phonecat/node_modules/.bin/bower:8:22)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)

npm ERR! angular-phonecat@0.0.0 postinstall: `bower install`
npm ERR! Exit status 8
npm ERR!
npm ERR! Failed at the angular-phonecat@0.0.0 postinstall script.
npm ERR! This is most likely a problem with the angular-phonecat package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     bower install
npm ERR! You can get their info via:
npm ERR!     npm owner ls angular-phonecat
npm ERR! There is likely additional logging output above.
npm ERR! System Darwin 13.1.0
npm ERR! command "node" "/Users/Ashton/.node/bin/npm" "install"
npm ERR! cwd /Users/Ashton/Dropbox/Learning Projects/angular-phonecat
npm ERR! node -v v0.10.26
npm ERR! npm -v 1.4.7
npm ERR! code ELIFECYCLE
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     /Users/Ashton/Dropbox/Learning Projects/angular-phonecat/npm-debug.log
npm ERR! not ok code 0

A: I was having a similar issue when I was trying to download angular-seed project on windows 10. I installed GIT command line. Then Instead of downloading the ZIP, I used GIT command line to download the project. git clone https://YOURPORJECT.For the network issue I typed in git config --global url."https://".insteadOf git://.


text:
Q: SQL Server : getting an 'Invalid Column Name' Error Message I am trying to run a query to pull the total amount of qualifying events grouped by event type and month. For example I need to know that there were 25 "LOSS_OF_COVERAGE_NON_PAYMENT" qualifying events in January, and 10 "LEAVE_OF_ABSENCE" qualifying events in January. I have tried various SQL select queries. I am not sure why the query below is returning an error that states

Invalid column name 'EventMonth'

My query:
SELECT
    a.GroupID, c.employername,
    MONTH(b.QualifyingEventDate) AS EventMonth,
    b.QualifyingEventType
FROM
    MST_MEMBER_DEMOGRAPHICS AS a
JOIN
    DET_ENROLLMENT_DETAILS AS b ON a.BFUNIQUEID = b.BFUNIQUEID
JOIN
    MST_EMPLOYER_GROUP_MASTER AS c ON a.groupid = c.groupid
WHERE
    a.groupid = 'TESTClient'
    AND QualifyingEventType <> 'NULL'
    AND QualifyingEventDate BETWEEN '01/01/2019' AND '08/13/2019'
GROUP BY
    b.QualifyingEventType, EventMonth
ORDER BY
    EventMonth, a.groupid, b.QualifyingEventType


text:
Q: Find text between two characters and for each, do something I have a file full with text in the following format:
(ignoring the fact that it is CSS) I need to get the string between the two | characters and each time, do something:
<div id="unused">
  |#main|
  #header|
  .bananas|
  #nav|
  etc
</div>

The code I have is this:
var test_str = $('#unused').text();
var start_pos = test_str.indexOf('|') + 1;
var end_pos = test_str.indexOf('|',start_pos);
var text_to_get = test_str.substring(start_pos,end_pos);
//I want to do something with each string here

This just gets the first string. How can I add logic in there to do something for each string?

A: You can use split method to get array of strings between |
Live Demo
arr = $('#unused').text().split('|');

A: You can split like
var my_splitted_var = $('#unused').text().split('|');

A: One way;
$.each($("#unused").text().split("|"), function(ix, val) {
    val = $.trim(val); //remove \r|\n
    if (val !== "")
        alert(val);
});

A: One way :
    var test_str = $('#unused').text();

while(!test_str.indexOf('|'))
{
var start_pos = test_str.indexOf('|') + 1;
var end_pos = test_str.indexOf('|',start_pos);
var text_to_get = test_str.substring(start_pos,end_pos);
test_str  = test_str.slice(end_pos,test_str.length);
}

A: RegExp-Version:
LIVE DEMO (jsfiddle.net)
var trimmedHtml = $("#unused").html().replace(/\s/g, '');

var result = new Array();

var regExp = /\|(.+?)(?=\|)/g;
var match = regExp.exec(trimmedHtml);
result.push(match[1]);
while (match != null) {
    match = regExp.exec(trimmedHtml);
    if (match != null) result.push(match[1]);
}

alert(result);

So you only get the elements BETWEEN the pipes (|).
In my example I pushed every matching result to an array. You can now iterate over it to get your result.


text:
Q: Angular get request I have a working angular form sitting inside an app (rails app). It sends a get request to a rails server.
The problem is that if this app receives a normal get request, it refreshes the page. However, when the request is sent via angular, I can see the request on the server, but the page is never refreshed. (I can use these get requests to get data back as well).
The question is how do I pass a get request in angular form, so that the server processes it normally, and refreshes the page?
html:
<form ng-submit="submitForm()" style="margin-top:30px;">

get request

  <button type="submit" class="btn btn-primary">Get</button>
</form>

app.js controller:
$scope.submitForm = function(){
  posts.factorySubmit();
};

app.js factory get function:
o.factorySubmit = function() {
      $http.get('http://localhost:8080/clients');
};

--Side note - if I create a get request, with regular java script in the app, outside of the angular context, I get expected behavior, the page refreshes.

A: You've wrapped your $http in a factory which is great practice.  What you're not doing is capturing the response.
o.factorySubmit = function() {
      // Add a return here
      return $http.get('http://localhost:8080/clients'); // This call returns a promise
};

Then when you call this function...
$scope.submitForm = function(){
  posts.factorySubmit().then(function(response) {
    $scope.requests = response.data;  // This is where you get your response
  },
  function(response) {
    // This is your error handling
  });
};

The cool thing about angular is that it will detect changes and update the page automatically.  It has a digest cycle that is called internally in response to changes.  Since you're using the built-in $http provider, it'll refresh when you update the $scope variables.

A: Angular is by design supposed to not refresh the page as it is built for Single Page Applications. If you want to manually refresh the page, use
$scope.submitForm = function(){
  posts.factorySubmit().success(function(){
   $route.refresh();
  });
};

In the success function of your $get request. Remember to inject $route into your controller.


text:
Q: How do I create a Vertical Curve UI design? I'm looking to replicate the vertical curve in the login page that you can see in the picture below.

I've heard I can do it with SVG's but so far I've only found horizontal SVGs that do this. How do they implement it vertically?
How do they accomplish this?

A: You can achieve this effect using quadratic curve paths in SVG.

<svg viewBox="100 400" width="100" height="400">
  <path d="M 0 0 H 100 Q 0 100, 50 200 T 50 400 H 0 Z" />
</svg>

This path works like this:

*

*Draws a line to the top right corner: M 0 0 H 100

*Draws a curve from that point to the middle (arcing towards the left): Q 0 100, 50 200

*Continues the curve to the bottom middle: T 50 400

*And finally moves back to the left edge to finish the shape: H 0 Z
Here's a good article for more reading on quadratic curves in SVG: https://www.sitepoint.com/html5-svg-quadratic-curves/


text:
Q: Numerical solution of a transcendental equation as a function of three arguments I'm trying to find a function of $P1$, $Pn$ and $n$ which approximates $\xi$, below. I will implement this approximation in a much simpler application which doesn't provide numeric equation solving.
$$n=\frac{(1-Pn)^{\frac{\xi }{\xi +1}}-1}{(1-P1)^{\frac{\xi }{\xi +1}}-1}$$
How would you go about this? I've gotten mired in the documentation. I gather that it's possible and there's many ways to do it, but I'm at a loss where to start.
In case it's useful, here are the assumptions:
0 < P1 < 1 && 0 < Pn < 1 && n ∈ Integers && n > 1 && ξ ∈ Reals &&
  ξ != -1 && ξ != 0

A: Concerning your side question, the expression
$Assumptions =
  {(x_ 1 | x_N | ξ) ∈ Reals, x_ 1 > 0, x_N > 0, ξ != 0, n ∈ Integers, n > 1}

has several errors.

*

*The symbol N is a symbol reseved for the built-in function that forces numerical evaluation. Use n instead.

*Consider
x_1 | x_n // FullForm

Alternatives[Pattern[x, Blank[]], Pattern[x, Blank[n]]]

You don't want Pattern and Blank, which are pattern matching functions. You want subscripting or indexing. Use Subscript[x, 1] and Subscript[x, n] or x[1] and x[n].

*Assumptions should be given in conjunctive form not as lists. That is,
ξ != 0 && n ∈ Integers && n > 1

not
{ξ != 0, n ∈ Integers, n > 1}}

*A relation such as x > 0 implies that x is real, so for such variable you need not write x ∈ Reals.
Putting all the above together leads me to suggest you write your assumptions as
Subscript[x, 1] > 0 && Subscript[x, n] > 0 && ξ ∈ Reals && ξ != 0 && n ∈ Integers && n > 1

or
x[1] > 0 && x[n] > 0 && ξ ∈ Reals && ξ != 0 && n ∈ Integers && n > 1

Update
The following discussion is in response to further information supplied by the OP.
As I understand the problem on the basis of the new information, you want to find a function u[a, b, n] that satisfies
 n == ((1 - a)^(u/(1 + u)) - 1)/((1 - b)^(u/(1 + u)) - 1) && n ∈ Integers

But what about a and b? Are they constrained to the reals? Further, do you require u to be a real-valued function? These are difficult constraints to meet. I am pessimistic about finding any kind of solution under such constraints.
On the other hand, if a and b can be complex numbers and u can be complex valued, Mathematica can find numerical instances that satisfy your equation for certain integer values of n. But even under these relaxed constraints, I very much doubt that Mathematica can not write a symbolic expression that will represent u.

A: I may be missing something, but it looks like you are trying to solve a transcendental equation algebraically.  While MMa can undoubtedly solve more of those than I can, most of them it cannot.  A numerical method is generally required.  If you want a function that leaves n and the P's temporarily unevaluated, you could do something like this:
fn[n_, Pn_, P1_, atry_] := FindRoot[n - ((1 - Pn)^a - 1)/((1 - P1)^a - 1), {a, atry}][[1,2]]

where I changed the exponents to a in your equation.
with that you could do something like
a = fn[2, 0.5, 0.3, .1]
\[Xi] = -(a/(a - 1))

-0.168292
-0.14405

or if you want a range over n
 a = Table[fn[n, 0.9, 0.5, 0.01], {n, 2, 20}]
\[Xi] = -(a/(a - 1))

{0.777116,0.130946,-0.218891,-0.456588,-0.635699,-0.778973,-0.898135,-1.,-1.08887,-1.16763,-1.23832,-1.30239,-1.36098,-1.41492,-1.46489,-1.51142,-1.55495,-1.59584,-1.63439}

{3.48663,0.150677,-0.179582,-0.313464,-0.388641,-0.437878,-0.473167,-0.5,-0.521273,-0.538668,-0.553236,-0.565669,-0.576447,-0.585907,-0.594302,-0.601819,-0.608603,-0.614769,-0.620405}

You need to be careful with FindRoot, though, because it will give an answer even if it never converges, but it generally complains when that happens, so take those complaints seriously.  You can see from plots that for some combinations of P1 and Pn, there are no roots for any n.
No assumptions necessary, although you can put restrictions on the arguments to your function.


text:
Q: Woocommerce Variant SKU Currently in Woocommerce, when handling variable products, the SKU needs to be defined for each variant in full.
What I would like to do, is define a parent SKU, and then define suffix to SKU for each variant, and the final SKU is produced by concatenating the parent plus the variant suffix.
So lets say I have a parent product of base SKU PRODUCT_0001, the SKU PRODUCT_0001 I would like to define here:

Then for variants, say VARIANT_A, I would like to define the suffixes here:

Now the final SKU for the variant of the product (ie what is transmitted during order workflow), I would like to represent as:
PRODUCT_0001/VARIANT_A
This way, this prevents double-handling of the same base product code when setting-up/defining many variants.
Is there an easy way to accomplish this?

A: I have not tried this on email, but this works on dashboard area and frontend..
add_filter( 'woocommerce_get_sku', 'reigel_woocommerce_get_sku', 10, 2 );
function reigel_woocommerce_get_sku( $sku, $product ){
    // remove current filter to prevent unli loop on get_sku()
    remove_filter( current_filter(), __FUNCTION__ );
    if ( $product->get_type() === 'variation' ) {
        $parent = $product->parent->id?$product->parent->id:$product->get_parent();
        $sku = wc_get_product($parent)->get_sku() . '/' . $sku;
    }
    add_filter( 'woocommerce_get_sku', 'reigel_woocommerce_get_sku', 10, 2 );
    return $sku;
}

disable sku uniqueness on variation...
add_filter( 'wc_product_has_unique_sku', 'reigel_wc_product_has_unique_sku', 10, 3 );
function reigel_wc_product_has_unique_sku( $sku_found, $product_id, $sku ) {
    $product = wc_get_product($product_id);
    if ( $product->get_type() === 'variation' ) {
        $sku_found = false;
    }
    return $sku_found;
}


text:
Q: Evaluating an 3-d integral
I have not been able to evaluate the integral in part d).
I get that $\nabla^2 G = \delta(\mathbf{x})$ has Fourier transform of $-|\mathbf{k}|^2 G(\mathbf{k})=1$:
$$\implies \begin{align}\displaystyle G &=\frac{1}{(2\pi)^3}\int \frac{-1}{|\mathbf{k}|^2}e^{i\mathbf{k}\cdot\mathbf{x}} d^3\mathbf{k} \\
&= \frac{1}{(2\pi)^3}\int_{0}^{\infty} \int_{0}^{\pi} \int_{0}^{2\pi} \frac{-1}{k^2} e^{i\mathbf{k}\cdot\mathbf{x}} k^2 \sin\theta\mathrm{d}\phi\mathrm{d}\theta\mathrm{d}k
\end{align}$$
However I am unsure as to how to evaluate this especially with regard to how $\mathbf{k} \cdot\mathbf{x}$ should be evaluated.