text:
Q: realloc, for string array in C Is there a correct way to use realloc, for when you want to add words of variable size to a string array? I am getting a segmentation fault.
Please show me what's wrong
// This function puts every word found in a text file, to a String array, **words
char **concordance(char *textfilename, int *nwords){
    FILE * fp;
    char *fileName = strdup(textfilename);
    fp = fopen(fileName, "r");
    if(fp == NULL) {
        perror("fopen");
        exit(1);
    }
    char **words = malloc(sizeof(char));
    // char **words = NULL

    char line[BUFSIZ];
    while(fgets(line, sizeof(line), fp) != NULL){
        char *word = strdup(line);
        word = strtok(word, " ");
        do{
            words = realloc(words, (*nwords+1) * sizeof(char(*)));
            words[*nwords] = word;
        } while((word = strtok(NULL, " ")) != NULL);
    }
    return words;
}

int main(int argc, const char * argv[]) {
    int *nwords = malloc(sizeof(int));
    nwords = 0;
    concordance("test.txt", nwords);
}

A: You seem to initialize nwords to 0, in a wrong way. As you have declared it as a pointer, you can not access it directly. instead, you should use the de-reference operator *.
make the following change in the main function
*nwords = 0; instead of nwords = 0;
nwords = 0 modifies the location to which nwords is pointing to, to the location with address 0, to which you have no access and can not assign.
WARNING:

*

*It is better not to perform realloc on the same pointer, it will make the pointing location NULL if the realloc fails, leading to the loss of the previously existing data. Instead, as @David suggests, you could use a temp variable to realloc memory and then, check if it is not NULL and then assign its contents to the words pointer.

    //your code
    char *tmp = realloc(words, /* new size*/);
    if(tmp != NULL)
        words = tmp;
    // your code

*while using realloc you usually use it to allocate a block of data, not for a single location.

A: When you initiate the value of nwords, you   were overwriting its pointer address, not its value.
Additionally, as the commenter says, the line char **words = malloc(sizeof(char)); is not correct. But you always re-allocate the variable words so the code still works as expected. To make it super safe you should change it to char **words = malloc(sizeof(char*));
I use the line *nwords = 0; and now it works as expected.
#define BUFSIZ 1000
#include<stdio.h>
// This function puts every word found in a text file, to a String array, **words
char **concordance(char *textfilename, int *nwords){
  FILE * fp;
  char *fileName = strdup(textfilename);
  fp = fopen(fileName, "r");
  if(fp == NULL) {
    perror("fopen");
    exit(1);
  }
  char **words = malloc(sizeof(char));
  // char **words = NULL

  char line[BUFSIZ];
  while(fgets(line, sizeof(line), fp) != NULL){
    char *word = strdup(line);
    word = strtok(word, " ");
    printf("word='%s'\n",word);
    do{
      *nwords=*nwords+1;
      printf("nwords=%d\n",*nwords);
      words = realloc(words, (*nwords+1) * sizeof(char(*)));
      words[*nwords] = word;
    } while((word = strtok(NULL, " ")) != NULL);
  }
  return words;
}

int main(int argc, const char * argv[]) {
  int *nwords = malloc(sizeof(int));
  *nwords = 0;
  concordance("test.txt", nwords);
}


text:
Q: JQuery Masonry Float Left Issue I have a 2 columned website which works fine until I try to apply masonry id to my right hand column (The column I want masonry to be applied to).  My question is, how can I apply JQuery Masonry to a column which is floated left?  I've even tried putting the masonry id div inside of the floated column and it still doesn't work. Anyone know of a solution?

A: Masonry applies to one DOM element. And it works with one div(element) at ones. You can apply Masonry to as many elements as you need:
$('#left-column-id').masonry({
    itemSelector: '.item'
});
$('#right-column-id').masonry({
    itemSelector: '.item'
});

or put all sortable elements in one div with itemSelector class name (named "item" in this example).

redpajama_set_name: RedPajamaStackExchange


text:
Q: WPF, Silverlight or WinForms? The company I work for has an existing product which is a Delphi 32 bit windows application.
The application has a spreadsheet like UI which requires a very fast data grid/table view and advanced charting (plus the usual button/dropdown/menuing/toolbar controls).
We also have a .net 3.5 ASP.NET application which mirrors large parts of the business logic in the windows app.
We want to re-write the delphi application in .net, so we can have one set of business logic code.
We would like one application if possible (which is why we are looking at Silverlight).
What do we lose in going from WPF to Silverlight? Should we use neither, and use WinForms instead? or should we just further enhance the ASP.NET/AJAX application?

A: If you are not tied to an existing Winform app, and you plan on doing a lot of design work, then WPF or Silverlight should be higher up on your priority list. The main benefit of WinForms today is that they are more mature and have more 3rd party components, but XAML is becoming more popular and opens new doors in terms of application GUI design.
The choice between Silverlight and WPF mainly pivots on your distribution method and application requirements. Silverlight apps are usually accessed via a web page, and while there are methods of accessing them offline they really work best in lightweight situations. WPF apps run in "Full trust" mode and have many features that are not available even in Silverlight Offline applications. If you are talking about a simple data entry or Line of Business application, Silverlight should meet your needs, but if you need access to external resources (Hard Drive, local database, USB device, etc) then you may be stuck with a WPF application. I believe that WPF apps can use Click-Once deployment, which gives you may of the benefits of a web-deployed application while retaining full access to the underlying hardware.

A: WPF vs Silverlight
I would go for WPF, even if you have some fancy control etc. in WinForms you can always host it in WPF.

UI which requires a very fast data grid/table

WPF uses DirectX and Redering is much faster. Also you have one more way - XBAP.
On the other hand, ASP.NET/AJAX is more multiplatform.
WPF = fast rendering, ASP.NET/AJAX = multiplatform.
Silverlight is not that mature.

A: just go througth this reference also
Choosing between WPF and Silverlight

A: WPF is currently more flexible but both WPF and Silverlight are slowly merging. If you want the ability to access the application in a browser go Silverlight, otherwise WPF.
The charting may be a bit of an issue depending on how complex it is. So far there isn't many charting packages available for WPF or silverlight. ChartFX is decent but doesn't support advanced financials such as MACD etc..., which there is a financial pack available in the winforms version.
Another consideration would be if this application is for internal or external use? If it's external I would say stay away from silverlight as the adoption isn't quite there yet. If it's internal and you control the standard then definitely do silverlight vs asp.net MVC.

A: Silverlight is largely a subset of WPF (that's an oversimplification, but the general point remains).  Frankly, you don't lose a whole lot by using it over WPF -- in fact, the XAML differences between the two are enough that making one Silverlight solution is going to be easier.
In any case, I'd say that either are better than WinForms, which throws out the web interface altogether.  Also, Silverlight/WPF has a generally better rendering engine, and allows for easier separation of display and business logic.


text:
Q: ASP.NET MVC CheckboxListFor values not posting back In desperation, I created a CheckboxListFor method as follows (I ripped this off from somewhere, probably here).
public static MvcHtmlString CheckBoxListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, IEnumerable<TProperty>>> expression, MultiSelectList multiSelectList, object htmlAttributes = null)
        {
            //Derive property name for checkbox name
            var body = expression.Body as MemberExpression;
            string propertyName = body.Member.Name;

            //Get currently select values from the ViewData model
            IEnumerable<TProperty> list = expression.Compile().Invoke(htmlHelper.ViewData.Model);

            //Convert selected value list to a List<string> for easy manipulation
            var selectedValues = new List<string>();

            if (list != null)
            {
                selectedValues = new List<TProperty>(list).ConvertAll(i => i.ToString());
            }

            //Create div
            var divTag = new TagBuilder("div");
            divTag.MergeAttributes(new RouteValueDictionary(htmlAttributes), true);

            //Add checkboxes
            foreach (SelectListItem item in multiSelectList)
            {
                divTag.InnerHtml += String.Format("
<input type=\"checkbox\" name=\"{0}\" id=\"{0}_{1}\" " +
                                                    "value=\"{1}\" {2} />{3}
",
                                                    propertyName,
                                                    item.Value,
                                                    selectedValues.Contains(item.Value) ? "checked=\"checked\"" : "",
                                                    item.Text);
            }

            return MvcHtmlString.Create(divTag.ToString());
        }

I call it like so:

Rights

        @Html.CheckBoxListFor(m=>m.SelectedRights, Model.Rights)

And it renders out correctly. However, the selected values do not post back. How do I go about fixing this? Can anybody suggest a good starting point?
Update:
I thought it might be good to add some more detail, as this thing may have multiple issues.
The ids of the checkboxes are coming out like "SelectedRights_6".
Here's the ViewModel I'm currently using.
 public class RoleSingleViewModel : BaseEntitySingleViewModel
    {
    public override int ListViewColSpan
    {
        get { return 6; }
    }

    public string Name {get;set;}
    public string Description {get;set;}

    public IEnumerable<SelectListItem> Sites {get;set;}
    public int SiteId{get;set;}
    public string SiteText{get;set;}
    public override string TypeName
    {
        get { return "Role"; }
    }

    public MultiSelectList Rights { get{return new MultiSelectList(AllRights, "Key", "Value", SelectedRights);}}
    public List<KeyValuePair<int, string>> AllRights { get; set; }
    public List<KeyValuePair<int, string>> SelectedRights { get; set; }
}

Also, the update method on the controller is like so. I set a breakpoint on the line where the exception is thrown and examined updateItem. The value of Rights, AllRights, and SelectedRights are not filled in (which is, I guess, expected behavior). I'm thinking my problem might be with the structure of my ViewModel. How should I change it?
[HttpPost]
public ActionResult Edit(RoleSingleViewModel updateItem)
    {
      throw new NotImplementedException();

    }

A: Remove the ID attribute from the check-box. When it posting the selected values(only) to server, it will be array of integer or string(I never tested with string). So your model/parameter should have the same property name(and it should be an array).

A: I found that I needed to initialise a collection in order for the results to bind, i.e. the For property has to be initialised before binding. The model binder will not create the collection, but it will add the items if you have already defined the collection:
On your model
private IEnumerable<int> checkedItems = new List<int>();

public IEnumerable<int> CheckedItems
{
    get {
        return this.checkedItems ;
    }

    set {
        this.checkedItems  = value;
    }
}

And in the razor view
@Html.CheckBoxListFor(CheckedItems, ...)


text:
Q: WordPress InnerBlocks Gutenberg don't save correct I have a very simple InnerBlock. When I'm opening a page I can create a nest the blocks without any issue. I can save and view the page everything is correct. However when I'm trying to edit the page again I get the Block validation failed error:
Content generated by `save` function:

Content retrieved from post body:

