text:
Q: App is crashing when I am opening a basic activity I recently started learning android,and I am using basic activity with a  button 'fab' as default given name.
here is my java file
   public class AddNewMember extends AppCompatActivity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_add_new_member);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);

            FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
            fab.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(AddNewMember.this, HomeScreen.class);
                    startActivity(intent);
                }
            });
        }

    }

the fab button takes user directly to home screen. But the activity crashes saying the following lines
 FATAL EXCEPTION: main
                                             Process: com.adt.alphadev.rotarydist3132, PID: 3361
                                             java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getVisibility()' on a null object reference
                                                 at android.widget.LinearLayout.forceUniformHeight(LinearLayout.java:1380)
                                                 at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1368)
                                                 at android.widget.TableRow.onMeasure(TableRow.java:114)
                                                 at android.view.View.measure(View.java:17547)
                                                 at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
                                                 at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
                                                 at android.widget.TableLayout.measureChildBeforeLayout(TableLayout.java:464)
                                                 at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
                                                 at android.widget.TableLayout.measureVertical(TableLayout.java:476)
                                                 at android.widget.TableLayout.onMeasure(TableLayout.java:439)
                                                 at android.view.View.measure(View.java:17547)
                                                 at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:727)
                                                 at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:463)
                                                 at android.view.View.measure(View.java:17547)
                                                 at android.widget.ScrollView.measureChildWithMargins(ScrollView.java:1260)
                                                 at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
                                                 at android.widget.ScrollView.onMeasure(ScrollView.java:337)
                                                 at android.view.View.measure(View.java:17547)
                                                 at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:727)
                                                 at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:463)
                                                 at android.view.View.measure(View.java:17547)
                                                 at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
                                                 at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:669)
                                                 at android.support.design.widget.HeaderScrollingViewBehavior.onMeasureChild(HeaderScrollingViewBehavior.java:89)
                                                 at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onMeasureChild(AppBarLayout.java:1319)
                                                 at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:734)
                                                 at android.view.View.measure(View.java:17547)
                                                 at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
                                                 at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
                                                 at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
                                                 at android.view.View.measure(View.java:17547)
                                                 at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
                                                 at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
                                                 at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
                                                 at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
                                                 at android.view.View.measure(View.java:17547)
                                                 at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
                                                 at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
                                                 at android.view.View.measure(View.java:17547)
                                                 at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
                                                 at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
                                                 at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
                                                 at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
                                                 at android.view.View.measure(View.java:17547)
                                                 at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
                                                 at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
                                                 at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2615)
                                                 at android.view.View.measure(View.java:17547)
                                                 at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2015)
                                                 at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1173)
                                                 at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1379)
                                                 at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1061)
                                                 at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5885)
                                                 at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
                                                 at android.view.Choreographer.doCallbacks(Choreographer.java:580)
                                                at android.view.Choreographer.doFrame(Choreographer.java

add new member activity
<?xml version="1.0" encoding="utf-8"?>

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

<include layout="@layout/content_add_new_member" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/fab_margin"
    android:src="@mipmap/ic_home_black_24dp" />

Home screen java file
public class HomeScreen extends AppCompatActivity {

ImageButton btn_dashboard, btn_reporting,btn_apply_credits,btn_upload_bulletin,btn_view_rank;
ImageButton btn_add_new_member,btn_update_club_details,btn_view_projects,btn_view_members,btn_view_notifications,btn_change_password,btn_logout;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home_screen);
  btn_add_new_member = (ImageButton)findViewById(R.id.btn_add_new_member);
  btn_add_new_member.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(new Intent(HomeScreen.this, AddNewMember.class));
            startActivity(intent);
        }
    });

  }
}

Please help!


text:
Q: Fail to add Holoeverywhere to Android Studio Library, Error: "hostname in certificate didn't match" I followed the guideline in the github to add Holoeverywhere in Android Studio (Guidelines as follow).
Guidelines

*

*Checkout from Version Control - Git

*Typo in Repository URL: https://github.com/Prototik/HoloEverywhere.git

*Press 'Clone', wait until repository checkout

*If you use Android Studio, then just click 'Yes' on the proposal to open a project. Otherwise in IDEA press Import project and specify path to downloaded repo, choose gradle model and press next.

Everything went fine from Step 1 - 3. Yet for Step 4, after it asks me to open the project and I clicks "yes", an error pops up: "hostname in certificate didn't match" I retried again, yet in vein.
I also searched in google, yet the materials I found does not help.
What should I do? I was stuck....
Thx in advance for any help

A: This is a known issue, the server is down: https://github.com/Prototik/HoloEverywhere/issues/855
Any way, if you are starting a project, please, don't use HoloEverywhere. Use minsdk 14. Or, even better, use Material!

redpajama_set_name: RedPajamaStackExchange


text:
Q: SQL Grand Total Column using Over() I would like to use grand total using over() function however it causes problems when the count() = 0.  It actually adds them to the total.  The real count is 138 not 141.  How can I fix this with keeping the counts() = 0 rows?
select
count(*) cnt,
sum(count(*)) over () grand_total,
count(*)/cast(sum(count(*)) over () as float) percentage
from
some_table

Data (6 rows returned)
4, 141, .03
116, 141, .82
18, 141, .13
0, 141, .01
0, 141, .01
0, 141, .01

A: I like puzzles with only partial information (feels kind of like every day actually), so I'll give this a shot. Ok, over is interesting function because it lets you specify your grouping for an aggregate outside of group by, however you have both kinds of aggregates, an over() aggregate and an aggregate without an over function. I'm going to assume the first column is a count of something (I'll call it sales), and the group is on a category (I'll call it product). With that assumption your sql ends up looking like:
Select ProductID
  , count(1) as UnitsSold
  , sum(count(1)) over () as TotalSales
  , cast(count(1) as money)/cast(sum(count(1)) over () as money)
From SomeTable
group by ProductID

A word to the wise, never ever use float unless you have a mission critical reason to do so, float is an approximation, which can cause all sorts of issues. A quick and dirty replacement I use for percentages is money, defaults to four decimal places, which is more than enough for most business needs for a percentage.
Anyway, continuing my hunch, I'm guessing that we are looking at a left outer join of a products table to a sales table (or some other such many to one relationship), so we have some products without sales that are getting counted, which is why you think the total should be less than you are getting from the count. Just to get that on "paper":
Select a.ProductID
  , count(1) as UnitsSold
  , sum(count(1)) over () as TotalSales
  , cast(count(1) as money)/cast(sum(count(1)) over () as money)
From SomeTable_Products a
  left outer join SomeTable_Sales b
group by a.ProductID

If this is the case, you are not counting the right things is your problem. It can be fixed by changing it to:
Select a.ProductID
  , count(b.SalesID) as UnitsSold
  , sum(count(b.SalesID)) over () as TotalSales
  , cast(count(b.SalesID) as money)/cast(sum(count(b.SalesID)) over () as money)
From SomeTable_Products a
  left outer join SomeTable_Sales b
group by a.ProductID

With b.SalesID being the PK of the sales table (and therefore being unique). Hope I guessed right, and hope that helps.


text:
Q: Error : No resource found that matches the given name (at 'icon' with value '@drawable/icon') Error : No resource found that matches the given name (at 'icon' with value '@drawable/icon').
This is my manifest... I'm extremely new to this, just started this morning and have no previous programming experience.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.asdf"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="19" />

 <application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
 </application>
<application android:label="@string/app_name" android:icon="@drawable/icon">
<activity android:name="ExampleActivity"
          android:label="@string/app_name">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>
</application>

</manifest>

A: If you are 100% sure that directories and files are ok, have a look at the project location.
There is a limit on the path length of files in the Operating System. Perhaps this limit is being exceded in your project files.
Move the project to a shorter folder (say C:/MyProject) and try again!
This was the problem for me!

A: Found this question. I was importing an old project into android studio and got the error.
The issue was eventually answered for me here mipmap drawables for icons
In the manifest it has
<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
...

but @drawable has been superseded by @mipmap so needed changing to:
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
...

I put this answer here, as it may become a more common issue.

A: I've spent on this problem much time and as for me (for Intellij IDEA) the solution is to specify right path to res directory:

*

*right click on project

*click Modules in the left panel

*select Android below your project name

*in Structure tab set right path.

And don't forget to check all the paths in this tab!
I hope it will be helpful for somebody!

A: Remove this line from your manifest:
<application android:label="@string/app_name" android:icon="@drawable/icon">

You have two application tags only one should be present.

A: You need to add icon.png through visual.
Resouces... / Dravable/ Add ///

A: What solved the problem for me was - create a folder "drawable" in "..platforms/android/res/" and put "icon.png" in it.

A: Yet another Googlemare Landmine....
Somehow, if you mess up, the icon line on your .gen file dies. (Empirical proof of mine after struggling 2 hours)
Insert a new icon 72x72 icon on the hdpi folder with a different name from the original, and update the name on the manifest also.
The icon somehow resurrects on the Gen file and voila!! time to move on.

A: This happens when you have previously changed your icon or the ic_launcher; and when that ic_launcher no longer exists in your base folder.
Try adding a png image and giving the same name and then copy it to your drawable folder.Now re build the project.

A: i had this problem. i created a picture for my background with jpg format. before added this picture, i changed the format to png with rename the format. and then i got this error like you. i changed my format picture with picture editor like photoshop to png and replaced it with picture in my project and then i hadnt that error. sory for bad english

A: if cordova app
copy a valid png file to
resources\android\icon.png
and then run
ionic resources --icon

A: In my case, I use Xamarin with Visual Studio 2013. I create Blank App (Android) then deploy without any code update.
You can try:

*

*Make sure that icon.png (or whatever files mentioned in the application android:icon tag) is present in the drawable-hdpi folder inside res folder of Android project.

*If it shows the error even if the icon.png is present,then remove the statement application android:icon from the AndroidManifest.xml and add it again.

*Check your project folder's path. If it is too long, or contains space, or contains any unicode character, try to relocated.