Why is the block not saving correctly?
const ALLOWED_BLOCKS = ['wpptheme/faq-block'];

registerBlockType('wpptheme/faq-section', {
    //built-in attributes
    title: 'FAQ Abschnitt',
    icon: 'star-filled',
    category: 'wpptheme',

    edit() {
        return ([

Häufig gestelle Fragen

                    <InnerBlocks allowedBlocks={ ALLOWED_BLOCKS } />

        ]);
    },
    save() {

        return (

                                <InnerBlocks.Content />

        );
    }
});

registerBlockType('wpptheme/faq-block', {
    //built-in attributes
    title: 'FAQ Block',
    icon: 'star-filled',
    parent: [ 'wpptheme/faq-section' ],
    category: 'wpptheme',

    edit() {
        return ([

Block

        ]);
    },
    save() {
        return (

Test

        );
    }
});

A: The issue how the classes are being applied in save() of wpptheme/faq-section. CSS classes in React should be passed in with "className" property, unlike vanilla HTML.
Updated save() for wpptheme/faq-section:
...
    save() {

        return (

                                <InnerBlocks.Content />

    );
}
...


text:
Q: Flutter app crashes on launch "Error connecting to the service protocol" I know others have posted about this problem but none of the solutions have worked for me. Been trouble shooting/researching for about 4 hours now and no luck...
Whenever I try to do the "flutter run" command in the terminal on ios(or just running from vs code) The app launches then crashes within the first few seconds giving me the 'Error connecting to the service protocol' error message.

*

*reseting xcode simulator

*running older version (12.0) of the iphone X sim(along with other phones in the apple ecosystem)