A: Trying to build HelloWorld app on Ubuntu 16.04. Got error with drawable/icon. Solution could be:
cp ./platforms/android/build/intermediates/exploded-aar/com.android.support/design/25.3.1/res/drawable/navigation_empty_icon.xml    ./platforms/android/build/intermediates/exploded-aar/com.android.support/design/25.3.1/res/drawable/icon.xml

So, it look like icon.xml file missed.

A: I also encountered this error. I have a Cordova application and the problem was that in config.xml I had a duplicated element <icon src="icon.png">, one pointing to an non-existing path.

A: There's an even simpler solution - delete the cache folder at user/.android/built-cache and go back to android studio and sync with gradle again, if that still doesn't work delete the cache folder again, and restart android studio and re-import the project


text:
Q: Open-source cross-platform (or MacOSX) tracking software I'm searching for some software (or some simple scripts or even only code snippets) which:

*

*is Open Source

*runs in the background

*collects some information

*

*most importantly location information (e.g. under MacOSX by using the CoreLocation framework)

*IP address

*...

*sends those information via mail or other ways somewhere

*opens a tunnel to localhost by connecting via SSH somewhere

It should be simple because I want to develop my own solution and just use this as a base.
This is intended for the case that my computer gets stolen so that I might be able to track it back (if it doesn't get completely reinstalled).

A: Open source anti-theft solution for Mac, PCs & Phones – Prey
Adeona: A Free, Open Source System for Helping Track and Recover Lost and Stolen Laptops (currently there's only an experimental release for OS X)
(Via iusethis searches for tracking and theft, not actually tested.)

A: Some code from Chrome:

*

*http://src.chromium.org/viewvc/chrome/trunk/src/content/browser/geolocation/

*http://src.chromium.org/viewvc/chrome/trunk/src/chrome/browser/geolocation/


text:
Q: Modify Spring Security Config at Runtime I am using the latest Spring Boot + Spring Boot Starter Security for a simple proxy application.  The goal is to launch the application with a single route/method:
@RequestMapping(value = "/api/register",
    method = RequestMethod.POST,
    produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<?> register(Registration registration) {

With a security configuration of:
@Override
protected void configure(HttpSecurity http) throws Exception {
    this.http = http
        .authorizeRequests()
        .antMatchers("/api/register").hasAuthority(AuthorityConstants.ADMIN)
    .and();
}

public HttpSecurity getHttpSecurity() {
    return http;
}

The goal of the application would be to accept registration requests of the form:
{
    "route":"/api/foo/bar",
    "proxy_location": "http://back-end-server/path/to/resource",
    "role": "some-authority"
}

And then the application would add an /api/foo/bar route with a pre-defined method that will proxy (forward) future requests to the backend service.
I know this is a little goofy, the real use-case involves websockets and dynamic creation of topics.
The issue I'm facing is that I cannot seem to update the security configuration after the SecurityConfigurer has completed.
In the code sample above I am caching the HttpSecurity object given to my SecurityConfigurer and then trying to use that object again to configure a new route:
@Inject
private SecurityConfigurer security;

@RequestMapping(value = "/api/register",
    method = RequestMethod.POST,
    produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<?> allowGetAccounts(Registration registration) {
    try {
        security.getHttpSecurity()
            .authorizeRequests()
            .antMatchers(registration.getRoute()).hasAuthority(registration.getRole());

        ...

    } catch (Exception e) {
        log.error("Updating security failed!", e);
    }

    return new ResponseEntity<>(null, HttpStatus.OK);
}

Is there any way to update the security configuration dynamically during runtime?
Also, if anyone has any notes on creating websocket topics dynamically that would be appreciated too!

A: You have several options:

*

*use antchMatcher("/some/path").access("@someBean.hasAccess(authentication)") . This allows you basically use any bean in your application context to apply the validation you need.

*Use @PreAuthorize("@someBean.hasAccess(authentication)") on you RequestMapping annotated method. Same idea as before but as an interceptor on the endpoint itself.

*Implement your own SecurityExpressionHandler and plug it into http.authorizeRequests().expressionHandler(...).

*Implement your own Security filter that handles whatever you need.


text:
Q: How to fully remove Avast? On windows, I've uninstalled avast via control panel but this popup still appears at the bottom right of my screen after logging in to any user.

I have searched all of my drives for 'avast' and deleted anything with it in its name.  How can I remove this pop up permanently?
UPDATE:
I have used avastclear, ran it in safe mode, and the popup still exists.


text:
Q: Confused about the correct use of in-text citations in essays I want to write a couple of essays on different subjects which I don't know much about, and the first logical thing that comes to mind is that I should do some research on those specific essay-topics before writing.
Now, my question is, when writing, say, about psychology theories or any other types of scientific theories (which, for the most part, are not common knowledge), should I always cite the sources?
I mean, let's say I don't know anything about psychology theories, and I have to explain at least three of them in my essay. So I go and read different psychology articles, magazines, and books, and then, once I finally have a clear idea about these three theories, I proceed to write my essay, which might roughly look like this:
Introduction.
Body:
Paragraph1: According to the behavioral psychology...
Today, behavioral techniques are still widely used in therapeutic settings to help clients learn new skills and behaviors.
Paragraph2: Theories of development provide a...
understanding these theories can provide useful insight into individuals and society.
Paragraph3: Learning theories focus on ...
This is an interdisciplinary topic of interest that often draws upon information from psychology, education, instructional design, and other areas.
Conclusion.
Nevertheless, the problem with following the simple process I've described above is that all the content written in the body of my composition would not be based on my own ideas or experiences, but on all the information, explanations, and definitions I read while doing my research. And I think there's no point in writing an essay if you don't include your own ideas and only write about other people's discoveries and thoughts. However, what else can you do when you are writing about things that have already been explained by experts on the subject you are dealing with? It feels like reinventing the wheel.
It is this feeling of lack of originality that makes me think that I have to add an in-text citation of the sources whithin parentheses at the end of every body paragraph. I feel as if I had to do that in order to avoid plagiarism. For example:
Paragraph1: According to the behavioral psychology...
Today, behavioral techniques are still widely used in therapeutic settings to help clients learn new skills and behaviors. (Williams, 2015)
But then again it wouldn't make sense to write an essay where you have to attach an in-text citation to every paragraph you write lol, plus that there would be not only one source but at least three sources to cite for every paragraph--because when you read extensively on a subject you don't know anything about in order to understand it and be able to compose an essay about it, you are basically summarizing and paraphrasing from different sources--putting together all the information you learned about a specific topic--in your own words of course--to build one strong paragraph. So it is my understanding that, in this case, you also have to add a citation within parentheses acknowledging the sources, right? This is what confuses me.
I might be wrong about how and when to use in-text citations, but I gather that my problem with originality when planning and writing essays, especially scientific ones, stems from the fact that I know I won't be innovating. I will more likely just research the topic and then write about other people's (scientists') ideas, discoveries, and theories.
Maybe I just shouldn't write essays without having original points or ideas about the topic that can be supported with citations of some extra sources. But I don't know, I can't wrap my head around this problem with originality.
So, could you please give me some suggestions on how to go about writing original essays without having to add in-text citations to virtually everything because you feel that everything you know about the topic does not come from you, but from your research/reading of outside sources?

A: You have to cite everything that you take from external resources be it a quote or an idea or even a dictionary definition. If you read an explanation of a theory in a book then you write this in your essay using your own words, you still have to cite it in-text and in the reference page. Otherwise it would be considered plagiarism. So be careful.

A: According to me, citation is only necessary if you are quoting something or writing the exact lines from a book or any other source. If you are reading, researching and writing things in your own words, you don't necessarily need to cite. Citation is also done if you want the reader to refer to a particular book or source for more information.


text:
Q: How to get Ubuntu's latest repositories on elementry OS Luna? I know that ElementryOS luna is based off of the Ubuntu 12.10 LTS, and so the packages are outdated (ex: the sudo apt-get install gimp will get you 2.6 instead of 2.8) so how do i get the latest ubuntu package reposorories, and how do I add them?

A: You shouldn't. Elementary  OS Luna is built on Ubuntu 12.04 LTS, and it is likely to be broken by installing newer packages. There is no guarantee that they will work at all.
As for being outdated, this is not correct. It is true that there are newer packages, however the older ones are still being maintained, which means that fixes are actively being produced and security patches applied for all packages managed by Canonical. After all, this is the meaning of the LTS = Long Term Support expression.
If you still want to try updating you system after this, knowing full well that you might break it badly, you may try adding the following lines to the /etc/apt/sources.list file, adjusting the location as per your needs:
deb http://us.archive.ubuntu.com/ubuntu/ saucy main restricted
deb-src http://us.archive.ubuntu.com/ubuntu/ saucy main restricted

deb http://us.archive.ubuntu.com/ubuntu/ saucy-updates main restricted
deb-src http://us.archive.ubuntu.com/ubuntu/ saucy-updates main restricted

deb http://us.archive.ubuntu.com/ubuntu/ saucy universe
deb-src http://us.archive.ubuntu.com/ubuntu/ saucy universe
deb http://us.archive.ubuntu.com/ubuntu/ saucy-updates universe
deb-src http://us.archive.ubuntu.com/ubuntu/ saucy-updates universe

## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team, and may not be under a free licence. Please satisfy yourself as to
## your rights to use the software. Also, please note that software in
## multiverse WILL NOT receive any review or updates from the Ubuntu
## security team.
deb http://us.archive.ubuntu.com/ubuntu/ saucy multiverse
deb-src http://us.archive.ubuntu.com/ubuntu/ saucy multiverse
deb http://us.archive.ubuntu.com/ubuntu/ saucy-updates multiverse
deb-src http://us.archive.ubuntu.com/ubuntu/ saucy-updates multiverse

## N.B. software from this repository may not have been tested as
## extensively as that contained in the main release, although it includes
## newer versions of some applications which may provide useful features.
## Also, please note that software in backports WILL NOT receive any review
## or updates from the Ubuntu security team.
deb http://us.archive.ubuntu.com/ubuntu/ saucy-backports main restricted universe multiverse
deb-src http://us.archive.ubuntu.com/ubuntu/ saucy-backports main restricted universe multiverse

deb http://security.ubuntu.com/ubuntu/ saucy-security main restricted
deb-src http://security.ubuntu.com/ubuntu/ saucy-security main restricted
deb http://security.ubuntu.com/ubuntu/ saucy-security universe
deb-src http://security.ubuntu.com/ubuntu/ saucy-security universe
deb http://security.ubuntu.com/ubuntu/ saucy-security multiverse
deb-src http://security.ubuntu.com/ubuntu/ saucy-security multiverse

## Uncomment the following two lines to add software from Canonical's
## 'partner' repository.
## This software is not part of Ubuntu, but is offered by Canonical and the
## respective vendors as a service to Ubuntu users.
deb http://archive.canonical.com/ubuntu/ saucy partner
deb-src http://archive.canonical.com/ubuntu/ saucy partner

But remember: you have been warned.


text:
Q: DateFormat DateTime Issue I have a strange issue with my project:
While using the same MSSQL Database, my local version shows date like this:

And my web version shows like this:

Moreover, when I'm trying to edit, in my local version the "datepicker" is populated by my model.date, and on the web version.. not.
 @Html.EditorFor(model => model.StartDate, new { htmlAttributes = new { @class = "form-control" } })\

Here's part of viewmodel:
[DataType(DataType.Date)]
[DisplayName("Data od")]
public DateTime? StartDate { get; set; }

I assume its because of that different Date format. How can I approach this issue?

A: Add new Data Annotation to StartDate property
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]


text:
Q: Issues when storing files in UWP app I'm currently working on an UWP XAML/C# app and I need to store data to my local folder. When executing the Code below I get this error: 'IAsyncAction' does not contain a definition for 'GetAwaiter' and the best extension method overload 'AwaitExtensions.GetAwaiter(Task)' requires a receiver of type 'Task'.
StorageFile file = await localFolder.CreateFileAsync("userInformation.txt", CreationCollisionOption.ReplaceExisting);
await FileIO.WriteTextAsync(file, responseContent.ToString()));

Screenshot
Update: full method
private async void Login()
    {
        StorageFile file = await localFolder.CreateFileAsync("userInformation.txt", CreationCollisionOption.ReplaceExisting);
        await FileIO.WriteTextAsync(file, "sample txt");
    }

A: This code works without any problem:
 StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("userInformation.txt", CreationCollisionOption.ReplaceExisting);
 await FileIO.WriteTextAsync(file, "some text");

As I see there is one extra bracket in your code. Second line should be:
await FileIO.WriteTextAsync(file, responseContent.ToString());


text:
Q: JFreeChart using shifting one series by a given offset value Let's assume that I have one instance of the org.jfree.data.xy.DefaultXYDataset and that I am adding two series to it in this way:
dataset.addSeries(name, values);
dataset.addSeries(name2, values)

How can I move the first or the second series by the X or Y offset value?

Assume that offset is always >= 0. By moving 'right' I mean each (x,y)
  point transform to (x + offset, y) point.

Moving 'left', 'up' and 'down' by analogy.

A: DefaultXYDataset is convenient for accessing individual elements of different series, but it doesn't expose the methods needed to manipulate the internal data structures in this way. Instead, implement the XYDataset interface by extending AbstractXYDataset, as shown here, where you can encapsulate the offset plumbing. You may also want to look at SlidingXYDataset, cited here.


text:
Q: Choosing N and E for Javascript RSA Key Generation using JSBN I'm using the JSBN library found at http://www-cs-students.stanford.edu/~tjw/jsbn/. I'm particularly trying to make the RSASetPublic() call in rsa.js, like this:
publicPem = RSASetPublic(N,E);

For example, when N = "667" and E = "327" I get the alert "Message too long for RSA".
The function is
function RSASetPublic(N,E) {
  if(N != null && E != null && N.length > 0 && E.length > 0) {
    this.n = parseBigInt(N,16);
    this.e = parseInt(E,16);
  }
  else
    alert("Invalid RSA public key");
}

which calls other functions...
function parseBigInt(str,r) {
  return new BigInteger(str,r);
}

function BigInteger(a,b,c) {
  if(a != null)
    if("number" == typeof a) this.fromNumber(a,b,c);
    else if(b == null && "string" != typeof a) this.fromString(a,256);
    else this.fromString(a,b);
}

And the BigInteger fromString() function is...
function bnpFromString(s,b) {
  var k;
  if(b == 16) k = 4;
  else if(b == 8) k = 3;
  else if(b == 256) k = 8; // byte array
  else if(b == 2) k = 1;
  else if(b == 32) k = 5;
  else if(b == 4) k = 2;
  else { this.fromRadix(s,b); return; }
  this.t = 0;
  this.s = 0;
  ....

And then, to use the key that was generated, such as with RSAEncrypt(text), n is important when the text is padded and encrypted...
function RSAEncrypt(text) {
  var m = pkcs1pad2(text,(this.n.bitLength()+7)>>3);
  if(m == null) return null;
  var c = this.doPublic(m);
  if(c == null) return null;
  var h = c.toString(16);
  if((h.length & 1) == 0) return h; else return "0" + h;
}

function pkcs1pad2(s,n) {
  if(n < s.length + 11) { // TODO: fix for utf-8
    alert("Message too long for RSA");
    return null;
  }
  var ba = new Array();
  var i = s.length - 1;
  while(i >= 0 && n > 0) {
     var c = s.charCodeAt(i--);
     if(c < 128) { // encode using utf-8
        ba[--n] = c;
     }
     ....

So I've gathered from various sources the following advice:

*

*N is the modulus, the product of two primes (N=pq) not exceeding k bits in length

*p and q are two large primes?

*N is used to specify the keysize

*Typical bit lengths are k = 1024, 2048, 3072, 4096,...

*choose 2nd argument for parseBigInt from {2,4,8,16,32,256}

*e is the public exponent, a number less than and coprime to (p-1)(q-1)

*Select a value of e from {3, 5, 17, 257, 65537}

Sites like http://asecuritysite.com/encryption/rsa are helpful for high-level understanding of the algorithm but I still don't know how his translates to specific parameter assignments, or what N and E (versus n and e) explicitely mean. So what should N and E be? How do I choose so the message is not "too long for RSA"?

A: Since it's hard to find a 1024-bit number that is the product of two large primes p and q, the solutions I found were:

*

*to download openssl, launch the .exe found in bin, and generate an N value using:
$openssl genrsa -out privatekey.txt 1024
$openssl cat privatekey.txt

*to use the jsbn2.js function RSAGenerate(B,E) passing in B=1024 and E=your public exponent, probably "10001" (base16), so that the modulus is generated for you.
I also noted that jsbn likes its inputs in hex, not decimal, and then converts them to the BigInteger type.


text:
Q: JQuery changing CSS in for loop with timer My question is: what is the most intelligent way to use a for loop which affects CSS via jQuery and a timer together?
Here's a fiddle:
http://jsfiddle.net/j6jLh2dn/
Below is my attempt at implementing a timer which defines a certain amount of time that you can either press the enter key, or not press the enter key, and depending on the situation, it will push a value to an array.
setTimeout(function(){
            if(e.which == 13){
                choice = 1;
            } else {
                choice = 0;
            }

            if(nBack == randomNumber){
                if(choice == 1){
                    correct.push(0);
                } else if(choice == 0){
                    incorrect.push(0);
                }
            } else {
                if(choice == 0){
                    correct.push(0);
                } else if(choice == 1){
                    incorrect.push(0);
                }
            }

        }, 1000 * i * y)();

and here's the portion which should select a certain css id, then edit it based on a random number being chosen:
randomNumber = Math.floor( Math.random() * (m+1) );

            while(randomNumber === history[i-1]){
                randomNumber = Math.floor( Math.random() * (m+1) );
            }

            $("." + randomNumber).css({ "background-color": "#ffe"});

            history[i] = randomNumber;

I have gotten it running without the timer with just alerts, and I have also gotten the timer to work, but upon trying to integrate the two and have it affect CSS, it won't work.

A: Try replacing the code
 $("." + randomNumber).css({ "background-color": "#ffe"});

with
  $("." + randomNumber).css({ "backgroundColor": "#ffe"});

jQuery does not accept "-" when entering css property via object


text:
Q: pip 6.0.6 installs setuptools 0.6rc11 on CentOS 6.3 with Python 2.6.6 installed pip 6.0.6 installs setuptools 0.6rc11 on CentOS 6.3 with Python 2.6.6 installed
pip 1.5.6 installed setuptools 8.2.1
Doing a pip update on setuptools gives the following message
# pip install -U setuptools
Collecting setuptools from https://pypi.python.org/packages/3.4/s/setuptools/setuptools-11.3.1-py2.py3-none-any.whl#md5=59cd761f2f2b926313bed7f83337e4d7
    Using cached setuptools-11.3.1-py2.py3-none-any.whl
Installing collected packages: setuptools
    Found existing installation: setuptools 0.6rc11
    Can't uninstall 'setuptools'. No files were found to uninstall.

Successfully installed setuptools-0.6rc11

I'm using the Chef Community Python Cookbook to install everything and the cookbook hasn't changed since 25-Feb-2014. However the cookbook installs the the latest version of pip and that has been updated recently.
What have I done wrong?
Update:
I found that the /usr/lib/python2.6/site-packages/setuptools-0.6c11-py2.6.egg-info file still existed.
deleting the file resolve the issue, however I would still like to know why the file still existed?

A: Thanks to xavfernandez on github for providing the answer.
The problem is that the version number of setuptools-0.6rc11 doesn't match the filename of the egg file.
Either deleting the egg file for setuptools or renaming the egg file to match the version number will resolve the issue.
If the version number and egg file in /usr/lib/python2.6/site-packages/ don't match pip seems to get lost and upgrades and uninstalls of packages won't work.


text:
Q: Parsing an arrayList I am new to android. How do I parse this array list
{apptName=Ken O'Reily, apptClientId=1056, apptOption1=Option1: Sun 11/26/2017 01:30 PM}

(sent from another activity)?

A: This is not an arraylist, its a Map. You can pass it to second activity by doing this:
Intent i = new Intent(this, SecondActivity.class);
i.putExtra("data" yourData);
startActivity(i);

Then get the data from SecondActivity by doing this...
        HashMap<String, Object> data = (HashMap)getIntent().getSerializable("data");
    String apptName =data.get("apptName").toString();
Log.v("APPT NAME: ", apptName)

Hope it help.


text:
Q: xcode 4.5 takes more than 2 seconds to switch tab I upgraded to XCode 4.5 and when I click on a tab to switch on it it takes more than 2 seconds to switch on it.
Anyone have experienced and solved same issue?

A: Yes, I have experienced exactly the same. On my machine it can take like 3-4 seconds to switch tabs in Xcode.
Luckily the issue goes away by restarting xcode. (A lame work-around, I know, but the only one that I have found so far).

A: Looks like a common issue. https://devforums.apple.com/thread/167765?tstart=0
Bug report has been submitted so hopefully it will be fixed soon.
Edit - Seems to be fixed with XCode 4.5.1


text:
Q: Magento authorize.net direct post checkout does nothing I've setup authorize.net direct post in our Magento website. At then end of checkout when I hit "place order" nothing happens and the text "Submitting order information..." just sits there. I haven't been able to find any solution to this (while the problem seems common).
I tried magento's default theme, blank theme, I tried disabling (in the xml config) all non-magento modules. There are no console errors. I have no clue how to debug this.
Anybody out there seen this problem?

A: I just ran into the same issue with Magento 1.8.0.0
There has been a change in the file
/app/design/frontend/base/default/template/checkout/onepage/review/info.phtml
(lines 79 - 83):
<script type="text/javascript">
//<![CDATA[
    review = new Review('<?php echo $this->getUrl('checkout/onepage/saveOrder', array('form_key' => Mage::getSingleton('core/session')->getFormKey())) ?>', '<?php echo $this->getUrl('checkout/onepage/success') ?>', $('checkout-agreements'));
//]]>
</script>

This is where the form_key hidden field/parameter gets added to the form. In my case I had this file customized and didn't update my copy in
/app/design/frontend/MYTEMPLATEPATH/default/template/checkout/onepage/review/info.phtml
(your 'MYTEMPLATEPATH' may vary)
Once I replaced those lines with the new code from Magento 1.8 everything worked like a charm.

A: I just installed magento 1.8 and have a similar problem I think this problem is because of
    if (!$this->_validateFormKey()) {
        $this->_redirect('*/*');
        return;
    }

in the OnepageController.php in the saveOrderAction() method.
I think I found a solution, add this line
   $this->getRequest()->setParam('form_key', Mage::getSingleton('core/session')->getFormKey());

copy the file /app/code/core/Mage/Authorizenet/controllers/Directpost/PaymentController.php
to /app/code/local/Mage/Authorizenet/controllers/Directpost/PaymentController.php
and edit the method placeAction, after line 142
    $this->_getDirectPostSession()->setQuoteId($this->_getCheckout()->getQuote()->getId());

add this line:
    $this->getRequest()->setParam('form_key', Mage::getSingleton('core/session')->getFormKey());


text:
Q: Code first: Where's the connection string & the Database? I'm testing how code first works. Here's how I defined the Context
public class EfDbContext: Context
{
  public DbSet<Client> Clients { get; set; }
}

I didn't create any data base, but I was able to do all the CRUD operations.
Now I don't see the connection string in my web.config. I don't see either the Database. I've checked the App_Data Directory and also the Sql Server Express. I don't see any trace of the Database created.
Yet, everything is perfectly.

A: EF code-first will use a connection string that has the same name as your DB context - so you could define it like this:
<connectionString>
   <add name="EfDbContext"
        connectionString="server=YourServer;database=YourChoice;Integrated Security=SSPI;" />
</connectionString>

The database won't be created by default, until you actually do something, e.g. it should show up as soon as you make a call to EfDbContext.SaveChanges() for the first time.
It will be called the same as your DB context (YourNamespace.EfDbContext) if you haven't defined your own, custom connection string, and it should show up in your default local SQL instance.
See from the ADO.NET EF 4.1 Code First Walkthrough:

Where's My Data?
DbContext by convention created a database for you on
  localhost\SQLEXPRESS. The database is named after the fully qualified
  name of your derived context, in our case that is
  "CodeFirstSample.ProductContext". We'll look at ways to change this
  later in the walkthrough.


text:
Q: Using this in statics functions I want to do something like this:
var Component = React.createClass({
   getInitialState: function () {
      return {
         message: ''
      }
   },
   statics: {
      action: function (msg) {
         this.setState({
            message: msg
         });
         this.forceUpdate();
      }
   },
   render: function () {
      // ...
   }
});

But I can't access this object of the react class from statics functions. How could I do this?


text:
Q: python idle offline installer Ubuntu 12.04 LTS.
Surprisingly, IDLE is not included by default.
Python is there.
I prefer to download tar.gz or .deb installer for IDLE.
Googled to look for it, but could not find.
Where can I get the installer for IDLE?
Thanks,
Vineet

A: There are two versions of IDLE in the repositories in 12.04
For Python 2.7 sudo apt-get install idle-python2.7
For Python 3.2 sudo apt-get install idle-python3.2
And two In 13.04
For Python 2.7 sudo apt-get install idle-python2.7
For Python 3.3 sudo apt-get install idle-python3.3
In a terminal CTRL+ALT+T


text:
Q: Setting up OrientDB server clusters on OpenShift I am trying to set up an OrientDB server cluster, where multiple pods have their own orientDB server, and they all contain the same data, no matter which pod's database you modify.
When I set this up locally, I can just start up multiple containers that run OrientDB's dserver.sh, and OrientDB's multicast ability allows the different containers/servers to find themselves. However when I'm running multiple instances on different pods they can't find themselves.
I'm currently thinking I'm supposed to have the pods on the same kubernetes service, and then they should be able to do the same? But I'm not making any headway.
How do I get multiple pods on OpenShift all to connect to each other, as if I was doing this with different containers on my local machine?
Thanks.

A: You can get multicast support in your cluster using Weave network solution.

Summary
With multicast, data can be distributed to multiple receivers that are in the same multicast group. It is used by
applications that generate and distribute data feeds to other
applications such as financial services.
Weave Net fully emulates a layer 2 network, and operates just like a
server that is attached to a standard Ethernet network. Multicast with
Weave Net works even if the underlying network doesn't support it,
which is the case with Amazon Web Services (AWS), Azure, GCP and other
public clouds.
What it Does

*

*Provides full multicast support for contained and uncontained applications

*Works in data centers and public clouds, regardless of the underlying network

*Uses industry-standard VXLAN and in-kernel switching for top performance

*Automatic service discovery through DNS lookups


text:
Q: Can I used simple sql commands in django I want to select data from multiple tables, so i just want to know that can i used simple SQL queries for that, If yes then please give me an example(means where to use these queries and how).
Thanks.

A: Refer django documentation
Making queries
Perform Raw SQL queries

A: Try this.
https://docs.djangoproject.com/en/dev/topics/db/sql/


text:
Q: How to monitoring a process on android Does someone know if it is possible to dump all writes of a process does in the fileystem in android? Or at least the path where the process writes?
I would like to monitor my application. I see the dalvik machine use netlink class to comunicate with kernel, should I edit that or something else?

A: If you are using Android Lollipop you can use the API App Usage Statistics. For pre-lollipop devices you can use getRecentTasks() from ActivityManager


text:
Q: How to properly return value from a data inside the function Im new to javascript and started to learn amazing stuff from it. As the code below how can I be able to return the value of index inside getData().then(data => {. getData function has json response values.
subPatternStart() {
  getData().then(data => {
    var patternStart = 1525750500000;
    var index = 0;

    for (var i = 0; i < data.length; i++) {
      if ( patternStart >= data[i].time && patternStart < data[i+1].time ) {
        //...somecode
      }
    }
    console.log("Index:" , index);
  })
}

What I want to achieve is that when I call this function I should ONLY get the value of index, which in this case the console log value is equivalent into 1.
I have this in my render method.
render() {
  index={this.subPatternStart()}
}

In this simple code, it returns the exact value in the render method, and I want to do something like this.
subPatternStart() {
  var patternStart = 1;
  return patternStart;
}

A: You should set the state of the component with the value you get from getData. Then React can update it self and render the page. For example
import React from 'react';

class App extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      index: 0
    }
  }

  subPatternStart() {
    getData().then(data => {
      var patternStart = 1525750500000;
      var index = 0;

      for (var i = 0; i < data.length; i++) {
        if (patternStart >= data[i].time && patternStart < data[i + 1].time) {
          //...somecode
        }
      }
      this.setState({
        index: index
      });
    })
  }
  render() {
    index =  this.state.index
  }
}

A: the function subPatternStart calls an async function getData so you need to use either callback or promises to get data in return.
1. Using Callbacks
subPatternStart(callbackFunction) {
        getData().then(data => {
            var patternStart = 1525750500000;
            var index = 0;

            for (var i = 0; i < data.length; i++) {
                if (patternStart >= data[i].time && patternStart < data[i + 1].time) {
                    //...somecode
                }
            }
            console.log("Index:", index);
            callbackFunction(index);
        })
    }

// calling the function
render() {
    var index;
    this.subPatternStart((i) => { index = i })
}

2. Using Promises
subPatternStart(callbackFunction) {
    var promise = new Promise(resolve => {
        getData().then(data => {
            var patternStart = 1525750500000;
            var index = 0;

            for (var i = 0; i < data.length; i++) {
                if (patternStart >= data[i].time && patternStart < data[i + 1].time) {
                    //...somecode
                }
            }
            console.log("Index:", index);
            resolve(index);
        })
    })
    return promise;
}

// calling the function
async render() {
    index = await this.subPatternStart();
}


text:
Q: how to list "shared with me" items via new OneDrive api? I need to connect to OneDrive and fetch the list of shared files on the same for a given account.
Looking forward for help.

A: You can get this list of objects using the REST API, details here: http://msdn.microsoft.com/en-us/library/dn659731.aspx#get_a_list_of_onedrive_objects_that_are_shared_with_the_signed-in_user.

To discover all OneDrive objects that are shared with the signed-in user, use the wl.contacts_skydrive scope to make a GET request to /USER_ID/skydrive/shared, where USER_ID is either me or the user ID of the sharing user. The sharing user must be one of the signed-in user's contacts, who has shared their OneDrive objects with the user. Here's an example:

GET https://apis.live.net/v5.0/me/skydrive/shared?access_token=ACCESS_TOKEN


text:
Q: Spring configuration file in web.xml I'm loading my spring configuration file in web.xml file. The spring file contains many beans. How can I get the bean name in my class. Is their any way to get the bean name without providing the path name.
web.xml
<context-param>
<param-name>configDir</param-name>
<param-value>D:/akatte/config</param-value>
</context-param>
<context-param>
<param-name>springConfig</param-name>
<param-value>spring-config.xml</param-value>
</context-param>

spring-config.xml
<bean id="foNasShare" class="com.katte.galaxe.FoNas">
<property name="fname" value="arvind"/>
<property name="lname" value="katte"/>
</bean>

Pojo class
FoNas.java
class FoNas
{
//getter and setter
}

Now tell me how can I access the bean name (context.getBean("foNasShare")) in my class. spring-config.xml file is already loaded in web.xml, i don't want to load the xml file one more time. The problem is spring bean is loading but the value of the getter and setter are setting to null.


text:
Q: How to show records from three tables without foreach I have problem how to make query to join records from 3 tables and print results on screen. I made solution but isn't good for speed and I have been seeking for better solution. My tables are:
test table
id_test
testName

question table
id_quest
id_test
question

answer table
id_answer
id_quest
answer

Every test has 7 questions and every question has 10 answers.
How to write database query without foreach to list this records on screen?
I made solution like this:
    $this->db->select('id_test,testName,description,time,type,sum');
    $this->db->where('id_test',$idTest);
    $query['test'] = $this->db->get('tests')->result()[0];

    $this->db->select('id_quest,inquiry');
    $this->db->where('id_test',$idTest);
    $query['questions'] = $this->db->get('questions')->result();

    $i=0;
    foreach ($query['questions'] as $question) {
        $this->db->select('id_answer,response,value');
        $this->db->where('id_quest',$question->id_quest);
        $query['questions'][$i]->answer = $this->db->get('answer')->result();
        $i++;
    }
    return $query;

A: You can make a more complex query like this so that you only have to hit the database once:
SELECT
t.id_test, t.testName, t.description, t.time, t.type, t.sum,
q.id_quest, q.inquiry,
a.id_answer, a.response, a.value
FROM tests AS t
LEFT JOIN questions AS q ON q.id_test = t.id_test
LEFT JOIN answers AS a ON a.id_quest = q.id_quest
WHERE t.id_test = $idTest;

Then your code will look something like this:
<?php
// your database info here
$db_host = '';
$db_user = '';
$db_pass = '';
$db_name = '';

$con = mysqli_connect($db_host,$db_user,$db_pass,$db_name);
if($con->connect_error)
    die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());

$query = "SELECT
t.id_test, t.testName, t.description, t.time, t.type, t.sum,
q.id_quest, q.inquiry,
a.id_answer, a.response, a.value
FROM tests AS t
LEFT JOIN questions AS q ON q.id_test = t.id_test
LEFT JOIN answers AS a ON a.id_quest = q.id_quest
WHERE t.id_test = ?";

if (!$stmt = $con->prepare($query))
    die('Prepare Error: ' . $con->error);

$idTest = 2;
if (!$stmt->bind_param('i', $idTest))
    die('Bind Parameters Error ' . $stmt->error);

if (!$stmt->execute())
    die('Select Query Error ' . $stmt->error);

while ($stmt->fetch())
{
// get each resulting answer row, complete with associated question id and test id
}
$stmt->close();
$con->close();

A: From what I get of your question you're looking to join the tables. I think you should be able to do something like this:
SELECT test_table.test_name,
       qestion_table.question,
       answer_table.answers
FROM test_table
INNER JOIN questions_table
on questions_table.id_test = test_table.id_test
INNER JOIN answers_table
ON answers_table.id_quest = questions_table.id_quest
WHERE test_table.id_test = ?

This should return the entire result set as one object rather than having to query the db several times.

A: I would totally look into using 'where_in' instead of throwing tons of queries at you database.
i.e..
//...

$this->db->select('id_quest,inquiry');
$this->db->where('id_test',$idTest);
$query['questions'] = $this->db->get('questions')->result();

$questionIds = array();

foreach($query['questions'] as $question)
     $questionIds[] = $question->id_quest;

$this->db->select('id_answer,response,value');
$this->db->where_in('id_quest', $questionIds);
$answers = $this->db->get('answer')->result();

$i=0; // <<< Idk what the main purpose of this is,
      //     but you do know you can simply use '[]' appending to an array, right?
foreach ($answers as $answer) {
    $query['questions'][$i]->answer = $answer;
    $i++;
}

Also if performance is still a major issue. Look into caching. CodeIgniter supports this very well.
https://www.codeigniter.com/userguide3/libraries/caching.html
P.S Also look into the join command in CI.
https://www.codeigniter.com/userguide2/database/active_record.html


text:
Q: Make the bootstrap carousel non-responsive My ui-bootstarp carousel (here) is inside a Flexbox.
I need to make the carousel non-responsive, so it wont get smaller in a smaller screen and the flexbox will react normally and its items will go one underneath each other.
Check the image to help you.
How do I make the carousel non-responsive?
Thanks

A: Try adding this to your css:
.owl-item{
float:none !important;
}

Don't know if it works


text:
Q: Java Lambda for break inside two for loops I am trying to convert an iterative block of code in Java 8 to functional. The functional approach is unable to find the matching message in the set shared.
List<Optional<Message>> allMessages = new ArrayList<>();

Set<Status> allStatuses = getAllStatuses();

//Iterative : Working
Set<StatusMessage> set = new HashSet<>(STATUS_MESSAGE.values());
for (StatusMessage statusMessage : set) {
    for (Status status : statusMessage.getStatusAndInfo().keySet()) {
        Optional<Message> message = MessageBuilder.createMessage(allStatuses, status, this::createMessage);
        if (message.isPresent()) {
            allMessages.add(message);
            break;
        }
    }
}

//Functional : Not working  - Never adds anything to the
//map even when matching status is present
STATUS_MESSAGE.values().stream()
        .distinct()
        .map(statusMessage -> statusMessage.getStatusAndInfo().keySet())
        .flatMap(Collection::stream)
        .map(key -> MessageBuilder.createMessage(allStatuses, key, this::createMessage))
        .anyMatch(allMessages::add);

The MessageBuilder.createMessage looks like this:
Optional<Status> matchingStatus = statuses.stream()
                .filter(matchingStatus::equals)
                .findFirst();
System.out.println("Found : " + matchingStatus.toString());
return matchingStatus.flatMap(creator);

Also, for debugging purposes, how can I see what is happening at each step of the stream? The stack in the debugger in intellij wasn't showing anything in the stream.

A: This should do it:
STATUS_MESSAGE.values().stream()
        .distinct()
        .forEach(statusMessage ->
            statusMessage.getStatusAndInfo().keySet().stream()
                    .map(status -> MessageBuilder.createMessage(allStatuses, status, this::createMessage))
                    .filter(Optional::isPresent)
                    .findFirst()
                    .ifPresent(allMessages::add)
        );

UPDATE
To build the result list using toList instead of adding to a list:
List<Optional<Message>> allMessages = STATUS_MESSAGE.values().stream()
        .distinct()
        .flatMap(statusMessage ->
            statusMessage.getStatusAndInfo().keySet().stream()
                    .map(status -> MessageBuilder.createMessage(allStatuses, status, this::createMessage))
                    .filter(Optional::isPresent)
                    .limit(1)
        )
        .collect(Collectors.toList());

A: This should be a comment, but it's too long...

Seems like your MessageBuilder.createMessage method is overcomplicated.
Check below a simplified and more readable version of the same logic:
if (allStatuses.contains(status)) {
    System.out.println("Found : " + status.toString());
    return creator.apply(status);
}
return Optional.empty();

A: You should not use forEach for accumulating operations, so this should be more idiomatic:
Function<StatusInfo, Optional<Message>> messageForStatus = statusInfo ->
        statusInfo().keySet().stream()
                    .map(status -> MessageBuilder.createMessage(allStatuses, status, this::createMessage))
                    .filter(Optional::isPresent)
                    .findFirst()
                    .orElse(Optional.empty());

allMessages = STATUS_MESSAGE.values().stream()
        .distinct()
        .map(StatusMessage::getStatusAndInfo)
        .map(messageForStatus)
        .filter(Optional::isPresent)
        .collect(toList());

As a side note, you have too many optionals, you may want to consider unwrapping some earlier, as a list of optionals may just as well be the list of only the present values.


text:
Q: Gulp concat plugins error I'm using gulp for concat my plugins (bootstrap, jquery, etc) in one big file, this is my code:
const gulp = require('gulp');
const csso = require('gulp-csso');
const concat = require('gulp-concat');
const babel = require('gulp-babel');
const uglify = require('gulp-uglify');

gulp.task('build', function() {

gulp.src(["./bower_components/bootstrap/dist/css/bootstrap.min.css",
         "./bower_components/ekko-lightbox/dist/ekko-lightbox.css",
         "./bower_components/owl.carousel/dist/assets/owl.carousel.min.css",
         "./bower_components/owl.carousel/dist/assets/owl.theme.default.css",
         "./client/css/core.css",
         "./client/css/responsive.css"])
.pipe(csso())
.pipe(concat("main.css"))
.pipe(gulp.dest("./build"));

gulp.src(["./bower_components/jquery/dist/jquery.js",
          "./bower_components/bootstrap/dist/js/bootstrap.bundle.js",
          "./bower_components/ekko-lightbox/dist/ekko-lightbox.min.js",
          "./bower_components/lazysizes/lazysizes.min.js",
          "./bower_components/owl.carousel/dist/owl.carousel.min.js",
          "./bower_components/moment/min/moment.min.js",
          "./bower_components/moment/min/locales.min.js",
          "./client/js/script.js" ])
.pipe(babel({
        presets: ['es2015']
    }))
.pipe(uglify())
.pipe(concat("main.js"))
.pipe(gulp.dest('./build'));

});

And it's doing OK. But when i'm including this script on my project, console throws my error: Uncaught TypeError: Cannot set property 'bootstrap' of undefined.
I tried just concat it without es2015 or uglify, but this error (or another, like moment is not defined) still persists. What am i doing wrong?

A: Ok, i got it.
npm install --save-dev babel-plugin-proposal-object-rest-spread
npm install --save-dev babel-plugin-transform-object-rest-spread

Then pipe
.pipe(babel({
    presets: [['env', {
        loose: true,
        modules: false,
        exclude: ['transform-es2015-typeof-symbol']
    }]],
    plugins: ['transform-es2015-modules-strip', 'transform-object-rest-spread']
}))

And it works


text:
Q: Python selenium Access Denied when clicking buttons I've been using selenium for a while now and today I've come across an issue I was hoping someone could help me out with.
I use this code to access the page I want to go to...
user_agent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.50 Safari/537.36'
options = selenium.webdriver.ChromeOptions()
options.add_argument('user-agent={0}'.format(user_agent))
...
driver = webdriver.Chrome(driverpath,chrome_options=options)
driver.get(url)

This works fine, however, when I attempt to click on a button that will take me to another page or load some content, I get taken to an Access Denied page.
button = driver.find_element_by_class_name('abutton')
button.click()

I was wondering if this could possibly be because the browser "forgets" my user-agent?
This is my current theory as I get the exact same Access Denied page when I do not include my user-agent.


text:
Q: como mostrar solo datos True en un foreign key de python models.py:
class Article(models.Model):
    ...
    user_create = models.ForeignKey(User, null=True, related_name = 'user_create')

upd.html:

...
Creador

    {{ form.user_create }}
    {{ form.user_create.errors }}

views.py:

...
form = ArticleForm(request.POST, instance=articulo)


text:
Q: Custom SQL Server performance counters I need to create several counters for a system health check and monitoring. Since there are numerous tools for logging, reporting and alerting Windows Perfmon data, I am looking to publish that data as Perfmon counters.
Some of the values need to come from a SQL Server 2008 database, examples of such are the number of records in a table used as a queue, and the age of the oldest record in the table.  While it looks like this can be accomplished by using a SQL Server, User Settable Object and the stored procedures sp_user_counter1 to sp_user_counter10 this limits me to only 10 counters per server and the counter names and descriptions cannot be customized to reflect what the counter is.
Without creating our own application to create the Perfmon counters,  are there any other ways to create counters in SQL Server?  If not, are there any tools/projects that allow for the creation of custom counters using SQL queries?

A: Late answer - but can be useful to other thread visitors
Besides other mentioned solutions, I can suggest a 3rd party tool called ApexSQL Monitor. It allows the creation of custom SQL performance counters for specific configuration of system on-demand monitoring, historical trending and alerting.
Custom metrics are T-SQL based queries that can be added to this tool. The data collected by those queries can be analyzed and alerted on, just like other built-in metrics.
The following article provides examples of custom SQL performance counters that may be useful: http://solutioncenter.apexsql.com/using-custom-sql-performance-counters-to-monitor-sql-server/

A: I think the only way to specifically use SQL server for the custom perfmon data is to use the ten sp_user_counterX stored procs. I did a bit of searching and the only results that came up in my searching were these stored procs.
I do have another suggestion though which requires a bit of coding. This article explains how to create a small application (be it service or console app) that allows you to create as many of your own performance counters as you like. You could use this to create your own counters.
In our organisation we use Idera Diagnostic Manager which we find very useful as we can use the built in metrics to monitor our servers as well as create our own counters. We find that it works very well and although it has quite a hefty price, it is the only monitoring tool that I know of that does not require any sort of agents on the SQL server.

A: If you look at the source for the stored procedures, you get:
ALTER procedure [sys].[sp_user_counter2] @newvalue int as
dbcc setinstance ('SQLServer:User Settable', 'Query', 'User counter 2', @newvalue)

=> you can try and call dbcc setinstance with your own counter name

A: This can be done with the undocumented DBCC commands:
To create a new metric:
dbcc addinstance ('SQLServer:User Settable', 'MyNewCounter')

To change its value:
dbcc setinstance ('SQLServer:User Settable', 'Query', 'MyNewCounter', 5)

To delete:
dbcc deleteinstance ('SQLServer:User Settable', 'MyNewCounter')


text:
Q: Interpreting this line in Assembly language? Below are the first 5 lines of a disassembled C program that I am trying to reverse engineer back into it's C code for purposes of better learning assembly language. At the beginning of this code I see it makes room on the stack and immediately calls
0x000000000040054e <+8>:    mov    %fs:0x28,%rax

I am confused what this line does, and what might be calling this from the corresponding C program. The only time I have seen this line so far is when a different method within a C program is called, but this time it is not followed by any Callq instructions so I am not so sure... Any ideas what else could be in this C program to be making this call?
0x0000000000400546 <+0>:    push   %rbp
0x0000000000400547 <+1>:    mov    %rsp,%rbp
0x000000000040054a <+4>:    sub    $0x40,%rsp
0x000000000040054e <+8>:    mov    %fs:0x28,%rax
0x0000000000400557 <+17>:   mov    %rax,-0x8(%rbp)
0x000000000040055b <+21>:   xor    %eax,%eax
0x000000000040055d <+23>:   movl   $0x17,-0x30(%rbp)
...

I know this is to provide some form of stack protection for buffer overflow attacks, I just need to know what C code would prompt this protection if not for a seperate method.

A: As you say, this is code used to defend against buffer overflows.  The compiler generates this "stack canary check" for functions that have local variables that might be buffers that could be overflowed.  Note the instructions immediately above and below the line you are asking about:
sub  $0x40, %rsp
mov  %fs:0x28, %rax
mov  %rax, -0x8(%ebp)
xor  %eax, %eax

The sub allocates 64 bytes of space on the stack, which is enough room for at least one small array.  Then a secret value is copied from %fs:0x28 to the top of that space, just below the previous frame pointer and the return address, and then it is erased from the register file.
The body of the function does something with arrays; if it writes sufficiently far past the end of an array, it will overwrite the secret value. At the end of the function, there will be code along the lines of
    mov    -0x8(%rbp), %rax
    xor    %fs:28, %rax
    jne    1
    mov    %rbp, %rsp
    pop    %rbp
    ret
1:
    call    __stack_chk_fail   # does not return

This verifies that the secret value is unchanged, and crashes the program if it has changed.  The idea is that someone trying to exploit a simple buffer overflow vulnerability, like you have when you use gets, won't be able to change the return address without also modifying the secret value.
The compiler has several different heuristics, selectable with command line options, for deciding when it is necessary to generate stack-canary protection code.
You can't write C code corresponding to this assembly language yourself, because it uses the unusual %fs:nnnn addressing mode; the stack-canary code intentionally uses an addressing mode that no other code generation relies on, to make it as difficult as possible for the adversary to learn the secret value.


text:
Q: How do I get lombok to work with Visual Studio Code? I have a java gradle project in vscode, and I followed the instructions on the site to use the gradle plugin and the vscode lombok extension. However, vscode is still unable to resolve the lombok.Data java import. What am I missing?

A: Use next plugin Lombok Annotations Support for VS Code

A: Turns out I had to run the following command in VS Code:
> Java: Clean the Java language server workspace

A: Try to exclude transitive dependency for better control
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
  <exclusions>
    <exclusion>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-logging</artifactId>
    </exclusion>
  </exclusions>
</dependency>

I am using VScode editor try to add lombok for from the extension window. After that clean the workspace it worked for me.


text:
Q: Xml, datatable, and variables - beginner questions I have a project that has to export variables and fixed values into a xml file.
The idea is to save the work done, and load it again later.
Please be aware i just beginned to study c#, so shortened explanations will be hard to understand (i've been reading about other issues as well)
In some links i've read that such this is easy when you create datatables, but on the examples i've read they only talk about fixed values, and as far as i've seen, they required the table to be created in the form (wich is not the objective).
I've tried to place a code i've found around
DataTable table = new DataTable();
table.Columns.Add("Dosage", typeof(int));
table.Columns.Add("Drug", typeof(string));
table.Columns.Add("Patient", typeof(string));
table.Columns.Add("Date", typeof(DateTime));

table.Rows.Add(25, "Indocin", "David", DateTime.Now);
table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);

It's pretty neat, but, can i visualy see the table somewhere? or it's like a console list?
Can i use variables, and will it update the matrix when the program changes the variable values?
Will the table be acessible in all the forms i create in the project? Or should i create her in a separate class and make it public?
How recommended is this process when the main objective is export / import data trough xml files?
edit: i will also have to add information about checkboxes, dropdown lists, etc, not only variables, so i'm wondering if datatables are really the best way to export/import xml.

A: You can convert a DataTable into XML Like this:
string fileName =myAppPath + @"\sample.xml";

DataTable table = new DataTable();
... //your code goes here...
table.WriteXml(fileName,  XmlWriteMode.WriteSchema);

And read it like this:
string fileName =myAppPath + @"\sample.xml";
DataTable newTable = new DataTable();
newTable.ReadXml(fileName);

Regarding:
Can I use variables, and will it update the matrix when the program changes the variable values?
As for variables I guess your mean memory. And the Your DataTable is a variable and it will hold everything in memory until your write it to the file.
If on the other hand you mean binding the values on the table to a control, well that would depend on the type of of technologies you are using.
Will the table be accessible in all the forms I create in the project?
Variables only exists within an scope and by scope to simplify I mean any two curly brackets "{}". In web applications(ASP.NET) for example you can use something called "session' to share data across forms and of course there are way to work this arounds in most technologies but your post does not specify it.


text:
Q: Handling ajax-request in leaflet map I have a very basic leaflet map using leaflet-panel-layers to create a pretty layer control. I have two functions to create my layers and overlays. My data is in external geoJSON-Files what seems to be my problem as leaflet does not offer anything to get an external geoJSON. I also use proj4leaflet library to use the projection given in my json.
So google told me to use ajax about which I unfortunately don't know anything. I copy-pasted something like this:
function getOverlays(){
    var url = 'myServerUrl';
    overlays = [];

    $.ajax({
        url: url,
        dataType: 'jsonp',
        jsonpCallback: 'getJson',
        success: function(response) {
            overlays.push({
                name: "Something",
                layer: L.Proj.geoJson(response, {
                ...
                }
            });
        }
    });
    return overlays;
}

my map is built like this:
var map = L.map('map', {
    layers: layers[0].layer
});
var layers = getBaseLayers();
var overlays = getOverlays();
var panelLayers = new L.Control.PanelLayers(layers,overlays);
map.addControl(panelLayers);

This actually works fine if I want to add the layers to the map directly. But in my case the asynchronous request seems to be ready after my layer switcher is added to my map so the layers don't appear there.
Is there any way to solve this simply without diving into callbacks?

A: Add your control after request has finished. This can be done with a callback function:
function getOverlays(callback){
    var url = 'myServerUrl';
    overlays = [];

    $.ajax({
        url: url,
        dataType: 'jsonp',
        jsonpCallback: 'getJson',
        success: function(response) {
            overlays.push({
                name: "Something",
                layer: L.Proj.geoJson(response, {
                ...
                }
            });
            callback(overlays)
        }
    });
    return overlays;
}

var map = L.map('map', {
    layers: layers[0].layer
});
var layers = getBaseLayers();
getOverlays(function(overlays){
    var panelLayers = new L.Control.PanelLayers(layers,overlays);
    map.addControl(panelLayers);
});


text:
Q: How do I preserve line breaks when getting text from a textarea? I am getting the value in a textarea when the user hits submit. I then take this value and place it elsewhere on the page. However, when I do this, it loses newline characters making the output pretty ugly.
Here is the textarea I am accessing:
<textarea id="post-text" class="form-control" rows="3" placeholder="What's up?" required></textarea>

Here is the JavaScript code accessing the post and transcribing it.
var post = document.createElement('p');
var postText = document.getElementById('post-text').value;
post.append(postText);
var card = document.createElement('div');
card.append(post);
var cardStack = document.getElementById('#card-stack');
cardStack.prepend(card);

When the input is something like:

Group Schedule:
Tuesday practice @ 5th floor (8 pm - 11 pm)
Thursday practice @ 5th floor (8 pm - 11 pm)
Sunday practice @ (9 pm - 12 am)

The output is:

Group Schedule: Tuesday practice @ 5th floor (8 pm - 11 pm) Thursday practice @ 5th floor (8 pm - 11 pm) Sunday practice @ (9 pm - 12 am)

So is there a way to preserve line breaks?

A:

function get() {
  var arrayOfRows = document.getElementById("ta").value.split("\n");
  var docfrag = document.createDocumentFragment();

  var p = document.getElementById("result");
  while (p.firstChild) {
    p.removeChild(p.firstChild);
  }

  arrayOfRows.forEach(function(row, index, array) {
    var span = document.createElement("span");
    span.textContent = row;
    docfrag.appendChild(span);
    if(index < array.length - 1) {
      docfrag.appendChild(document.createElement("br"));
    }
  });

  p.appendChild(docfrag);
}
<textarea id="ta" rows=3></textarea>

<button onclick="get()">get</button>

You can split textarea rows into array:
var arrayOfRows = postText.value.split("\n");

Then use it to generate, maybe, more p tags...

A: Here is an idea as you may have multiple newline in a textbox:
 var text=document.getElementById('post-text').value.split('\n');
 var html = text.join('
');

This HTML value will preserve newline. Hope this helps.

A: Similar questions are here
detect line breaks in a text area input
detect line break in textarea
You can try this:

var submit = document.getElementById('submit');

submit.addEventListener('click', function(){
var textContent = document.querySelector('textarea').value;

document.getElementById('output').innerHTML = textContent.replace(/\n/g, '
');

});
<textarea cols=30 rows=10 >This is some text
this is another text

Another text again and again</textarea>
<input type='submit' id='submit'>

document.querySelector('textarea').value; will get the text content of the
textarea and textContent.replace(/\n/g, '
') will find all the newline character in the source code /\n/g in the content and replace it with the html line-break
.

Another option is to use the html
 tag. See the demo below

var submit = document.getElementById('submit');

submit.addEventListener('click', function(){

  var content = '
';

  var textContent = document.querySelector('textarea').value;

  content += textContent;

  content += '
';

  document.getElementById('output').innerHTML = content;

});
<textarea cols=30 rows=10>This is some text
this is another text

Another text again and again </textarea>
<input type='submit' id='submit'>

A: You could set width of div using Javascript and add white-space:pre-wrap to p tag, this break your textarea content at end of each line.

document.querySelector("button").onclick = function gt(){
var card = document.createElement('div');
card.style.width = "160px";
card.style.background = "#eee";
var post = document.createElement('p');
var postText = document.getElementById('post-text').value;
post.style.whiteSpace = "pre-wrap";
card.append(post);
post.append(postText);
document.body.append(card);
}
<textarea id="post-text" class="form-control" rows="3" placeholder="What's up?" required>
Group Schedule:

Tuesday practice @ 5th floor (8pm - 11 pm)

Thursday practice @ 5th floor (8pm - 11 pm)

Sunday practice @ (9pm - 12 am)</textarea>

<button>Copy!!</button>

A: I suppose you don't want your textarea-content to be parsed as HTML. In this case, you can just set it as plaintext so the browser doesn't treat it as HTML and doesn't remove newlines No CSS or preprocessing required.

<textarea id='ta' rows='3'>
  line 1
  line 2
  line 3
</textarea>
<button id='btn' onclick='copycontent();'>
Copy
</button>

A: The easiest solution is to simply style the element you're inserting the text into with the following CSS property:
white-space: pre-wrap;

This property causes whitespace and newlines within the matching elements to be treated in the same way as inside a <textarea>.  That is, consecutive whitespace is not collapsed, and lines are broken at explicit newlines (but are also wrapped automatically if they exceed the width of the element).
Given that several of the answers posted here so far have been vulnerable to HTML injection (e.g. because they assign unescaped user input to innerHTML) or otherwise buggy, let me give an example of how to do this safely and correctly, based on your original code:

document.getElementById('post-button').addEventListener('click', function () {
  var post = document.createElement('p');
  var postText = document.getElementById('post-text').value;
  post.append(postText);
  var card = document.createElement('div');
  card.append(post);
  var cardStack = document.getElementById('card-stack');
  cardStack.prepend(card);
});
#card-stack p {
  background: #ddd;
  white-space: pre-wrap;  /* <-- THIS PRESERVES THE LINE BREAKS */
}
textarea {
  width: 100%;
}
<textarea id="post-text" class="form-control" rows="8" placeholder="What's up?" required>Group Schedule:

Tuesday practice @ 5th floor (8pm - 11 pm)

Thursday practice @ 5th floor (8pm - 11 pm)

Sunday practice @ (9pm - 12 am)</textarea>

<input type="button" id="post-button" value="Post!">

Note that, like your original code, the snippet above uses append() and prepend().  As of this writing, those functions are still considered experimental and not fully supported by all browsers.  If you want to be safe and remain compatible with older browsers, you can substitute them pretty easily as follows:

*

*element.append(otherElement) can be replaced with element.appendChild(otherElement);

*element.prepend(otherElement) can be replaced with element.insertBefore(otherElement, element.firstChild);

*element.append(stringOfText) can be replaced with element.appendChild(document.createTextNode(stringOfText));

*element.prepend(stringOfText) can be replaced with element.insertBefore(document.createTextNode(stringOfText), element.firstChild);

*as a special case, if element is empty, both element.append(stringOfText) and element.prepend(stringOfText) can simply be replaced with element.textContent = stringOfText.

Here's the same snippet as above, but without using append() or prepend():

document.getElementById('post-button').addEventListener('click', function () {
  var post = document.createElement('p');
  var postText = document.getElementById('post-text').value;
  post.textContent = postText;
  var card = document.createElement('div');
  card.appendChild(post);
  var cardStack = document.getElementById('card-stack');
  cardStack.insertBefore(card, cardStack.firstChild);
});
#card-stack p {
  background: #ddd;
  white-space: pre-wrap;  /* <-- THIS PRESERVES THE LINE BREAKS */
}
textarea {
  width: 100%;
}
<textarea id="post-text" class="form-control" rows="8" placeholder="What's up?" required>Group Schedule:

Tuesday practice @ 5th floor (8pm - 11 pm)

Thursday practice @ 5th floor (8pm - 11 pm)

Sunday practice @ (9pm - 12 am)</textarea>

<input type="button" id="post-button" value="Post!">

Ps. If you really want to do this without using the CSS white-space property, an alternative solution would be to explicitly replace any newline characters in the text with
 HTML tags.  The tricky part is that, to avoid introducing subtle bugs and potential security holes, you have to first escape any HTML metacharacters (at a minimum, & and <) in the text before you do this replacement.
Probably the simplest and safest way to do that is to let the browser handle the HTML-escaping for you, like this:
var post = document.createElement('p');
post.textContent = postText;
post.innerHTML = post.innerHTML.replace(/\n/g, '
\n');

document.getElementById('post-button').addEventListener('click', function () {
  var post = document.createElement('p');
  var postText = document.getElementById('post-text').value;
  post.textContent = postText;
  post.innerHTML = post.innerHTML.replace(/\n/g, '
\n');  // <-- THIS FIXES THE LINE BREAKS
  var card = document.createElement('div');
  card.appendChild(post);
  var cardStack = document.getElementById('card-stack');
  cardStack.insertBefore(card, cardStack.firstChild);
});
#card-stack p {
  background: #ddd;
}
textarea {
  width: 100%;
}
<textarea id="post-text" class="form-control" rows="8" placeholder="What's up?" required>Group Schedule:

Tuesday practice @ 5th floor (8pm - 11 pm)

Thursday practice @ 5th floor (8pm - 11 pm)

Sunday practice @ (9pm - 12 am)</textarea>

<input type="button" id="post-button" value="Post!">

Note that, while this will fix the line breaks, it won't prevent consecutive whitespace from being collapsed by the HTML renderer.  It's possible to (sort of) emulate that by replacing some of the whitespace in the text with non-breaking spaces, but honestly, that's getting rather complicated for something that can be trivially solved with a single line of CSS.

A: The target container should have the white-space:pre style.
Try it below.

<textarea id='ta' rows='3'>
  line 1
  line 2
  line 3
</textarea>
<button id='btn' onclick='copycontent();'>
Copy
</button>


text:
Q: DDD Factory Entity Value Object I have been increasingly adopting DDD / Onion Architecture in my current project.
One of the many things I am still unclear about is how much encapsulation should there be.
Easier explained with a concrete example.
Example
namespace MyProject.Model
{
    public class ComplexEntity
    {
        private int _id;
        public int Id { get {return _id;} }
        public ValueObjectA ValueA {get; set;}
        public bool IsBool {get; set;}
        public ComplexEntity(ValueObjectA a, bool isBool)
        {
            // Do some validation first
            ValueA = a;
            ValueB = b;
            IsBool = isBool;
        }
    }

    public class ValueObjectA
    {
        public bool IsBoolA {get; private set;}
        public bool IsBoolB {get; private set;}
        public ValueObjectA(bool a, bool b)
        {
            IsBoolA = a;
            IsBoolB = b;
        }
    }

    public Interface IComplextEntityFactory
    {
        // Option 1
        ComplexEntity Create(
            ValueObjectA a,
            bool IsBool);

        // Option 2
        ComplexEntity Create(
            bool valueABool a,
            bool valueBBool b,
            bool isBool);
    }
}

Question
For the factory of an entity, do you,

*

*Expect the caller to construct the value objects for you and use it to initialize the ComplexEntity?

*Have essentially CLR basic types being passed to the factory and you construct every ValueObject that makes up the Entity?

I am leaning towards option 2 but I can't seem to find supporting literature for it.
Edit 1
To be honest I am still no clearer.  What about aggregate roots?
When my entity refers to other entities, e.g. below.

*

*Should I have an IComplexEntityFactory, ILessComplexEntityFactory?  Or just an IComplexEntityAggregateFactory that creates the LessComplexEntity and instantiates ComplexEntity ?

*In the case of the AggregateFactory solution, what do I do if the LessComplexEntity attribtues that have been passed to the factory correspond to an existing LessComplexEntity?  Do I retrieve and reuse it from a Repository?  Or do I return an error to the caller?

*What would the method signature be for the AggregateFactory?  Would it be (ValueObject a, ValueObject b), or (ValueObject value, LessCompelxEntity entity)
public class ComplexEntity
{
    private readonly int _id;
    public int Id { get { return _id;} }
public ValueObject Value {get; set;}
public LessComplexEntity Entity {get; set;}

public ComplexEntity(int id, ValueObject value, LessComplexEntity entity)
{
}

}
public class LessComplexEntity
{
    private readonly int _id;
    public int Id { get {return _id;} }
    public ValueObject Value {get; set;}
    public LessComplexEntity(int id, ValuObject value)
    {
    }
}

A: I'd choose option 1.

*

*Makes explicit to everyone that you need a ValueObjectA to build a ComplexEntity. More readable, less head scratching when you see the method used somewhere.

*If ValueObjectA changes, you'll have to modify the code in only one place (the factory's caller) as opposed to changing the signature of Create() + adjusting the value object creation inside the factory.

*Less parameters to the factory's Create() method is less verbose and more readable.

*In unit tests, it gives you a lot more options to be able to inject the ValueObjectA you want. There's not a lot you can do in terms of testing if you keep ValueObjectA's creation hidden inside the factory entirely.
[Edit]
It's not clear what your real problem is with Aggregate Roots and Factories, but you shouldn't mix up the responsibility to retrieve/rehydrate an existing object with the responsibility to create an object.
I'd take as a general rule that a Factory's job is to assemble a new object from smaller parts (whether they be primitive types, value objects, entities...)
The Factory should be provided with all these parts, it is not its duty to retrieve or rehydrate them from somewhere. You can leave that to the Factory's caller. It will make the Factory more cohesive and coupled to less classes (Repositories, etc.)

A: I prefer Option #1 as it would reduce the number of parameters required on the factory method. But my advice would be to only use a factory when the aggregate in question requires a creation strategy.
In one of your comments you say:

"..but then I don't understand the benefit of the factory. All it would be doing then is just calling the constructor of the ComplexEntity rather than creating all the subcomponents that make it up."

The factory's job is to make decisions on how to instantiate the aggregate by looking at the data passed to it. In my experience a common scenario where this is required is where inheritance/polymorphism has been used. For example, imagine you have an abstract Account class, with two sub classes: SavingsAccount & CurrentAccount. The factory's job is to decide on which one to instantiate, given some data.
Another potential benefit of a factory is how expressive you can be. If an aggregate can be instantiated in more than one way (i.e. different arguments) then this can be expressed better with a method name on a factory than an overloaded constructor.
As I say, my advice is to not create a factory for every aggregate unless for one of the above reasons. Otherwise, as you have pointed out, it will just be one line calling the constructor with the same arguments passed to it.


text:
Q: test GameCenter Multiplayer on emulator are there anyways I can test a multiplayer games on the xcode emulator? because right now I am creating a multiplayer game and its my first one so there is alot of testing and it just seems like there should be an easier way to test the app rather than installing the build on 2 devices everytime.

A: You can use Xcode to build and run multiple instances of your application. You can select a connected device and build&run. Then select your iPhone simulator or another connected device and use build&run again. In the console you can switch between the two instances.


text:
Q: Is Swarm Mode going to be supported on Azure Container Service? After creating a Container Service with Swarm orchestration, setting up an SSH tunnel to the manager, and setting the DOCKER_HOST environment variable, I was able to issue commands to the Swarm manager on Azure.
Then I tried to deploy a Docker stack using a compose file (with the native docker stack up command, not the docker-compose utility), and I got an error message like
Daemon uses API version 1.24, stack deploy requires version 1.25.

(I don't have the exact text right now, but I think I remember the versions correctly.)
Similarly, issuing docker inspect swarm outputs
No such object: swarm

(Again, not exact quote.)
If I'm not mistaken, these errors are because the Docker version is too old, and does not have native Swarm Mode yet. And I only realized this after reading the Note about it in this article.
I know there are a couple of ways described in said article to make it work, one being acs-engine, but they are all far from straightforward. At least relative to how easy it was to access the Manager using just SSH and the local docker command.
So my question is really: Are there any plans to upgrade to a newer Docker version, and to have complete support for native Swarm Mode as orchestration? Or am I expected to just use Kubernetes (or something like that) instead?
In any case, I think it would be worth considering to somehow communicate better the fact that the supported Swarm is the legacy one, and not the native Swarm Mode.

A: Docker CE is available in preview in a number of regions and is rolling out across all regions now. See https://github.com/Azure/ACS/blob/master/announcements/2017-08-04_additional_regions.md
Docker Inc. also provide Docker for Azure as @janshair says in another answer.

A: Azure Container Service does not support Swarm Mode for now. It uses older Docker Swarm for container orchestrations. For now you can use Kubernetes or Mesos on ACS.
If you still want to use Swarm Mode, you either have to setup your own environment (i.e. setup VMs, Init Swarm etc.) or use Docker for Azure with Docker CE or EE edition.


text:
Q: How to fix plot labels from appearing above one bar in grouped plot? I made a grouped bar plot in ggplot and I want to label each bar with the number_of_systems. The labels show up but they all appear over the middle bar, reporting_systems B, in the group. How can I edit geom_text to get the labels to appear over their appropriate bars?
data1 <- data.frame(office = c("HR","HR","HR","Comms","Comms","Comms","Legal","Legal","Legal","Accounting","Accounting","Accounting","Admin","Admin","Admin","Policy","Policy","Policy","Research","Research","Research"), reporting_systems = c("A","B","C","A","B","C","A","B","C","A","B","C","A","B","C","A","B","C","A","B","C"), number_of_systems = c(27,0,0,12,1,4,15,2,15,29,0,0,2,0,0,59,28,46,0,0,0))

reporting_order <- factor(data$reporting_systems, level = c("A","B","C"))

ggplot(data = data1, aes(x = office, y = number_of_systems, fill = reporting_order)) +
  geom_bar(stat = "identity", position = position_dodge()) +
  xlab("") +
  ylab("Number of Projects") +
  ggtitle("") +
  geom_text(aes(label = number_of_systems, fill = reporting_order), vjust = -0.3, color = "black", size = 4) +
  theme(axis.line = element_line(color = "black"),
        axis.text = element_text(color = "black", size = 15),
        axis.text.x = element_text(angle = 35, hjust = 1),
        axis.text.y = element_text(angle = 0, hjust = 1), axis.title.y = (element_text(size = 15)),
        panel.grid.minor = element_blank(), panel.grid.major = element_blank(),
        panel.border = element_rect(color = "black", fill = NA, size = 0.5),
        panel.background = element_rect(fill = NA), text = element_text(size = 15))

A: There's a very similar issue here.
The answer is to add a position parameter to your geom_text:
ggplot(data = data1, aes(x = office, y = number_of_systems, fill = reporting_order)) +
  geom_bar(stat = "identity", position = position_dodge()) +
  xlab("") +
  ylab("Number of Projects") +
  ggtitle("") +
  geom_text(position = position_dodge(width=0.9), aes(label = number_of_systems, fill = reporting_order), vjust = -0.3, color = "black", size = 4) +
  theme(axis.line = element_line(color = "black"),
        axis.text = element_text(color = "black", size = 15),
        axis.text.x = element_text(angle = 35, hjust = 1),
        axis.text.y = element_text(angle = 0, hjust = 1), axis.title.y = (element_text(size = 15)),
        panel.grid.minor = element_blank(), panel.grid.major = element_blank(),
        panel.border = element_rect(color = "black", fill = NA, size = 0.5),
        panel.background = element_rect(fill = NA), text = element_text(size = 15))