*adding "NO_PROXY=localhost,127.0.0.1" to the .bash_profile as recommended in other posts similar to this one.
This is the code that I think may cause the error if it is code related not simulator, note that some of the data is not important and is just filler such as the local array data.
class _MyAppState extends State<MyApp> {
//-----------------Variables--------------------
  final PageController ctrl = PageController();
  List<String> local = ['1', '2', '3']; //fill with events in your area
//----------------------------------------------
  @override

  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
            body: PageView(
      scrollDirection: Axis.horizontal,
      controller: ctrl,
      children: <Widget>[
        StreamBuilder(
            stream: Firestore.instance.collection('local').snapshots(),
            builder: (context, snapshot) {
              if (!snapshot.hasData)
                return const Text('Loading...');
              else {
                return ListView.builder(
                  itemCount: snapshot.data.documents.length,
                  itemBuilder: (context, index) {
                    DocumentSnapshot userPost = snapshot.data.documents[index];
                    return Container(
                      width: MediaQuery.of(context).size.width,
                      height: 350.0,
                      child: Padding(
                          padding: EdgeInsets.only(top: 8.0, bottom: 8.0),
                          child: Material(
                            color: Colors.white,
                            elevation: 14.0,
                            shadowColor: Color(0x802196f3),
                            child: Center(
                              child: Padding(
                                  padding: EdgeInsets.all(8.0),
                                  child: Column(
                                    children: <Widget>[
                                      Container(
                                          width:
                                              MediaQuery.of(context).size.width,
                                          height: 200.0,
                                          child: Image.network(
                                            '${userPost['image']}',
                                            fit: BoxFit.fill,
                                          )),
                                      SizedBox(height: 10.0),
                                      Text('${userPost['title']}',
                                          style: TextStyle(
                                              fontSize: 20.0,
                                              fontWeight: FontWeight.bold)),

expected to have a card displayed showing firestore data but was given this terminal response:
Configuring the default Firebase app...
6.1.0 - [Firebase/Core][I-COR000004] App with name __FIRAPP_DEFAULT does not exist.
6.1.0 - [Firebase/Core][I-COR000012] Could not locate configuration file: 'GoogleService-Info.plist'.
6.1.0 - [Firebase/Core][I-COR000005] No app has been configured yet.
6.1.0 - [Firebase/Core][I-COR000005] No app has been configured yet.
*** First throw call stack:
(
    0   CoreFoundation                      0x000000010904029b __exceptionPreprocess + 331
    1   libobjc.A.dylib                     0x00000001085dc735 objc_exception_throw + 48
    2   CoreFoundation                      0x00000001090400f5 +[NSException raise:format:] + 197
    3   Runner                              0x0000000102cf5f42 +[FIRApp configure] + 562
    4   Runner                              0x0000000103244c66 -[FLTCloudFirestorePlugin init] + 214
    5   Runner                              0x0000000103244a6c +[FLTCloudFirestorePlugin registerWithRegistrar:] + 300
    6   Runner                              0x0000000102baa360 +[GeneratedPluginRegistrant registerWithRegistry:] + 112
    7   Runner                        <…>
Error connecting to the service protocol: HttpException: , uri =
http://127.0.0.1:50250/IGi9jQDg97Q=/ws

A: For Android,
Have you added internet permission in android manifest file?.
<uses-permission android:name="android.permission.INTERNET"/>

For iOS,
in Info.plist
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>


text:
Q: Elegant creating of images in JS I would like to ask if there is a more elegant way to insert images to html with javascript without jQuery than:
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title></title>
    </head>
    <body>
        <script>
            for(i = 0; i < 3; i++) {
                name = i + "_img";
                document.write("<img name=" + name + " />");
                img = document.images[name];
                img.src = i + ".png";
            }

        </script>
    </body>
</html>

Eventually I am gonna have there much more atributes and I want to avoid using < img /> as much as possible to make it more transparent.

A: You can create elements in JavaScript by using document.createElement("tag"). For example, document.createElement("image"). So you don't need to construct a string like you're doing. For some elements, such as an image, you can also just do new Image(). Keep in mind when you create an element in such a manner, it not yet part of the DOM. You must add it using appendChild or some other means.
Also, I would refrain from using document.images[] as I'm not sure that's entirely cross-browser friendly. I believe the standard practice is document.getElementsByTagName("image"), which returns an array you can iterate through.
var whereToAppend = document.getElementsByTagName("body")[0];

for(var i = 0; i < 3; i++) {
     var name = i + "_img";
     var img = new Image();
     img.src = i + ".png";
     whereToAppend.appendChild(img);
}


text:
Q: open the content in chrome browser phonegap I need help resolving the error I get when I run a phonegap android app. I'm iframing a page with an embedded UStream feed. Everything else loads perfectly expects the ustream section and I get the error:

Sorry! The stream could not be played on this device.
  Open the Content in Chrome Browser

Any assistance you can offer will be greatly appreciated.

A: Probably what is going on is that the UStream feed uses some HTML5 or other fancy API that is not yet in the WebView that Cordova/PhoneGap uses. You see, Phonegap uses a native WebView component to render the HTML content of your app. The problem is that this WebView is an oooold version of WebKit and doesn't support HTML5 and some other things. This is why the same web page will sometimes act differently depending on if you open it with Chrome browser, the standard Android browser, or with a Cordova WebView. This problem exists for all platforms as far as I know.
The slightly good news is that they just announced that Android 4.4 will have an updated WebView based on Chromium code, so hopefully your iframe will work in a 4.4 version of Cordova.


text:
Q: Non-Standard Syntax Error in Thread Constructor I'm currently looking at producing a C++ library. I've not much experience with C++ and have what is probably a very basic question about class instance method calling.
main.cpp
msgserver m;
std::thread t1(m.startServer, "192.168.50.128", 8081);

msgserver.h
class msgserver
{
public:
    msgserver() { }
    int startServer(std::string addr, int port);
};

msgserver.cpp
int msgserver::startServer(string addr, int port)

This code results in:
[C3867] 'msgserver::startServer': non-standard syntax; use '&' to create a pointer to member

I know i can fix the compiler error by making this method static but I'm unsure if that is a requirement imposed by the fact it's being called in a thread constructor (which doesn't allow the parens on the call signature) or if I need to figure out the syntax.
I've read around this and it's actually left me a bit more confused that when I started. It seems any fix I apply like:
int &msgserver::startServer(string addr, int port)
or
std::thread t1(&m.startServer, "192.168.50.128", 8081);

Is actually illegal syntax according to the compiler.
How can I call this as an instance method? Or is actually a good idea to start a thread running in the background on a static function?

A: The syntax for a getting a pointer to a member function is &<class name>::<function_name>.
In this case &msgserver::startServer would be the correct expression. Since std::invoke is used on the background thread, you need to pass the object to call the function for as second constructor parameter for std::thread, either wrapped in a std::reference_wrapper or by passing a pointer:
std::thread t1(&msgserver::startServer, std::ref(m), "192.168.50.128", 8081);

or
std::thread t1(&msgserver::startServer, &m, "192.168.50.128", 8081);

A: Replace
msgserver m;
std::thread t1(m.startServer, "192.168.50.128", 8081);

with the lambda function
msgserver m;
std::thread t1([=](std::string addr, int port){ m.startServer(addr, port); },
    "192.168.50.128", 8081);

I'm guess that you expected your version to do what the lambda function does by some kind of C++ magic. But that's not how C++ works.
Completely endorse the recommendation that you get a C++ book. Now you have lambda functions to add to your list of topics to learn.


text:
Q: How to test a COM dependent object in C# I´m trying to do TDD with an object that has a dependency on a COM Interface. I though about mocking the COM interface, while doing development testing, and do it real on the integration tests.
However, I cannot mock the COM interface, I tried with Moq, and it throws an exception:

System.TypeLoadException was unhandled
  by user code
  Message=Could not load type 'Castle.Proxies.iTunesAppProxy'
  from assembly 'DynamicProxyGenAssembly2,
  Version=0.0.0.0, Culture=neutral,
  PublicKeyToken=null'. The type is
  marked as eligible for type
  equivalence, but either it has generic
  parameters, or it is not a structure,
  COM imported interface, enumeration,
  or delegate

Is it possible with other frameworks?
How do you do TDD with COM dependent objects?
Thanks in advance!or delegate

A: Try to set "Embed Interop Types" to FALSE for assembly that contains COM interface.

A: I would suggest that you take ownership of the interface of the COM object, this is where Dependency Inversion Principle would come into play.
If you don't have access to the source, you will have to create your own abstraction that wraps the COM Object, otherwise you will have third-party calls throughout your code.
[EDIT]
Now the abstraction should be able to be mocked. The actual implementation of the wrapper will have the COM object as a HAS-A relationship.
You will then want to have an integration test for the implementation.
You need to treat the COM object itself as if it was something similar to a database or graphic rendering engine or a web service.

A: You need to add the following in the initialization part like explained here https://code.google.com/p/moq/issues/detail?id=254
Castle.DynamicProxy.Generators.AttributesToAvoidReplicating.Add(typeof (TypeIdentifierAttribute));

A: OK, I thing there is no straightforward way of doing that, not sure that some of mocking frameworks could mock COM.
What I have in my mind..
You have some COM interface, ISomeThing and COM object implements this interface CoSomeThing, this some real implementation. You should implemenent yet another COM component, that would implement same interface, but actually just mocking it - CoSomeThingMock.
In your code you instantiate CoSomeThingMock, instead of CoSomeThing and use it.
var component = new CoSomeThingMock();
var testObject = new Tested(component);


text:
Q: invalidate files in cloudfront using Ruby on Rails I want to invalidate files in cloudfront cache. The files are saved in amazon S3.
My requirement is
When I delete a post in my application, I want delete the file in S3 and send an invalidation request to cloudfront.
File delete from S3 is done. But I do not know how to send invalidation request to S3. I read about cloudfront-invalidator gem from https://github.com/reidiculous/cloudfront-invalidator/network/members. But I am not getting any specific example using that gem.

A: I got my solution using cloudfront-invalidator.
I changed as per my requirement and using it successfully..
I get problem in my rails 2.3.8 and ruby 1.8.7. So customize it and now it is successfully running
Here is the link
https://github.com/krishnasahoo/cloudfront-invalidator


text:
Q: Why do copied and pasted SSRS Expressions change? I am seeing a strange behavior in Visual Studio 2008 when creating SSRS reports.  It is happening when I copy the contents of one Text Box (Tablix Cell) and paste into another Text Box.  Any copied expressions change to give the fully qualified name of each function called.  The functions are still correct, but unsightly.
Why is this happening and is there a way to prevent it?  I am constantly copying and pasting expressions and the fully qualified names can make even simple expressions difficult for other developers to read and understand.

For Example:
Original Expression:
=IIF(ISNOTHING(Fields!MyField.Value), 0, Fields!MyField.Value)

Copied and Pasted Expression:
=Microsoft.VisualBasic.Interaction.IIF(Microsoft.VisualBasic.Information.ISNOTHING(Fields!MyField.Value), 0, Fields!MyField.Value)

A: Even i have faced the same issue and i researched about it then i found the below link that it is a bug in microsoft itself.
http://connect.microsoft.com/SQLServer/feedback/details/757358/pasting-objects-with-expressions-pastes-fully-qualified-functions


text:
Q: Generate a multivariable table output for use in Excel from R I have a data frame that looks like this:
> head(hhinc_all)
# A tibble: 6 × 6
# Groups:   county, incgrp, hhsize, hhworker [6]
  county        incgrp       hhsize hhworker na.rm     n
  <chr>         <fct>        <fct>  <fct>    <lgl> <int>
1 Hardin_Orange $0 - $25,170 1      0        TRUE   5205
2 Hardin_Orange $0 - $25,170 1      1        TRUE    984
3 Hardin_Orange $0 - $25,170 2      0        TRUE   1254
4 Hardin_Orange $0 - $25,170 2      1        TRUE    664
5 Hardin_Orange $0 - $25,170 2      2+       TRUE    102
6 Hardin_Orange $0 - $25,170 3      0        TRUE    211

The variables for this dataframe are:

*

*county = counties

*incgrp = income categories

*hhsize = households with 1 person, 2 persons, 3 persons, 4 persons,
5+ persons

*hhworker = number of workers in a household ranging from 0 to 2+
persons

*n = weighted values needed to populate the table
I need to output this data in the following way:
Household-Income-Workers Three-Way Table
I am trying to figure out how to get the output from the data frame to the picture. So, I need the income categories on the y-axis. The logic of the x-axis is that the number of workers is stratified by the household size like in the image above. The variable "n" are the values in the cells. I can easily output this to *.csv, open it in Excel and drop it into a PivotTable, but it would be much easier to just output the file in R. Is there a way to do this? Please let me know if I can provide additional info that may help.

A: Try:
library(tidyr)
pivot_wider(
  hhinc_all,
  id_cols = c(county,incgrp),
  names_from = c(hhworker, hhsize), values_from = n)

however you will obtain a table with one row of headers and two row names columns. You can choose the separator with names_sep argument.


text:
Q: How do I add a c++ library to my c9 project? I want to add curl and jansson to my c9 c++ project. I can't find any c9 documentation for this task so is this even supported?

A: Think of Cloud9 workspaces like Ubuntu machines that you have sudo access to. They come with a lot of libraries pre-installed, but it shouldn't stop you from installing and using most other libraries.
Since each workspace is uses Ubuntu, installation instructions for Ubuntu should work as-is on Cloud9 workspaces.


text:
Q: Asterisk queue agi script set variable problem ive setup asterisk with queues (agent.conf sip.conf queues.conf)
Everything is working well.
I need to send caller's id to agent's machine (or web site) from queue.
something like this
....
exten => _200,n,Queue(qtest,t,,,10,"test.pl,${MEMBERNAME},${QUEUENAME}")
MEMBERNAME and QUEUENAME are enabled by setinterfacevar=yes in queues.conf
This doesnt work :(. and i cant get that variables in agi script.
What should i do?

A: That is very strange. Ive checked version 1.4.x, 1.6.x and 1.8.x and only one solution that was working everywhere was using macros.
like this:
extensions.conf
[macro-mymacro]
exten => s,1,NoOp(${MEMBERINTERFACE})

[queue]
exten => s,1,Queue(queue)

queues.conf
setinterfacevar=yes
membermacro=mymacro

This macro will be executed right after agent will receive call. This helped me to solve the problem. I also can agi from macro


text:
Q: Download png/jpg with R i would like to download all of images from this site but after downloading photos all are corrupted. What i should do to download them successfully?
My code:
library(XML)
dir.create('c:/photos')
urls<-paste("http://thedevilsguard.tumblr.com/page/",1:1870,sep="")
doc<-htmlParse(urls[1])
links<-unique(unlist(xpathApply(doc,'//div[@class="timestamp"]/a',xmlGetAttr,'href')))
for (i in 1:length(links)){
  doc2<-htmlParse(links[i])
  link<-xpathApply(doc2,'//div[@class="centre photopage"]//p//img',xmlGetAttr,'src')[[1]][1]
  download.file(link,paste("C:/photos/",basename(link),""))
}

A: First, try and download one. Do this:
link = "http://29.media.tumblr.com/tumblr_m0q2g8mhGK1qk6uvyo1_500.png"
download.file(link,basename(link))

Does that work?
I notice its a PNG and NOT a JPEG, so maybe you are trying to read it in as a JPEG.

A: So it looks you are under Windows. When you download binary files, you have to specify the mode to be binary, e.g.
download.file(link, ..., mode = 'wb')

see ?download.file for details.


text:
Q: Is there a way to have an iframe in fullscreen? I want to put an iframe onto my page with a another div over top of the iframe to go back to a specific page, however, I cannot seem to get the iframe to go full screen (height:100% and width: 100%). Is there any work around to get the iframe in full screen?
I have already tried setting the height to window height using jquery, however, its not working.

A: You should modify your css (Set body margin to 0, position iframe absolute and set the border to 0)
Example:
body {
  margin: 0;
}

iframe {
  position: absolute;
  top: 0;
  left: 0;
  height:100%;
  width:100%;
  border: 0;
}

A: Use Viewport width and height instead of percentages
iframe {
  height:100vh;
  width:100vw;
 }

A: use the   width:100%; height:100vh;
of iframe.


text:
Q: Select entries from matrix based on row number in MATLAB I have matrix A=rand(M,N) and row vector B=randi([1 M],1,N). I want to assign entries to C from A according to the row numbers in B. That is
C(1,1)=A(B(1,1),1),  C(1,2)=A(B(1,2),2), etc. Is there easier way to get C without using a for loop?

A: You just need to use sub2ind to convert row subscripts, B, and column subscripts, 1:numel(B), into linear indices
C = A(sub2ind(size(A), B, 1:numel(B)));


text:
Q: Loss won't decrease on Siamese Network I am very new to machine learning and I started implementing a Siamese network to check the similarity level on handwritten digits, training with MNIST dataset but i am having a serious loss problem.
Network model
import keras
from keras.layers import Input, Conv2D, MaxPooling2D, Flatten, Dense, Lambda
from keras.models import Sequential, Model
from keras.optimizers import Adam
import keras.backend as K
import cv2
from keras.datasets import mnist
import numpy as np
import random

def siameseNet(input_shape):
    input1 = Input(input_shape)
    input2 = Input(input_shape)

    model = Sequential()
    model.add(Conv2D(50, (5,5), activation='relu', input_shape=input_shape))
    model.add(MaxPooling2D())
    model.add(Conv2D(100, (3,3), activation='relu'))
    model.add(MaxPooling2D())
    model.add(Conv2D(100, (3,3), activation='relu'))

    model.add(Flatten())
    model.add(Dense(2048, activation='sigmoid'))

    input_model_1 = model(input1)
    input_model_2 = model(input2)
    distance_func = Lambda(lambda t: K.abs(t[0]-t[1]))
    distance_layer = distance_func([input_model_1, input_model_2])

    prediction = Dense(1,activation='sigmoid')(distance_layer)

    network = Model(inputs=[input1,input2],outputs=prediction)

    return network

Training data
My pairs object is a numpy array with two arrays, containing the images on the same index, first half of the array are the image of the same category, second half different category.
category object is a simple array containing the same number of samples from the training set, first half of it beeing 0 to specify the Y value of beeing the same image, and second half is set to 1.
Both pairs and category are populated in the following function:
INPUT_SHAPE = (28,28,1)

def loadData():
    (X_train, Y_train), _ = mnist.load_data()
    n_samples = 20000
    arrPairs = [np.zeros((n_samples, INPUT_SHAPE[0], INPUT_SHAPE[1],INPUT_SHAPE[2])) for i in range(2)]
    category = np.zeros((n_samples))
    category[n_samples//2:] = 1
    for i in range(n_samples):
        if i%1000==0:
            print(i)

        cur_category = Y_train[i]

        img = random.choice(X_train[Y_train==cur_category]).reshape(28,28,1)
        _, img = cv2.threshold(img, .8, 1, cv2.THRESH_BINARY)
        arrPairs[0][i] = img.reshape(28,28,1)

        if category[i] == 1:
            img = random.choice(X_train[Y_train!=cur_category])
        else:
            img = random.choice(X_train[Y_train==cur_category])
        _, img = cv2.threshold(img, .8, 1, cv2.THRESH_BINARY)
        arrPairs[1][i] = img.reshape(28,28,1)
    arrPairs[0] = arrPairs[0]/255
    return arrPairs, category

Training results
pairs, category = loadData()
model = siameseNet(INPUT_SHAPE)
model.compile(optimizer=Adam(lr=0.0005),loss="binary_crossentropy")
model.fit(pairs, category,  epochs=5, verbose=1, validation_split=0.2)

Train on 16000 samples, validate on 4000 samples
Epoch 1/5
16000/16000 [==============================] - 6s 353us/step - loss: 0.6660 - val_loss: 0.9474
Epoch 2/5
16000/16000 [==============================] - 5s 287us/step - loss: 0.6628 - val_loss: 0.9335
Epoch 3/5
16000/16000 [==============================] - 5s 287us/step - loss: 0.6627 - val_loss: 0.8487
Epoch 4/5
16000/16000 [==============================] - 5s 287us/step - loss: 0.6625 - val_loss: 0.9954
Epoch 5/5
16000/16000 [==============================] - 5s 288us/step - loss: 0.6616 - val_loss: 0.9133

But no matter what I try, the loss won't decrease, thus, predicting incorrectly.
I tried changing the activations, increasing and decreasing the network complexity (adding and removing layers, as well as increasing and decreasing the Conv2D parameters), but none of that worked, so i'm guessing it is an architectural problem that I am missing
Update:
Lines used for testing:
test_pairs = [np.zeros((2, INPUT_SHAPE[0], INPUT_SHAPE[1],INPUT_SHAPE[2])) for i in range(2)]
test_pairs[0][0] = cv2.cvtColor(cv2.imread('test1_samenumber.png'), cv2.COLOR_BGR2GRAY).reshape(28,28,1);
test_pairs[1][0] = cv2.cvtColor(cv2.imread('test2_samenumber.png'), cv2.COLOR_BGR2GRAY).reshape(28,28,1);

pred = model.predict(test_pairs)
print(pred)

Which outputed:
[[0.32230237]
 [0.44603676]]

A: You have unnecessary normalization when loading in your data.  Specifically, for the first pair of images, you are dividing by 255 when that isn't required.  After you threshold with cv2.threshold, the output values are inherently 0 or 1, so further dividing by 255 makes the dynamic range smaller than the second pair of images which may cause a problem in learning how to differentiate between two images.  I've removed this normalization by commenting out the arrPairs[0] = arrPairs[0] / 255 statement.
After I trained your network, I ran through each of the pairs and examined the output prediction.  Essentially, if the category is 1 and the prediction generated by the network (your sigmoid layer) is larger than 0.5, I count this as a correct prediction.  Similarly, when I see that the category is 0 and the prediction generated is smaller than 0.5, this is also correct.
correct = 0
for i in range(len(pairs[0])):
    output = model.predict([pairs[0][i][None], pairs[1][i][None]])[0][0]
    if (category[i] == 1 and output >= 0.5) or (category[i] == 0 and output < 0.5):
        correct += 1

print(correct / len(pairs[0]))

I get a 99.26% accuracy here, meaning that 0.74% out of 20000 samples, or about 148 samples were incorrectly classified.  I'd say that's a good result.
Reproducible Google Colab notebook can be found here: https://colab.research.google.com/drive/10Q6rjuiytRSump2nulW5UhXY_PJh1eor


text:
Q: Is their any way to do Frame by Frame Animation in canvas ..? For normal Activity with the help of ImageView we are able to attain Frame Animation ("Through some online tutorial i done that")
    img = (ImageView) findViewById(R.id.myimage);
    img.setBackgroundResource(R.drawable.loadimage);
    AnimationDrawable frameAnimation = (AnimationDrawable) img.getBackground();
    frameAnimation.start();

but here in Canvas i'm using Bitmap to get an image to the view, their i'm stuck..
    Resources res = getResources();
    Bitmap bitmap = BitmapFactory.decodeResource(res, R.drawable.loadimage);

is their any way to do frame animation in canvas..?

A: You can create an animated custom view using SurfaceView with a Thread to schedule the animation times properly.
The idea is to extend from SurfaceView, get the Canvas from the SurfaceHolder, draw on it, post the draw on the screen, and repeat (done in a background thread). A basic example:
public class CustomView extends SurfaceView implements Runnable {

    Thread animationThread = null;
    SurfaceHolder holder;
    volatile boolean running = false;

    public CustomView(Context context) {
        super(context);
        holder = this.getHolder();
    }

    // called from Activity's onResume() to start the thread
    public void resume() {
        running = true;
        animationThread = new Thread(this);
        animationThread.start();
    }

    // called from Activity's onPause() to end the thread
    public void pause() {
        running = false;
        while(true) {
            try {
                animationThread.join();
                break;
            } catch (InterruptedException e) { }
        }
    }

    // run until pause() is called
    @Override
    public void run() {
        while(running) {
            if(!holder.getSurface().isValid())
                continue;

            Canvas canvas = holder.lockCanvas();
            // your drawing logic goes here:
            // - calculate the time of the frame
            // - draw a different bitmap each time ...
            canvas.drawBitmap(...)
            holder.unlockCanvasAndPost(canvas);
        }

    }
}

To handle the size of the view, you would need to override onMeasure() and onSizeChanged().
For a better understanding of how this works:

*

*http://blog.infrared5.com/2011/06/android-graphics-and-animation-part-i/

*http://blog.infrared5.com/2011/07/android-graphics-and-animation-part-ii-animation/

*http://developer.android.com/reference/android/view/SurfaceView.html


text:
Q: How to install and execute e2defrag on KuBuntu? How to install and execute e2defrag on KuBuntu?
http://launchpad.net/e2defrag
From the link:

Utility for offline defragmentation of ext[234] filesystems.
This poor ancient package used to be known as the defrag packge but was removed from Debian and hence Ubuntu due to it not having had a maintainer in many years and suffering from bit rot. I am rescuing it from the bit bucket.

A: You don't mention which version of Ubuntu you are using but packages are only available for 14.04 through 15.10 at this time as it's been almost 2 years since the PPA has been updated. Since 14.04 is the only one of these currently supported, I'm providing instructions for that version.
For 14.04
Run the following commands in a terminal
sudo add-apt-repository ppa:dpmva1/ppa
sudo apt-get update
sudo apt-get install e2defrag

EDIT from man page:
Note  that  unlike  the  fsck  program,  defrag MUST NOT be run on a mounted file system device
       (unless invoked with the -r (readonly) option, which is always safe).  Also note  that  if  you
       defragment  a  partition  containing  a bootable kernel image and are using lilo ( grub doesn't
       care unless you have it installed in the partition using blocklists instead of the MBR  ),  you
       will  have to reinstall the boot loader for that image (since the location on disk of the image
       may have changed).

       Remember, if defrag fails to complete for any reason (including  power  glitches,  kernel  bugs
       etc.), you will be left with a terminally sick, and possibly completely unreadable, filesystem,
       so backup any valuable data before you start.

Installation tested on 14.04.5 I have no reason to expect the point release is relevant.


text:
Q: MS Access: Conditional formatting - highlight duplicates Is there an expression that I can use in MS Access ,to highlight Duplicate entries in Reports?
I tried something like Expression is : Count(*)>1 but it doesn't work.
Br,

A: I suspect that the original query will need to be bulked up with a sub-query that has an ID column and count of ID.  The outermost query will then need to also return the ID count.
Within the report you'd then need add another field that would show the linked ID count if it was > 1.

A: Access reporting (and forms) allows conditional formatting to be used in a similar way to excel.
See Ribbon: Report Design Tools>Formt>ControlFormatting...
It will let you change the format of a control depending on the value it, or another control, contains.
It's a very nice feature and will also let you add bar charts to you list forms to graphically represent the values sorted in a control.
However, the data set will need to have a column that indicates whether the current row has duplicate records.  The snippet from you current query that you provided (that I repeat below) will not do this:
 ...OR (((Object.Key) In (SELECT [Key] FROM [Object] As Tmp GROUP BY [Key] HAVING Count(*)>1 )));

Without seeing the whole query I can't really help much, but you will need to remove the use of IN and make the SELECT statement a subquery of the main SQL Statement.  The main query resultset will need to be  LEFT JOINED to the sub query using the Key field.  Because of the LEFT JOIN you can use "isnull(Key)" in the SELECT clause and isnull(Key) will be true for non-duplicate rows.
You can then refer to thiscolumn in your conditional formatting
I hope this makes some sense.
You

A: For a quick and dirty way to highlight duplicate data:

*

*Select the object you want to highlight if it's duplicated, and make
the background white (or whatever the colour of your background is).

*Create a copy of the object that you want highlighted if it's
a duplicate.

*Format the copy so it has a highlight, and/or add extra text
(eg:  DUPLICATE)

*Put the copy behind the original (so it can't be seen).

*On the original object, select "Hide duplicates" in properties.

*Ensure "Hide duplicates" is NOT selected on the copy.
So when the duplicate appears, Access will hide it, but then the object you've created that was originally hidden beneath now becomes visible - effectively highlighting the field.
(Unfortunately it will only highlight the field itself, not the entire section.)


text:
Q: MongoDB Compass returns all rows when I run a filter I am trying to run a filter in MongoDB Compass and it returns all rows instead of the row that I am looking for.  I can run the filter on example databases that are similar to my database without any problem.
https://i.stack.imgur.com/IBivJ.png
Here is the code that I am using to add records and select from them.
public class NoSQLDataAccess
{
    // Create an instance of data factory
    public NoSQLDataFactory noSQLDataFactory;
    public List<dynamic> DocumentDetails { get; set; }
    private IMongoCollection<dynamic> collection;
    private BsonDocument bsonDocument = new BsonDocument();

    public NoSQLDataAccess() { }
    public void TestNoSQL()
    {
        MongoClient client;
        IMongoDatabase database;
        string connectionString = ConfigurationManager.AppSettings["NoSQLConnectionString"];
        client = new MongoClient(connectionString);
        database = client.GetDatabase("TestDatabase");
        collection = database.GetCollection<dynamic>("TestCollection");
        // Insert
        List<Layer> layers = new List<Layer>();
        layers.Add(new Layer { LayerId = 117368, Description = "BOOTHLAYER" });
        layers.Add(new Layer { LayerId = 117369, Description = "DRAWINGLAYER" });
        layers.Add(new Layer { LayerId = 117370, Description = "LAYER3" });
        List<Element> elements = new List<Element>();
        elements.Add(new Element { ElementId = 9250122, Type = "polyline" });
        elements.Add(new Element { ElementId = 9250123, Type = "polyline" });
        List<dynamic> documentDetails = new List<dynamic>();
        documentDetails.Add(new DrawingDTO { Layers = layers, Elements = elements });
        collection.InsertMany(documentDetails);
        List<FilterDetails> filterDetails = new List<FilterDetails>();
        filterDetails.Add(new FilterDetails { Type = "layers.id", Value = "117368" });
        foreach (FilterDetails detail in filterDetails)
        {
            bsonDocument.Add(new BsonElement(detail.Type, detail.Value));
        }
        List<dynamic> results = collection.Find(bsonDocument.ToBsonDocument()).ToList();
    }
}

I have been able to get the result I need with MongoDB shell but I have not been able to replicate the results in C#.
Here is the solution in MongoDB shell:
db.TestCollection.find({"layers.id": 117368}, {_id:0, layers: {$elemMatch: {id: 117368}}}).pretty();

A: I have found a post that is similar to my question that works for them.  The C# code that I attached is how I will access it after I get it working properly.  I use MongoDB Compass to test finds/inserts/updates/deletes.
Retrieve only the queried element in an object array in MongoDB collection


text:
Q: How to declare an import name the same as declared in another constants/variables file I have two files, routes.js and package.ts
I want to declare an import name in package.ts by using variable declared in routes.js
This is routes.js
//object for the whole app routes
export default Object.freeze({
  packageModule: "PackageModule",
  complaintModule: "ComplaintModule",
  login: "Login",
});

Now i want to declare like this in package.ts -
import routes from "../../navigation/routes";
import routes.packageModule from './SearchPackage';

export { routes.packageModule };

How to handle this properly? This is because i want to have a common place to manage all my imports in react native.


text:
Q: Testing to see if a string contains any of a set of other strings in PHP I am trying to test if a url leads to an image, such as "http://i.imgur.com/vLsht.jpg"
by testing to see if the string contains ".jpg" or ".png" or ".gif" etc.
My curent code is:
if (stripos($row_rsjustpost['link'], ".png") !== false) {
//do stuff
}

I would like to do something like
if (stripos($row_rsjustpost['link'], ".png" || ".jpg" || ".gif") !== false) {
//do stuff
}

A: This is an okay use of a regular expression via preg_match():
$matches = array();
if (preg_match('/\.(png|jpg|gif)/i', $row_rsjustpost['link'], $matches) {
    // Contains one or more of them...
}

// $matches holds the matched extension if one was found.
print_r($matches);

Note: if the string must occur at the end like a file extension, terminate it with $:
/\.(png|jpg|gif)$/i
//-------------^^

If you were attempting to locate only one substring, it would be more appropriate to use stripos(), but you can match a number of different patterns with a regex, without having to cough out a long if/else chain.

A: If I didn't want to use regular expressions, here's how I'd do it:
Get the last 4 characters (the file extension)
$filepath = $row_rsjustpost['link'];
$extension = substr($filepath, length($filepath) - 4);

Then see if it matches a pattern:
if (in_array($extension, array(".png", ".jpg", ".gif"))) {
   // Have a party!
}


text:
Q: Viewing .doc file with java applet I have a web application. I've generated MS Word document in xml format (Word 2003 XML Document) on server side. I need to show this document to a user on a client side using some kind of viewer. So, question is: what libraries I can use to solve this problem? I need an API to view word document on client side using java.

A: You cannot reliably display a Word document in a web page using Java (or any other simple technology for that matter). There are several commercial libraries out there to render Word, but you will not find these to be easy, cheap or reliable solutions.
What you should do is the following:
(1) Open the Word engine on the server using a .NET program
(2) Convert the document to Rich Text using the Word engine
(3) Display the rich text either using the RTF Swing widget, or convert to HTML:
String rtf = [your document rich text];
BufferedReader input = new BufferedReader(new StringReader(rtf));

RTFEditorKit rtfKit = new RTFEditorKit();
StyledDocument doc = (StyledDocument) rtfKit.createDefaultDocument();
rtfEdtrKt.read( input, doc, 0 );
input.close();

HTMLEditorKit htmlKit = new HTMLEditorKit();
StringWriter output = new StringWriter();
htmlKit.write( output, doc, 0, doc.getLength());

String html = output.toString();

The main risk in this approach is that the Word engine will either crash or have a memory leak. For this reason you have to have a mechanism for restarting it periodically and testing it to make sure it is functional and not hogging memory.

A: docx4all is a Swing-based applet which does Word 2007 XML (ie not Word 2003 XML), which we wrote several years ago.
Get it from svn.
That's a possible approach for editing.  If all you want is a viewer, which not convert to HTML or PDF?  You can use docx4j for that.  (Disclosure: "my" project).

A: You might have a look at the Apache POI - Java API to Handle Microsoft Word Files which  is able to read all kinds of word documents (OLE2 and OOXML formats, .doc and .docx extensions respectively).
Reading a doc file can be easy as:
import java.io.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;

public class ReadDocFile {
public static void main(String[] args) {
File file = null;
WordExtractor extractor = null ;
try {

file = new File("c:\\New.doc");
FileInputStream fis=new FileInputStream(file.getAbsolutePath());
HWPFDocument document=new HWPFDocument(fis);
extractor = new WordExtractor(document);
String [] fileData = extractor.getParagraphText();
for(int i=0;i<fileData.length;i++){
if(fileData[i] != null)
System.out.println(fileData[i]);
}
}
catch(Exception exep){}
}
}

You can find more at: HWPF Quick-Guide (specifically HWPF unit tests)
Note that, according to the POI site:

HWPF is still in early development.

A: I'd suggest looking at the openoffice source code and implement that.
It's supposed to be written in java.


text:
Q: Trying to connect to an ODBC server using RODBC in ubuntu I am getting the error:
 [RODBC] ERROR: state 01000, code 0, message [unixODBC][Driver Manager]Can't open lib 'SQL Server' : file not found
 2: In odbcDriverConnect("driver={SQL Server};server=*******;database=****;trusted_connection=true") :
 ODBC connection failed

Can anyone provide detailed instructions on installing the driver for ODBC in order for it to work with RODBC?
Note: I am trying to connect to an MSSQL Server

A: Here at my job, we use Centos 5.8. When I need to connect to our MS-SQL servers, I use FreeTDS drivers. I talk a bit more about it here: https://stackoverflow.com/a/10196098/1332389, including the packages and dependencies that I installed.
A sample connection string might look like this:
data_odbc <- odbcDriverConnect(connection="Driver=FreeTDS;
                                           Server=dataserver1\\instancename(default: master);
                                           Port=1433;
                                           Database=database_01;
                                           Uid=data_mgmt;
                                           Pwd=placeholder")

We configured our odbcinst.ini file (in /etc/) to say:
# FreeTDS Drivers
# Manual setup, used for MS SQL
[FreeTDS]
Description     = FreeTDS for MSSQL
# 32 bit
Driver          = /usr/lib/libtdsodbc.so
Setup           = /usr/lib/libtdsS.so
# 64 bit
Driver64        = /usr/lib64/libtdsodbc.so
Setup64         = /usr/lib64/libtdsS.so
FileUsage = 1

I've had no issues since getting it set up. Hope this helps - I can try and answer if you have more questions.

A: I had similar problem using remote R session on Linux, with RJServer, connecting to it from StatET under Eclipse. The error looked like this:
[RODBC] ERROR: state 01000, code 0, message [unixODBC][Driver Manager]Can't open lib '/usr/local/easysoft/sqlserver/lib/libessqlsrv.so' : file not found
The difficulty of solving this problem was that the error message is misleading: the file shown in the message is perfectly visible (I could test it). The "secret" is that "file not found" refers to another dependent library.
Bottom line: I added few elements to the LD_LIBRARY_PATH used in the remote session, in my case it was:
/usr/local/easysoft/unixODBC/lib:/usr/local/easysoft/lib
To figure out what you need to add, you should see what is missing. Use "ldd" command on the library in question.


text:
Q: For which partial orders is the Axiom of Choice necessary to prove the existence of ultrafilters? This question is about ultrafilters on partial orders. Using the Axiom of Choice, one may prove that every partial order has an ultrafilter on it. For certain partial orders, some form of AC is known to be necessary, but for other partial orders this is not so:
Example 1: (ZF) If $P$ is atomic, then it has an ultrafilter.
Example 2: (ZF) If $P = \omega^{<\omega}$ is the set of all finite sequences of integers, ordered by extension, then it has an ultrafilter. Any $r \in \omega^\omega$ can be used to define an ultrafilter on $P$, namely the set of all finite initial subsequences of $r$.

My question is whether we can determine that the statement "there exists an ultrafilter on $P$'' is independent of ZF just by looking at the combinatorial properties of $P$ (without needing to go through a forcing argument to construct a symmetric model).

I don't expect an exact characterization. But I would love to know a reasonably general sufficient condition for implying that ZF is not strong enough to prove the existence of an ultrafilter on $P$.
My motivating example:
Let $P$ be the set of all dense subsets of $\mathbb R$, ordered by inclusion. I came across this partial order recently while thinking about a problem in topology, and I'd like to know whether ZF alone proves that this partial order admits an ultrafilter.
I strongly suspect that the answer is no (though I have not yet tried to work out the details). Right now, the only way I know to approach the problem is to build a symmetric model of ZF. It seems to me that it should be possible, somehow, to know beforehand, just by looking at $P$, that something beyond ZF is needed to get an ultrafilter.
A caveat:
In my question above, we should think of $P$ as the unique partial order satisfying some definition. In particular, I want to allow that $P^M$ and $P^N$ can be two different sets if $M$ and $N$ are two different models of set theory. (For example, the phrase "the dense subsets of $\mathbb R$, ordered by inclusion" defines a partial order, but the set satisfying this definition can be made larger by forcing.)
This point is perhaps pedantic, but also pertinent. To see why, suppose $P$ is a partial order in some model $M$ of ZFC, and suppose $N \supseteq M$ is a model of ZF. Then $P \in N$, $P$ is a partial order in $N$, and, no matter what, $P$ has an ultrafilter in $N$. The proof is easy: fix $U \in M$ such that $M \models$ "$U$ is an ultrafilter on $P$'' and then observe that the statement "$U$ is an ultrafilter on $P$'' is absolute to larger models of set theory.
Example 3: (ZF) If $P$ is a constructible partial order (i.e., if $P \in L$) then $P$ has an ultrafilter. In fact, any $U \in L$ such that $L \models$ "$U$ is an ultrafilter on $P$" is an ultrafilter on $P$.


text:
Q: Why doesn't this rule create a file every time it is built? I write the below bazel rule for incremental test.
This rule(foo_library) has a dependency property.
When there are no dependencies, it creates a file with its own name, filling the contents of the file with its own name.
When there is a dependency, it creates a file with its own name, and at this time, the contents of the file are filled by adding its own name to the contents of the file created by the dependency target.
In this test, foo3, foo2, and foo1 are linked as dependencies, so I expected 3 files to be created, but only foo3 was created.
What could be the problem?
Hera are my test bazel code, build command and log message.
# ~/rules/dev.bzl
def _foo_binary_impl(ctx):

    this_name = ctx.attr.name
    file_name = ctx.actions.declare_file(ctx.label.name)

    print("##-000 this_name: {}".format(this_name))
    print("##-001 file_name: {}".format(file_name))

    file_content = ""

    if ctx.attr.deps:
        for dep in ctx.attr.deps:
            t1 = dep[DefaultInfo].files.to_list()[0].basename
            t1 = t1 + this_name
            print("##-100 t1: {}".format(t1))

            file_content = t1

    else:
        t2 = this_name
        print("##-101 t2: {}".format(t2))

        file_content = t2

    ctx.actions.write(
        output = file_name,
        content = file_content,
    )

    return [
        DefaultInfo(
            files = depset([file_name])
        ),
    ]

foo_binary = rule(
    implementation = _foo_binary_impl,
    attrs = {
        "deps": attr.label_list(),
    },
)

# build command and log
$> bazel build -s //rules/example:foo3                                                                                1 х  11:38:08
DEBUG: ~/rules/dev.bzl:10:10: ##-000 this_name: foo1
DEBUG: ~/rules/dev.bzl:11:10: ##-001 file_name: <generated file rules/example/foo1>
DEBUG: ~/rules/dev.bzl:25:14: ##-101 t2: foo1
DEBUG: ~/rules/dev.bzl:10:10: ##-000 this_name: foo2
DEBUG: ~/rules/dev.bzl:11:10: ##-001 file_name: <generated file rules/example/foo2>
DEBUG: ~/rules/dev.bzl:19:18: ##-100 t1: foo1foo2
DEBUG: ~/rules/dev.bzl:10:10: ##-000 this_name: foo3
DEBUG: ~/rules/dev.bzl:11:10: ##-001 file_name: <generated file rules/example/foo3>
DEBUG: ~/rules/dev.bzl:19:18: ##-100 t1: foo2foo3
INFO: Analyzed target //rules/example:foo3 (3 packages loaded, 8 targets configured).
INFO: Found 1 target...
Target //rules/example:foo3 up-to-date:
  bazel-bin/rules/example/foo3
INFO: Elapsed time: 0.107s, Critical Path: 0.00s
INFO: 2 processes: 2 internal.
INFO: Build completed successfully, 2 total actions

Build foo3 and expected 3 files(foo1, foo2, foo3) are generated. howver, foo3 is generated only.

A: If ctx.attr.deps is nonempty, foo_binary_impl writes a file with content that depends on the file name of the last file in ctx.attr.deps rather than the content of the last file in ctx.attr.deps. No dependency on any file in ctx.attr is ever introduced. Therefore, Bazel does not build anything in deps when producing the output of foo_binary_impl.
To make the output of foo_binary_impl depend on the content of dependencies, make an action to produce the final output that takes the dependency files as inputs. For example, to concatenate all the files in deps into the output:
ctx.actions.run_shell(
    inputs = ctx.files.deps,
    outputs = [file_name],
    command = "cat " + " ".join([f.path for f in ctx.files.deps]) + " >" + file_name.path,
)


text:
Q: Intuition behind canonical definition of inner product structure of tensors Consider Napkin Problem 13D (a):

Let $V$ and $W$ be finite-dimensional inner product spaces over $k$, where $k$ is either $\mathbb{R}$ or $\mathbb{C}$. Find a canonical way to make $V \otimes_k W$ into an inner product space too.

I approached this by working on special cases. Let $e_1, \dots , e_n$ and $f_1, \dots , f_m$ are orthonormal bases for $V$ and $W$, respectively.
I think we want $\langle e_1 \otimes f_1, e_1 \otimes f_1 \rangle_{V \otimes W} = 1$, since it feels like $\|e_1\| = \|f_1\| = 1$ should imply that $\| e_1 \otimes f_1 \|$. We also want $\langle e_1 \otimes f_1, e_2 \otimes f_2 \rangle_{V \otimes W} = 0$, since it feels like the fact that $e_1$ and $e_2$ are orthogonal and $f_1$ and $f_2$ are orthogonal should imply that $e_1 \otimes f_1$ and $e_2 \otimes f_2$ are orthogonal.
So for any $v_1, v_2 \in V$ and $w_1, w_2 \in W$, the inner form $\langle v_1 \otimes w_1, v_2 \otimes w_2 \rangle_{V \otimes W} := \langle v_1, v_2 \rangle_V \langle w_1, w_2 \rangle_W$ seems like a good choice, and it ended up being the intended inner form.
But I'm still very uncomfortable with the intuition behind this; is there a more solid way to understand why we take the product of the individual inner forms to get the inner form of the tensor product?

A: Canonical is an imprecise word, but here is a justification. An inner product on $V$ is a map $V \otimes V \to k$ with certain properties. So having inner products on $V$ and $W$ gives a map
$$(V \otimes W) \otimes (V \otimes W) \cong (V \otimes V) \otimes (W \otimes W) \to k \otimes k \xrightarrow{(x \otimes y) \mapsto xy} k$$
and I would argue that the first isomorphism and the third map, the multiplication on $k$, are the canonical maps with those domains and targets. This composition is exactly the same as your formula, but all it says is that given bilinear forms on $V$ and $W$ there is a "canonical" bilinear form on $V \otimes W$. You still have to check that it's an inner product if you start with inner products.
To add some intuition in line with @Milten's comment, an inner product (or more generally a bilinear form) on $V$ is a product on $V$ taking values in $k$, so is a function on $V \otimes V$ since that's the universal target for a product on $V$. To have a way to multiply $v_1 \otimes w_1, v_2 \otimes w_2 \in V \otimes W$ (*) it should suffice to know how to:

*

*rearrange to $(v_1 \otimes v_2) \otimes (w_1 \otimes w_2)$;

*multiply $v_1$ with $v_2$ and $w_1$ with $w_2$ individually to get elements of $k$;

*multiply in $k$.

These are precisely the three maps that are being composed; 1 and 3 are "canonical" and 2 is the input.
(*) I'm ignoring that not all elements are pure tensors, but a "product" should satisfy distributive law so it's enough to know what it does to a generating set anyway.


text:
Q: Excel Sum instances of an item in a column until a different column variable is met What I'm trying to accomplish is a little complicated to explain:
There is a formula that inserts an integer into Columns B or C depending on the values of other columns (not shown here).
What I want to do it place a sum of the items in column B where the criteria are:

*

*Items in column B have a value of 1

and

*The range that is counted are all items between Type A and Type A (in the image below B2:B13)

The sum should be placed in the cell in line with the instance of Type A being used for the range.
So Below I want the sum of items in column B that are occur in rows B3:B13 and have that number placed in B2.
Then the same for B15:B24 and the result placed in B14, and so on...
The test in column A that will be the trigger will remain consistent as it is auto-generated.
Then the same would happen in column C (which I'm assuming I can just use the same formula just change the column references)

Any help would be appreciated.

A: Place this formula in B2:
=IFERROR(SUM(OFFSET(B3,0,0,MATCH($A2,$A3:$A1000,0)-1,1)),SUM(B3:B1000))

Then filter on all rows with Type A and copy from B2 for all the visible cells.
The IFERROR is only for the last Type A (with no Type A underneath it. Then it will just sum the remaining rows underneath. Also, adjust the 1000 if needed.


text:
Q: How to print a list of values + max/min I am looking at this Little man computer problem:

*

*The user will enter first the size of the data, and then the individual numbers.

*I have to print (OUT) excatcly what was input, followed by the max and the min of the data values
Example:

*

*First input: 2 // Number of DATA

*Second input: 5 // First DATA

*Third input: 7 // Second DATA

*Output: 2, 5, 7, 5(min), 7(max)

I have to print everything at the end (when the user finished to enter all the inputs)
My attempt:
        IN         # Acc = number of values to read (N)
        STO M
LOOP    BRZ PRG
        SUB ONE
        STO N      # N=N-1
        IN         # values
ST      STO PRG    # Store it in the program starting at PRG
        LDA ST     # Get current store command (ST)
        ADD ONE    # add one to store command to increment memory location
        STO ST     # Update store command (ST)
        LDA N      # Put current value of N in accumulator
        BRZ PRINT
        BRP LOOP    # Continue loop - 12

#My problem is here
PRINT   LDA M
        OUT
        LDA PRG
        OUT

FIN     HLT

M       DAT 0
N       DAT 0      # Number of values to read
ONE     DAT 1      # Value 1
PRG     DAT 0      # We will store all of the values from this point onward

Question
I tried to get this solved, but as you can see, I only succeeded to print the first value. I also saved my inputs in memory, but how can I loop on the address to get the values for output?

A: The self-modifying code pattern, that you have used to store the input, can also be used to output it. Instead of modifying the dynamic STO PRG instruction, you would have a dynamic LDA PRG instruction.
Your attempt shows no code for determining the minimum and maximum value. You can either collect this information during the input loop or during the output loop.
Please take into consideration these additional remarks:

*

*initialise the variables (that are not constants) with code, so that if the LMC is reset (without a complete re-assembly), it still works correctly.

*use more descriptive labels and variable names. ST and PRG are quite obscure names...

So it could work like below. This code uses the LMC mnemonics as described on Wikipedia. So STA = STO and INP = IN. You can run the program here:

#input: 5 3 9 6 2 4
           INP # data size
           BRZ halt # nothing to do
; initialise (so program still runs correctly when reset)
           STA size
           LDA halt # =zero
           STA max
           LDA big
           STA min
           LDA staArray
           STA store
           LDA ldaArray
           STA load

; input loop
           LDA size
           SUB one
nextInput  STA counter
           INP # get data value
store      STA array # self-modified
           STA value
           SUB min
           BRP checkmax
           LDA value
           STA min
checkmax   LDA max
           SUB value
           BRP incInput
           LDA value
           STA max
incInput   LDA store
           ADD one
           STA store # modify code
           LDA counter
           SUB one
           BRP nextInput

           LDA size
           OUT # output input size
           SUB one
outputLoop STA counter
load       LDA array # self-modified
           OUT # output data value
           LDA load
           ADD one
           STA load # modify code
           LDA counter
           SUB one
           BRP outputLoop

           LDA min
           OUT
           LDA max
           OUT

halt       HLT

# constants
one        DAT 1
big        DAT 999
staArray   STA array
ldaArray   LDA array

# variables
size       DAT
counter    DAT
min        DAT
max        DAT
value      DAT
array      DAT

<script src="https://cdn.jsdelivr.net/gh/trincot/lmc@v0.812/lmc.js"></script>

Remark:
If there would not be the requirement that the output is only produced after all input has finished, you would not need self-modifying code. See this answer where the output is generated while the input is processed.


text:
Q: can I clean tmp folder in rails project - ruby on rails I have a simple question:
can I delete the content in the tmp folder in my rails project? Or will there be some errors?
I don't want to try because I am afraid...

A: Yes , the tmp folder will be automatically regenerated if you delete it


text:
Q: Nest a function I am trying to develop a game in python using tkinter.
To do so, I need to use a nested function. I think I have formatted the call correctly, but the error code is:
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\Chris\AppData\Local\Programs\Python\Python36-32\Lib\tkinter\__init__.py", line 1699, in __call__
    return self.func(*args)
  File "C:/Users/Chris/Desktop/Paul's stuff/Paul/CpmpProject/question screen.py", line 56, in display
    answer1 = Button(self.master, text=output[0], command= Buttons.display.check())
AttributeError: 'function' object has no attribute 'check'

My code is below. I am new to tkinter so a basic explanation would be best, if possible.
from tkinter import *
from pygame.locals import *

class Buttons:

    def __init__(self, master):
        self.master = master
        self.frame = Frame(self.master)
        self.b1 = Button(self.master, text="Button1", command=self.display)
        self.b2 = Button(self.master, text="Button2", command=self.new_window)
        self.b1.pack()
        self.b2.pack()
        self.frame.pack()

    def display(self):
        def check():
            if player_answer == answers[s][0] or player_answer == answers[s][1]:
                score += 1
                return score
            else:
                print("Wrong")
                return score
        import random
        import pygame
        from random import shuffle
        import sys
        questions = ["What species of bird is also a nickname for New Zealand?",
                     "Which Twins can you play as in Assassin's Creed Syndicate?",
                     "Which year was 'Killing In The Name' Christmas Number one?"]

        answers = [["kiwi", "Kiwi", "Falcon", "Sparrow", "Crow"], ["frye", "Frye", "Bank", "Green", "Bundy"],
                   ["2009", "2009",
                    "1999", "1993",
                    "2004"]]
        # I had to do it in two separate lists as it's easier to work with later on
        # Also I made the correct answers non-case sensitive to make it easier to test.

        r = len(questions)
        score = 0
        s = random.randrange(0, r, 1)
        # This generates a random number within the range of how many questions there are
        # and then prints out that question
        w = Label(text=questions[s])
        w.pack()

        pygame.init()
        self.FPS = 60
        self.fps_clock = pygame.time.Clock()
        self.surface = pygame.display.set_mode((640, 480))
        list = answers[s]
        output = []

        for i in range(1, 5):
            output.append(answers[s][i])
        shuffle(output)
        answer1 = Button(self.master, text=output[0], command= Buttons.display.check())
        answer2 = Button(self.master, text=output[1], command= Buttons.display.check())
        answer3 = Button(self.master, text=output[2], command= Buttons.display.check())
        answer4 = Button(self.master, text=output[2], command= Buttons.display.check())
        # this takes the answers that correspond with the randomly generated question and shuffles the answers
        # I did this as otherwise, the answer would always be the first answer to appear and the player could exploit this
        answer1.pack()
        answer2.pack()
        answer3.pack()
        answer4.pack()
        player_answer = input()

        while True:
            pygame.display.update()
            self.fps_clock.tick(self.FPS)
            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit()

I really need help with this otherwise I wouldn't be asking on a public platform.

A: You don't want Buttons.display.check, that will get the check attribute of Buttons.display. You just want check, because it is already in scope.
Also, don't call it; pass check, not check()


text:
Q: Working with branches in Dulwich (access objects / checkout) I have a problem with Dulwich (switched to it from GitPython because of the well-known Windows bug with opened files in .git folder).
I'm trying to get a file from another branch of currently opened repo (its state from last commit). In GitPython this task can be solved in nice and easy manner:
file_object = repo.heads[BRANCH].commit.tree[FILENAME]

But I didn't found any comfortable way to deal with branches in Dulwich.
While writing this question I've found a get_refs method which returns dictionary with all refs and the commits they're pointed. Now I think I can get SHA of the last commit but the refs are very unfriendly to work with - I need to use such form to get a commit:
commit_id = repo.get_refs()[b"refs/heads/develop"]

After that I can get my file in this way:
    tree_path = porcelain.path_to_tree_path(REPO_ROOT, os.path.join(REPO_ROOT, FILENAME))
    _, object_sha = tree_lookup_path(repo.get_object, repo[commit_id].tree, tree_path)
    file_object = repo[object_sha].data

Is there a proper (more "pythonic"/"gitonic") way to get the needed version of a file without checking out a branch fully? Some staged/unstaged files can be stored in repo at the moment of program running and I suppose they will interrupt the checkout process.
Now the main problem for me is the need to "pack" usual branch name to "refs/heads/" form.
And if there is no more accurate way to get this information - I hope my question may help someone in future :)
Python: 3.6.1
Dulwich: 0.19.6

A: In recent versions of dulwich, you can use get_object_by_path (from dulwich.porcelain):
print get_object_by_path(x, "some/file/path", "somebranch").data

In older versions the shortest way to do this is (where x is a repository)::
mode, object_sha = tree_lookup_path(
      x.__getitem__, x['refs/heads/master'].tree, 'some/file/path')
x[object_sha].data


text:
Q: What made Reed Richards elastic in the 2015 Fantastic Four film? In the 2015 Fantastic Four film,

five people are transformed by Planet Zero. We see how four of them are transformed. Von Doom observes that green lava is alive, like neural tissue that makes the planet a sort of organism. Then Von Doom touches the green neural lava and blends with the planet to the point where he can control matter with his thoughts. Then the others gain lesser powers as part of the storm that is provoked in the wake of this. Ben has rocks fall onto him, so he becomes rock. Jonny gets torched, so he becomes flames. And Sue gets hit by electromagnetic energy, so she gains the ability to control electromagnetic energy. ... Each of those four get hit by specific aspects of the planet, and they each become manifestations of the aspect that hit them individually.

But I do not recall seeing Reed during the act of his transformation. Instead, we just see Reed afterwards in the form in which we would expect if we saw any of the other movies.
So what caused Reed to become elastic in the 2015 film?

A: From what I recall, the movie didn't show anything specific happening to Reed to give him the power that he ultimately got. My interpretation is that his change didn't happen until after he was back in our universe:
He was trapped beneath a pile of metal and rubble, but he was desperately trying to reach his friend to see if he was OK. Since he couldn't free his legs, his body responded by stretching out to let him move anyway. Whatever force gave him his power responded to what he was "thinking" at the time.
Also note that Sue didn't get hit by anything from Planet Zero that didn't also hit Reed; she was caught in the backwash of the explosion itself, just like the other three. It's possible that her thoughts at the time (maybe "I shouldn't be here" followed by "I could use a blast shield about now") influenced her power as well.
(Yes, I get it, it's thin; it would have been way better for them to just leave all four powers as being random, but unfortunately they did not.)

A: When Doom fell in the lava, Reed was trying to reach him out.
Perhaps he got that power while trying to catch him, literally stretching his arms.

A: Sues powers came from the energy of planet zero bonding her with the force field of the teleporter, at least that's how I took it...
Reed I have no idea...
I wish the movie would've made a comment that the energy of the planet made their molecular structures unstable, then when they teleported back without the safety measures in place, their molecular structures would've fused with whatever else was in the pods with them.
Johnny with fire, Ben with rocks, Sue with the force field of the teleporter, and because nothing was with Reed his molecules would've stayed in a state of flux (thus stretchy-ness).


text:
Q: Javascript redirect: script in symfony route not working The page I from where I redirect:

            {% if is_granted('ROLE_USER') %}

                {% if app.user.isOwnStar( id ) %}
                    <button class="uk-icon-button uk-icon-star uk-margin-small-right" style="background: #00a8e6;"></button>
                {% else %}
                    <button class="uk-icon-button uk-icon-star uk-margin-small-right" onclick="window.location='{{ path("shot.giveStar",{"id" : id})  }}'"></button>
                {% endif %}

                {% if app.user.isOwnFavorite( id ) %}
                    <button class="uk-icon-button uk-icon-heart uk-margin-small-right" style="background: #d32c46;"></button>
                {% else %}
                    <button class="uk-icon-button uk-icon-heart uk-margin-small-right" onclick="window.location='{{ path("favorite.add",{"id" : id}) }}'"></button>
                {% endif %}

            {% endif %}

This is a image with an anchor and an overlay which containts some links. Because it is impossible to do nested anchors, i setup this links a buttons with javascript redirect.
The main problem is, that the called symfony route's (from the buttons) script is not executed:
public function giveStarAction(Application $app, Request $request, $id)
{
    $msg = $this->shotManager->giveStar($app['user']->getId(),$id);
    $app['session']->getFlashBag()->add('info', $msg );
    exit;
    return $app->redirect( $app->path('shot.view', array('id' => $id) ) );
}

e.g Route for path("shot.giveStar",{"id" : id})
The first three lines were ignored, only the redirect command is executed ...
What do I have to change, that the code is executed before redirect?

A: Its
window.location.href = ''
// or
window.location.replace("")


text:
Q: How to link an SQL Database in Visual Studio to Razor cshtml? I was following this tutorial
https://learn.microsoft.com/en-us/aspnet/web-pages/overview/getting-started/introducing-aspnet-web-pages-2/displaying-data
but I am doing this in Visual Studio instead of WebMatrix since there is no more support for WebMatrix anymore. I tried creating a database within Visual Studio, but I'm not sure how to reference it with C#. Any help would be appreciated.
Also if possible link it to a Microsoft Access database.

A: If your DB is already configured on your project, you must first open the connection in your cshtml header or whatever
var db = Database.Open("DATABASENAME");

The Database must be connected with a few line in the Web.config page (This kind of informationS)
<connectionStrings>
    <add name="DATABASENAME" connectionString="server=Servername;database=DATABASENAME;trusted_connection=True" providerName="System.Data.SqlClient" />
    <add connectionString="Server=.\DATABASE STRING;Database=DATABASENAME;Trusted_Connection=True" name="DATABASE NAME" providerName="System.Data.SqlClient" />
</connectionStrings>


text:
Q: Creating a triangle with for loops I don't seem to be able to find the answer to this-
I need to draw a simple triangle using for loops.
    *
   ***
  *****
 *******
*********

I can make a half triangle, but I don't know how to add to my current loop to form a full triangle.
*
**
***
****
*****

for (int i = 0; i < 6; i++) {
    for (int j = 0; j < i; j++) {
        System.out.print("*");
    }
    System.out.println("");
}

A: I appreciate the OP is new to Java, so methods might be considered "advanced", however I think it's worth using this problem to show how you can attack a problem by breaking it into pieces.
Let's think about writing a method to print a single line, telling the method which number line it is:
public void printTriangleLine(int rowNumber) {
    // we have to work out what to put here
}

We have to print some number of spaces, then some number of stars.
Looking at the example, I can see that (if the first row is 0) it's (5-rowNumber) spaces and (2*rowNumber + 1) stars.
Let's invent a method that prints the rows of characters for us, and use it:
public void printTriangleLine(int rowNumber) {
    printSequence(" ", 5 - rowNumber);
    printSequence("*", 2 * rowNumber + 1);
    System.out.println();
}

That won't compile until we actually write printSequence(), so let's do that:
public void printSequence(String s, int repeats) {
    for(int i=0; i<repeats; i++) {
        System.out.print(s);
    }
}

Now you can test printSequence on its own, and you can test printTriangleLine on its own. For now you can just try it out by calling those methods directly in main()
public static void main(String [] args) {
    printSequence("a",3);
    System.out.println();
    printTriangleLine(2);
}

... run it and verify (with your eyes) that it outputs:
aaa
   *****

When you get further into programming, you'll want to use a unit testing framework like jUnit. Instead of printing, you'd more likely write things like printTriangleLine to return a String (which you'd print from higher up in your program), and you would automate your testing with commands like:
assertEquals("   *****", TriangleDrawer.triangleLine(2));
assertEquals("     *", TriangleDrawer.triangleLine(0))

Now we have the pieces we need to draw a triangle.
public void drawTriangle() {
    for(int i=0; i<5; i++) {
        printTriangleLine(i);
    }
}

The code we have written is a bit longer than the answers other people have given. But we have been able to test each step, and we have methods that we can use again in other problems. In real life, we have to find the right balance between breaking a problem into too many methods, or too few. I tend to prefer lots of really short methods.
For extra credit:

*

*adapt this so that instead of printing to System.out, the methods return a String -- so in your main() you can use System.out.print(drawTriangle())

*adapt this so that you can ask drawTriangle() for different sizes -- that is, you can call drawTriangle(3) or drawTriangle(5)

*make it work for bigger triangles. Hint: you will need to add a new "width" parameter to printTriangleLine().

A: First think of a solution without code. The idea is to print an odd number of *, increasing by line. Then center the * by using spaces. Knowing the max number of * in the last line, will give you the initial number of spaces to center the first *. Now write it in code.

A: A fun, simple solution:
for (int i = 0; i < 5; i++)
  System.out.println("    *********".substring(i, 5 + 2*i));

A: Try this one in Java
for (int i = 6, k = 0; i > 0 && k < 6; i--, k++) {
    for (int j = 0; j < i; j++) {
        System.out.print(" ");
    }
    for (int j = 0; j < k; j++) {
        System.out.print("*");
    }
    for (int j = 1; j < k; j++) {
        System.out.print("*");
    }
    System.out.println();
}

A: First of all, you need to make sure you're producing the correct number of * symbols. We need to produce 1, 3, 5 et cetera instead of 1, 2, 3. This can be fixed by modifying the counter variables:
for (int i=1; i<10; i += 2)
{
    for (int j=0; j<i; j++)
    {
        System.out.print("*");
    }
    System.out.println("");
}

As you can see, this causes i to start at 1 and increase by 2 at each step as long is it is smaller than 10 (i.e., 1, 3, 5, 7, 9). This gives us the correct number of * symbols. We then need to fix the indentation level per line. This can be done as follows:
for (int i=1; i<10; i += 2)
{
    for (int k=0; k < (4 - i / 2); k++)
    {
        System.out.print(" ");
    }
    for (int j=0; j<i; j++)
    {
        System.out.print("*");
    }
    System.out.println("");
}

Before printing the * symbols we print some spaces and the number of spaces varies depending on the line that we are on. That is what the for loop with the k variable is for. We can see that k iterates over the values 4, 3, 2, 1 and 0 when ì is 1,3, 5, 7 and 9. This is what we want because the higher in the triangle we are, the more spaces we need to place. The further we get down the triangle, we less spaces we need and the last line of the triangle does not even need spaces at all.

A: Homework question?
Well you can modify your original 'right triangle' code to generate an inverted 'right triangle' with spaces
So that'll be like
for(i=0; i<6; i++)
{
    for(j=6; j>=(6-i); j--)
    {
        print(" ");
    }
    for(x=0; x<=((2*i)+1); x++)
    {
        print("*");
    }
    print("\n");
}

A:   for (int i=0; i<6; i++)
  {
     for (int k=0; k<6-i; k++)
     {
        System.out.print(" ");
     }
     for (int j=0; j<i*2+1; j++)
     {
        System.out.print("*");
     }
     System.out.println("");
  }

A: This will answer to your question. uncomment the commented code to display only outer line :)
public class TrianglePattern {

    public static void main(String[] args) {
        // This logic will generate the triangle for given dimension
        int dim = 10;
        for (int i = 0; i < dim; i++) {
            for (int k = i; k < dim; k++) {
                System.out.print(" ");
            }
            for (int j = 0; j <= i; j++) {
                //if (i != dim - 1)
                //  if (j == 0 || j == i)
                //      System.out.print("*");
                //  else
                //      System.out.print(" ");
                //else
                    System.out.print("*");
                System.out.print(" ");
            }
            System.out.println("");
        }
    }
}

A: private static void printStar(int x) {
    int i, j;
    for (int y = 0; y < x; y++) { // number of row of '*'

        for (i = y; i < x - 1; i++)
            // number of space each row
            System.out.print(' ');

        for (j = 0; j < y * 2 + 1; j++)
            // number of '*' each row
            System.out.print('*');

        System.out.println();
    }
}

A: This lets you have a little more control and an easier time making it:
public static int biggestoddnum = 31;

public static void main(String[] args) {
    for (int i=1; i<biggestoddnum; i += 2)
    {
        for (int k=0; k < ((biggestoddnum / 2) - i / 2); k++)
        {
            System.out.print(" ");
        }
        for (int j=0; j<i; j++)
        {
            System.out.print("*");
        }
        System.out.println("");
    }
}

Just change public static int biggestoddnum's value to whatever odd number you want it to be, and the for(int k...) has been tested to work.

A: Well, there will be two sequences size-n for spaces and (2*(n+1)) -1 for stars. Here you go.
public static void main(String[] args) {
    String template = "***************************";
    int size = (template.length()/2);
    for(int n=0;n<size;n++){
        System.out.print(template.substring(0,size-n).replace('*',' '));
        System.out.println(template.substring(0,((2*(n+1)) -1)));
    }
}

A: Try this code
class Main{
public static void main (String[] args) {
 //[][][][][][][][][[[[[[[[[][[[[[[[]]]]]]]]]]]]]]
 String s="*";
 String s3="*";
 String s2=" ";
 for (int l=10,ln=0;l!=0 && ln!=10 ;l--,ln++) {
 System.out.println(s2.repeat(l)+s+s3);
  s+="*";
  s3+="*";
 }
 //[][][][][][][][][[[[[[[[[][[[[[[[]]]]]]]]]]]]]]
}
}

AND THIS IS MY OUTPUT>>
~ $ java Main.java
          **
         ****
        ******
       ********
      **********
     ************
    **************
   ****************
  ******************
 ********************
~ $

IN THIS CODE FIRST I HAVE WRITTEN A COMMAND TO MAKE A HALF TRIANGLE AND THEN TO DRAW ANOTHER HALF WHICH MAKE A FULL TRIANGLE.
HOPE IT WILL HELP YOU;

A: Try this
class piramid
{
    public static void main(String[] args)
    {
        //System.out.println("Hello World!");

    int max = 7;
    int k=max/2;
    int j ;
    printf("\n");
    printf("\n");
    printf("\n");
    printf("\n");
    for(i=k;i>0;i--){

          for(j=0;j<k+1;j++){

                if(i==j){

                       printf("*");

                }else if(j>i){
                      printf(" ");
                      printf("*");
                }else {
                      printf(" ");

                }

           }
            printf("\n");

    }

   }

}

hope it will help you


text:
Q: Downloading the content in frames of a document I'm writing an extension for Google Chrome that converts a page to a PDF.
To do this, I download the DOM of the page and pass it to a software that further converts the webpage to a PDF. Since only the DOM is passed, the software downloads the various other resources, like CSS, images, etc.
The software is not allowed to access secured resources, i.e. located at URLs beginning with https://. These resources are downloaded separately in the (NPAPI) DLL that interacts with the JavaScript, by using XMLHttpRequest.
This approach works fine for pages that don't have HTTPS frames. To extend this functionality to work for HTTPS frames, I need to download their DOM, images and CSS, and so on for each nested frame. How do I do this?

A: If you're using a content script to capture the DOM, it should be as easy as injecting the capturing code into all the frames:

chrome.tabs.executeScript(tabId, { code:code, allFrames:true});

Then have the message passing function also pass back window.location and cross-reference that with the src="..." attribute on all the frames.


text:
Q: Correcting dataframe in R I have a dataframe in which some elements of the second column are misplaced . for example :
"15365","JAS ONLINE SERVICES PRIVATE LIMITED"
"15366","KRESS ITALIAN FOOD SPECIALTIES PRIVATE LIMITED"
"15367","SHATAYU CRITICARE HOSPITAL AND RESEARCH CENTER PRI
VATE LIMITED"
"15368","WHITE HEARTS FOODIES PRIVATE LIMITED"
"15369","MAAHI LOGISTICS PRIVATE LIMITED"
...
...

"15376","G S LIFE SKILLS EDUCATION WORLDWIDE PRIVATE LIMITE
D"
"15377","RED LINE LOGISTICS PRIVATE LIMITED"

and so on . Here row 15367 and 15376 need editing . Is there some way to do this without doing it manually ?

A: Simply use the quote parameter of read.table. Suppose you have the string in the variable ds and want to store the resulting data.frame in my.df:
my.df <- read.table(text=ds, sep=",", quote="\"")

If you want to remove the line breaks from the resulting column you can use the following code, just replace replacement with the text you want to replace the linebreaks with and V2 with the column name of your data.frame.
my.df$V2 <- gsub("\\n", replacement, my.df$V2)


text:
Q: Athena SPLIT_PART last element I have no normalised fields in a no-sql json extract queried from ATHENA.
I would like to get the last value of my field.
fields examples:
Raleigh, NC, USA
Frankfurt, Germany

In the idea i would like something like this to select last element:
SPLIT_PART(city, ',' , last_element ) AS country

I don't know if i use the right function to perform this.
Bonus: how to select a field with like value.from without raise sql error ? :)

A: You can use regexp_extract():
select regexp_extract(city, '[^ ,]+$')

This returns the last set of strings in city that do not contain spaces or commas -- the last element you are looking for.

A: If instead of split_part(), you use split() and element_at() functions of AWS Athena combined together, you would get the desired result.
ELEMENT_AT(SPLIT(city, ','),-1) AS country

For further reference on element_at() function follow this doc.
For further reference on split() function follow this doc.