text:
Q: Getting Fatl Exception in Fragments I am very new to Android and i am learning android through "online" from some site.
Now i am learning how to implement Fragments.
In that very initially i got below exception and i don't know the reason.Please help me to resolve it.
Exception::
03-30 17:55:23.583: I/Process(1221): Sending signal. PID: 1221 SIG: 9
03-30 17:55:24.701: E/Trace(1265): error opening trace file: No such file or directory (2)
03-30 17:55:24.921: D/AndroidRuntime(1265): Shutting down VM
03-30 17:55:24.921: W/dalvikvm(1265): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
03-30 17:55:24.952: E/AndroidRuntime(1265): FATAL EXCEPTION: main
03-30 17:55:24.952: E/AndroidRuntime(1265): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.fragments/com.example.fragments.MainActivity}: android.view.InflateException: Binary XML file line #11: Error inflating class fragment
03-30 17:55:24.952: E/AndroidRuntime(1265):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
03-30 17:55:24.952: E/AndroidRuntime(1265):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
03-30 17:55:24.952: E/AndroidRuntime(1265):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-30 17:55:24.952: E/AndroidRuntime(1265):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
03-30 17:55:24.952: E/AndroidRuntime(1265):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-30 17:55:24.952: E/AndroidRuntime(1265):     at android.os.Looper.loop(Looper.java:137)
03-30 17:55:24.952: E/AndroidRuntime(1265):     at android.app.ActivityThread.main(ActivityThread.java:5041)
03-30 17:55:24.952: E/AndroidRuntime(1265):     at java.lang.reflect.Method.invokeNative(Native Method)
03-30 17:55:24.952: E/AndroidRuntime(1265):     at java.lang.reflect.Method.invoke(Method.java:511)
03-30 17:55:24.952: E/AndroidRuntime(1265):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-30 17:55:24.952: E/AndroidRuntime(1265):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-30 17:55:24.952: E/AndroidRuntime(1265):     at dalvik.system.NativeStart.main(Native Method)
03-30 17:55:24.952: E/AndroidRuntime(1265): Caused by: android.view.InflateException: Binary XML file line #11: Error inflating class fragment
03-30 17:55:24.952: E/AndroidRuntime(1265):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
03-30 17:55:24.952: E/AndroidRuntime(1265):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
03-30 17:55:24.952: E/AndroidRuntime(1265):     at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
03-30 17:55:24.952: E/AndroidRuntime(1265):     at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
03-30 17:55:24.952: E/AndroidRuntime(1265):     at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
03-30 17:55:24.952: E/AndroidRuntime(1265):     at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:270)
03-30 17:55:24.952: E/AndroidRuntime(1265):     at android.app.Activity.setContentView(Activity.java:1881)
03-30 17:55:24.952: E/AndroidRuntime(1265):     at com.example.fragments.MainActivity.onCreate(MainActivity.java:15)
03-30 17:55:24.952: E/AndroidRuntime(1265):     at android.app.Activity.performCreate(Activity.java:5104)
03-30 17:55:24.952: E/AndroidRuntime(1265):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
03-30 17:55:24.952: E/AndroidRuntime(1265):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
03-30 17:55:24.952: E/AndroidRuntime(1265):     ... 11 more
03-30 17:55:24.952: E/AndroidRuntime(1265): Caused by: android.app.Fragment$InstantiationException: Unable to instantiate fragment com.example.fragments: make sure class name exists, is public, and has an empty constructor that is public
03-30 17:55:24.952: E/AndroidRuntime(1265):     at android.app.Fragment.instantiate(Fragment.java:592)
03-30 17:55:24.952: E/AndroidRuntime(1265):     at android.app.Fragment.instantiate(Fragment.java:560)
03-30 17:55:24.952: E/AndroidRuntime(1265):     at android.app.Activity.onCreateView(Activity.java:4709)
03-30 17:55:24.952: E/AndroidRuntime(1265):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:680)
03-30 17:55:24.952: E/AndroidRuntime(1265):     ... 21 more
03-30 17:55:24.952: E/AndroidRuntime(1265): Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.fragments" on path: /data/app/com.example.fragments-1.apk
03-30 17:55:24.952: E/AndroidRuntime(1265):     at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:65)
03-30 17:55:24.952: E/AndroidRuntime(1265):     at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
03-30 17:55:24.952: E/AndroidRuntime(1265):     at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
03-30 17:55:24.952: E/AndroidRuntime(1265):     at android.app.Fragment.instantiate(Fragment.java:582)
03-30 17:55:24.952: E/AndroidRuntime(1265):     ... 24 more

MainActivity .java
public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Configuration config = getResources().getConfiguration();
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction =
        fragmentManager.beginTransaction();

        /**
        * Check the device orientation and act accordingly
        */
        if (config.orientation == Configuration.ORIENTATION_LANDSCAPE) {
           /**
           * Landscape mode of the device
           */
            LM_Fragement ls_fragment = new LM_Fragement();
           fragmentTransaction.replace(android.R.id.content, ls_fragment);
        }else{
           /**
           * Portrait mode of the device
           */
            PM_Fragement pm_fragment = new PM_Fragement();
           fragmentTransaction.replace(android.R.id.content, pm_fragment);
        }
        fragmentTransaction.commit();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

PM_Fragement.Java
package com.example.fragments;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class PM_Fragement extends Fragment{

    public View onCreateView(LayoutInflater inflater,
              ViewGroup container, Bundle savedInstanceState) {
              /**
               * Inflate the layout for this fragment
               */
              return inflater.inflate(
              R.layout.pm_fragment, container, false);
           }
}

AndroidManifet.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.fragments"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="17" />

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".PM_Fragement" />
        <activity android:name=".LM_Fragement"/>
    </application>

</manifest>

**LM_Fragement.java **
package com.example.fragments;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class LM_Fragement extends Fragment {

    public View onCreateView(LayoutInflater inflater,
              ViewGroup container, Bundle savedInstanceState) {
              /**
               * Inflate the layout for this fragment
               */
              return inflater.inflate(
              R.layout.lm_fragment, container, false);
           }
}

A: Remove these form manifest file
<activity android:name=".PM_Fragement" />
<activity android:name=".LM_Fragement"/>

PM_Fragement and LM_Fragement are Fragments not Activities. Only Activities are declared in manifest file.


text:
Q: White border around page doesn't go away (html, css, js) i can't seem to get rid of the white border around around the page. i tried using *, html, and body, but nothing seems to work. it might have something to do with the #main page or nav bar? i'm new to html, css and js so this might be out of my scope or not looking for the right thing.  thanks in advance!

const backToTopButton = document.querySelector("#back-to-top-btn");

window.addEventListener("scroll", scrollFunction);

function scrollFunction() {
  if (window.pageYOffset > 300) { // Show backToTopButton
    if(!backToTopButton.classList.contains("btnEntrance")) {
      backToTopButton.classList.remove("btnExit");
      backToTopButton.classList.add("btnEntrance");
      backToTopButton.style.display = "block";
    }
  }
  else { // Hide backToTopButton
    if(backToTopButton.classList.contains("btnEntrance")) {
      backToTopButton.classList.remove("btnEntrance");
      backToTopButton.classList.add("btnExit");
      setTimeout(function() {
        backToTopButton.style.display = "none";
      }, 250);
    }
  }
}

backToTopButton.addEventListener("click", smoothScrollBackToTop);

// function backToTop() {
//   window.scrollTo(0, 0);
// }

function smoothScrollBackToTop() {
  const targetPosition = 0;
  const startPosition = window.pageYOffset;
  const distance = targetPosition - startPosition;
  const duration = 750;
  let start = null;

  window.requestAnimationFrame(step);

  function step(timestamp) {
    if (!start) start = timestamp;
    const progress = timestamp - start;
    window.scrollTo(0, easeInOutCubic(progress, startPosition, distance, duration));
    if (progress < duration) window.requestAnimationFrame(step);
  }
}

function easeInOutCubic(t, b, c, d) {
    t /= d/2;
    if (t < 1) return c/2*t*t*t + b;
    t -= 2;
    return c/2*(t*t*t + 2) + b;
};
* {
    margin: 0;
    padding: 0;
    font-family: sans-serif;
}

.container {
  width: 100%;
  height: 100vh;
  scroll-behavior: smooth;
  overflow-y: scroll;
  scroll-snap-type: y mandatory;
  overflow-x: hidden;
  min-width:100%;
}

.scroll {
  width: 100%;
  height: 100vh;
  scroll-snap-align: center;
  position: relative;
}

/* NAVIGATION BAR */

#main {
    width: 100%;
    height: 100%;
  background-color: green;
}

nav {
    width: 100%;
    height: 80px;
    background-color: #fff;
    line-height: 80px;
}

nav ul {
    text-align: center;
}

nav ul li {
    list-style-type: none;
    display: inline-block;
    transition: 0.8s all;
}

nav ul li a {
    text-decoration: none;
    color: gray;
    padding: 30px;
}

nav ul li a:hover {
    color: #000;
}

/* HOME NAME */

.name {
  font-family: sans-serif;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translateX(-50%) translateY(-50%);
    text-align: center;
}

/* TYPEWRITER EFFECT */

.css-typing {
  position: absolute;
  top: 55%;
  left: 36.5%;
  /*transform: translateX(-40%) translateY(-60%);*/
}

.css-typing p {
  border-right: .15em solid orange;
  font-family: "Courier";
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
}

.css-typing p:nth-child(1) {
  /*width: 7.3em;*/
  width: 10ch;
  -webkit-animation: type 2s steps(10, end);
  animation: type 2s steps(10, end);
  -webkit-animation-fill-mode: forwards;
  animation-fill-mode: forwards;
}

.css-typing p:nth-child(2) {
  width: 38ch;
  opacity: 0;
  -webkit-animation: type2 2s steps(40, end);
  animation: type2 2s steps(40, end);
  -webkit-animation-delay: 2s;
  animation-delay: 2s;
  -webkit-animation-fill-mode: forwards;
  animation-fill-mode: forwards;
}

.css-typing p:nth-child(3) {
  width: 13ch;
  opacity: 0;
  -webkit-animation: type3 5s steps(20, end), blink .5s step-end infinite alternate;
  animation: type3 5s steps(20, end), blink .5s step-end infinite alternate;
  -webkit-animation-delay: 4s;
  animation-delay: 4s;
  -webkit-animation-fill-mode: forwards;
  animation-fill-mode: forwards;
}

@keyframes type {
  0% {
    width: 0;
  }
  99.9% {
    border-right: .15em solid orange;
  }
  100% {
    border: none;
  }
}

@-webkit-keyframes type {
  0% {
    width: 0;
  }
  99.9% {
    border-right: .15em solid orange;
  }
  100% {
    border: none;
  }
}

@keyframes type2 {
  0% {
    width: 0;
  }
  1% {
    opacity: 1;
  }
  99.9% {
    border-right: .15em solid orange;
  }
  100% {
    opacity: 1;
    border: none;
  }
}

@-webkit-keyframes type2 {
  0% {
    width: 0;
  }
  1% {
    opacity: 1;
  }
  99.9% {
    border-right: .15em solid orange;
  }
  100% {
    opacity: 1;
    border: none;
  }
}

@keyframes type3 {
  0% {
    width: 0;
  }
  1% {
    opacity: 1;
  }
  100% {
    opacity: 1;
  }
}

@-webkit-keyframes type3 {
  0% {
    width: 0;
  }
  1% {
    opacity: 1;
  }
  100% {
    opacity: 1;
  }
}

@keyframes blink {
  50% {
    border-color: transparent;
  }
}
@-webkit-keyframes blink {
  50% {
    border-color: tranparent;
  }
}

/* SECTIONS */

.box {
  width: 100%;
  height: 100vh;
  padding: 70px;
  display: flex;
}

.box .imgPro {
  width: 150px;
  flex: 0 0 150px;
}

.box .imgPro img {
  width: 100%;
  padding: 10px;
  border-radius: 50%;
}

.box .content {
  padding-left: 20px;
}

.box .content h2 {
  margin: 0;
  padding-left: 0;
  padding-bottom: 20px;
  text-align: center;
}

/* BACK TO TOP BUTTON */

#back-to-top-btn {
  display: none;
  position: fixed;
  bottom: 20px;
  right: 20px;
  font-size: 26px;
  width: 50px;
  height: 50px;
  background-color: #fff;
  color: #333;
  cursor: pointer;
  outline: none;
  border: 3px solid #333;
  border-radius: 50%;
  transition-duration: 0.2s;
  transition-timing-function: ease-in-out;
  transition-property: background-color, color;
}

#back-to-top-btn:hover, #back-to-top-btn:focus {
  background-color: #333;
  color: #fff;
}
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=devide-width, initialpscale=1.0">
    <title> TITLE </title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
    <link rel="stylesheet" type="text/css" href="style.css">

    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">

  <button id="back-to-top-btn"></button>

Home

About

Resume

Portfolio

Contact

TITLE

About

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ac gravida nibh. Donec et viverra leo. Sed hendrerit blandit lectus. In pretium orci tellus, porta sollicitudin mauris lobortis et. Donec at sollicitudin nisl. Cras congue elit sed dolor interdum auctor. Nunc convallis purus a vestibulum mollis. Suspendisse ac volutpat sem. Nunc in neque mollis, mattis augue tristique, ornare dolor. Morbi imperdiet tincidunt lectus at molestie. Fusce ultricies mattis maximus.

A: _grid.scss is overriding your custom rules because the .container selector they're using is more specific than your wildcard * selector.
You can use the !important qualifier to increase your rules' priority, however be aware that this sort of convention is somewhat discouraged, and in your scenario will cause all elements to have a margin and padding of 0.
Instead, make your selector a bit more specific by changing * to body .container (see below). You should really review Specificity to ensure you understand what exactly is going on here.

const backToTopButton = document.querySelector("#back-to-top-btn");

window.addEventListener("scroll", scrollFunction);

function scrollFunction() {
  if (window.pageYOffset > 300) { // Show backToTopButton
    if(!backToTopButton.classList.contains("btnEntrance")) {
      backToTopButton.classList.remove("btnExit");
      backToTopButton.classList.add("btnEntrance");
      backToTopButton.style.display = "block";
    }
  }
  else { // Hide backToTopButton
    if(backToTopButton.classList.contains("btnEntrance")) {
      backToTopButton.classList.remove("btnEntrance");
      backToTopButton.classList.add("btnExit");
      setTimeout(function() {
        backToTopButton.style.display = "none";
      }, 250);
    }
  }
}

backToTopButton.addEventListener("click", smoothScrollBackToTop);

// function backToTop() {
//   window.scrollTo(0, 0);
// }

function smoothScrollBackToTop() {
  const targetPosition = 0;
  const startPosition = window.pageYOffset;
  const distance = targetPosition - startPosition;
  const duration = 750;
  let start = null;

  window.requestAnimationFrame(step);

  function step(timestamp) {
    if (!start) start = timestamp;
    const progress = timestamp - start;
    window.scrollTo(0, easeInOutCubic(progress, startPosition, distance, duration));
    if (progress < duration) window.requestAnimationFrame(step);
  }
}

function easeInOutCubic(t, b, c, d) {
    t /= d/2;
    if (t < 1) return c/2*t*t*t + b;
    t -= 2;
    return c/2*(t*t*t + 2) + b;
};
body .container {
    margin: 0;
    padding: 0;
    font-family: sans-serif;
}

.container {
  width: 100%;
  height: 100vh;
  scroll-behavior: smooth;
  overflow-y: scroll;
  scroll-snap-type: y mandatory;
  overflow-x: hidden;
  min-width:100%;
}

.scroll {
  width: 100%;
  height: 100vh;
  scroll-snap-align: center;
  position: relative;
}

/* NAVIGATION BAR */

#main {
    width: 100%;
    height: 100%;
  background-color: green;
}

nav {
    width: 100%;
    height: 80px;
    background-color: #fff;
    line-height: 80px;
}

nav ul {
    text-align: center;
}

nav ul li {
    list-style-type: none;
    display: inline-block;
    transition: 0.8s all;
}

nav ul li a {
    text-decoration: none;
    color: gray;
    padding: 30px;
}

nav ul li a:hover {
    color: #000;
}

/* HOME NAME */

.name {
  font-family: sans-serif;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translateX(-50%) translateY(-50%);
    text-align: center;
}

/* TYPEWRITER EFFECT */

.css-typing {
  position: absolute;
  top: 55%;
  left: 36.5%;
  /*transform: translateX(-40%) translateY(-60%);*/
}

.css-typing p {
  border-right: .15em solid orange;
  font-family: "Courier";
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
}

.css-typing p:nth-child(1) {
  /*width: 7.3em;*/
  width: 10ch;
  -webkit-animation: type 2s steps(10, end);
  animation: type 2s steps(10, end);
  -webkit-animation-fill-mode: forwards;
  animation-fill-mode: forwards;
}

.css-typing p:nth-child(2) {
  width: 38ch;
  opacity: 0;
  -webkit-animation: type2 2s steps(40, end);
  animation: type2 2s steps(40, end);
  -webkit-animation-delay: 2s;
  animation-delay: 2s;
  -webkit-animation-fill-mode: forwards;
  animation-fill-mode: forwards;
}

.css-typing p:nth-child(3) {
  width: 13ch;
  opacity: 0;
  -webkit-animation: type3 5s steps(20, end), blink .5s step-end infinite alternate;
  animation: type3 5s steps(20, end), blink .5s step-end infinite alternate;
  -webkit-animation-delay: 4s;
  animation-delay: 4s;
  -webkit-animation-fill-mode: forwards;
  animation-fill-mode: forwards;
}

@keyframes type {
  0% {
    width: 0;
  }
  99.9% {
    border-right: .15em solid orange;
  }
  100% {
    border: none;
  }
}

@-webkit-keyframes type {
  0% {
    width: 0;
  }
  99.9% {
    border-right: .15em solid orange;
  }
  100% {
    border: none;
  }
}

@keyframes type2 {
  0% {
    width: 0;
  }
  1% {
    opacity: 1;
  }
  99.9% {
    border-right: .15em solid orange;
  }
  100% {
    opacity: 1;
    border: none;
  }
}

@-webkit-keyframes type2 {
  0% {
    width: 0;
  }
  1% {
    opacity: 1;
  }
  99.9% {
    border-right: .15em solid orange;
  }
  100% {
    opacity: 1;
    border: none;
  }
}

@keyframes type3 {
  0% {
    width: 0;
  }
  1% {
    opacity: 1;
  }
  100% {
    opacity: 1;
  }
}

@-webkit-keyframes type3 {
  0% {
    width: 0;
  }
  1% {
    opacity: 1;
  }
  100% {
    opacity: 1;
  }
}

@keyframes blink {
  50% {
    border-color: transparent;
  }
}
@-webkit-keyframes blink {
  50% {
    border-color: tranparent;
  }
}

/* SECTIONS */

.box {
  width: 100%;
  height: 100vh;
  padding: 70px;
  display: flex;
}

.box .imgPro {
  width: 150px;
  flex: 0 0 150px;
}

.box .imgPro img {
  width: 100%;
  padding: 10px;
  border-radius: 50%;
}

.box .content {
  padding-left: 20px;
}

.box .content h2 {
  margin: 0;
  padding-left: 0;
  padding-bottom: 20px;
  text-align: center;
}

/* BACK TO TOP BUTTON */

#back-to-top-btn {
  display: none;
  position: fixed;
  bottom: 20px;
  right: 20px;
  font-size: 26px;
  width: 50px;
  height: 50px;
  background-color: #fff;
  color: #333;
  cursor: pointer;
  outline: none;
  border: 3px solid #333;
  border-radius: 50%;
  transition-duration: 0.2s;
  transition-timing-function: ease-in-out;
  transition-property: background-color, color;
}

#back-to-top-btn:hover, #back-to-top-btn:focus {
  background-color: #333;
  color: #fff;
}
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=devide-width, initialpscale=1.0">
    <title> TITLE </title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
    <link rel="stylesheet" type="text/css" href="style.css">

    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">

  <button id="back-to-top-btn"></button>

Home

About

Resume

Portfolio

Contact

TITLE

About

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ac gravida nibh. Donec et viverra leo. Sed hendrerit blandit lectus. In pretium orci tellus, porta sollicitudin mauris lobortis et. Donec at sollicitudin nisl. Cras congue elit sed dolor interdum auctor. Nunc convallis purus a vestibulum mollis. Suspendisse ac volutpat sem. Nunc in neque mollis, mattis augue tristique, ornare dolor. Morbi imperdiet tincidunt lectus at molestie. Fusce ultricies mattis maximus.

A: Css works as cascade. In your html head you have multiple .css files their order matters. First is overwritten by second, second by third.

Css works as cascade - you can set the same property many times and only the last / closest one will be assigned.
Css can be declared as:

*

*.css file indicated in file .html section

*inside .css file with @import

*straight declaration in section

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can i windows command prompt commands from maven pom.xml file? I am making a maven project which is trying to run command prompt commands. I tried Exec Maven Plugin but couldn't do it. I think i'm at wrong way for this. Here is my work for making a file with "Exec Maven Plugin". Can someone make an explanation why this is not working or make a suggestion about new plugin or solution which is working at pom.xml (not Ant).
 `<build>
    <plugins>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.2.1</version>
            <executions>
                <execution>
                    <goals>
                        <goal>exec</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <executable>mkdir</executable>
                <arguments>
                    <argument>C:\Users\USERNAME\Desktop\FILENAME</argument>
                </arguments>
            </configuration>
        </plugin>
    </plugins>
</build>`

Thank You..

A: This is just a workaround you can try until someone comes up with a better answer. (I will remove it afterwards probably)
Instead of executing commands directly, you can create a bash/batch script and try to execute that. For example:
<execution>
  <id>Some ID</id>
  <phase>generate-sources</phase>
  <goals>
    <goal>exec</goal>
  </goals>
  <configuration>
    <executable>${basedir}/scripts/do_stuff.sh</executable>
  </configuration>
</execution>

It's basically the same thing, but you can use the normal syntax in the script, instead of the XML syntax in the POM file.


text:
Q: Using observe_field on an field inside a fields_for I'm trying to observe a field that get generated inside a fields_for loop.
The thing is that the id of that field is generated dynamically.
_form.html.erb
<% form_for @exp, :url => {:action => "update"} do |f| %>
    <% f.fields_for:patterns do |builder| %>
    <%= render 'pattern_fields', :f => builder %>
    <% end %>
<% end %>

_pattern_fields.html.erb
Pattern: <%= f.select(:LC_PATTERN, [['stripes', 'stripes'],
                                  ['dots', 'dots'],
                                  ['lines', 'lines'],
                                 ],{ :prompt => "Please select"}
                                 ) %>

<%= observe_field("------", :frequency => 1,
:with => "'id='+value", :function => 'alert(value)')%>

My question is how do i get the id of the field inside the fields_for tag.

A: I finally got it. Found this solution on the internet...Hope it might be of help to someone else.
In your application_helper.rb, add the following functions:
def sanitized_object_name(object_name)
  object_name.gsub(/\]\[|[^-a-zA-Z0-9:.]/,"_").sub(/_$/,"")
end

def sanitized_method_name(method_name)
  method_name.sub(/\?$/, "")
end

def form_tag_id(object_name, method_name)
  "#{sanitized_object_name(object_name.to_s)}_#{sanitized_method_name(method_name.to_s)}"
end

You can then view the id of the fields generated inside 'fields_for' by using the following code:
<%=form_tag_id(f.object_name, :LC_PATTERN) %>


text:
Q: How to keep logged-in to Facebook in Win Store app? I'm using Facebook C# SDK to build a Windows Store app which interacts with data in Facebook.
I followed sample project and I could build an app.
But I have one question.
Login page shows a checkbox "Keep me signed-in".
I check the box and login to Facebook. But every time I launch the app, the login page is shown and I have to input my account.
I had developed similar app for Windows Phone7 with Facebook C# SDK. With that app, I have to login only once. From 2nd time, it automatically proceeds to content page.
How can I do the same thing for Windows Store App?

A: you can register on file your AccessToken and reuse it.
I have wrap the fb client in Singleton object and use this code
        if (!string.IsNullOrEmpty((string)Windows.Storage.ApplicationData.Current.LocalSettings.Values["AccessToken"]))
        {
            FbClient.Instance.AccessToken = (string)Windows.Storage.ApplicationData.Current.LocalSettings.Values["AccessToken"];
            Frame.Navigate(typeof(FBHomePage));
        }
        else
        {
            var s = FbClient.Instance.Login(); //as Sdk example...
        }
        FbClient.Instance.LoginSucced += Instance_LoginSucced;

and in Instance_LoginSucced
    void Instance_LoginSucced(object sender, EventArgs e)
    {

        Windows.Storage.ApplicationData.Current.LocalSettings.Values.Add
        (
            new KeyValuePair<string, object>("AccessToken", FbClient.Instance.AccessToken)
        );

        Frame.Navigate(typeof(FBHomePage));
    }


text:
Q: "Polysticks" in 3d Consider a finite set of three-dimensional Euclidean vectors with integer components. How many three-dimensional closed loops can I construct with them? How many of them are elementary, i.e., cannot be generated by joining one (or more) edges of two other loops? How can I prove that a loop is elementary?
Any helpful references? The closest structures that I am aware of are polysticks, but my searches for polysticks in three dimensions yielded no useful results.
EDIT ::
This problem occurs when trying to enumerate the elementary closed paths that particles traverse when they move on a lattice. The sense of directionality is important.
The naive search algorithm -- i.e., start with the shortest possible loops (length 3), find how many they are, then increase the length and see if the loops of this length can be decomposed into loops of shorter length sharing one or more edges -- is very ineffective and, therefore, wasteful. I was hoping to find a more elegant approach.

A: I found out that an answer to the first question (the total number of loops of a certain length) can be furnished by algebraic graph theory, and in particular the adjacency matrix. All one needs to do is to represent any given configuration of polysticks as a graph $G$ and then form the adjacency matrix $A_G$ of $G$. Then, the matrix $A_G^n$ (i.e., the matrix product of $n$ copies of $A_G$) has an interesting interpretation: the entry in row $i$ and column $j$ gives the number of walks of length $n$ from vertex $i$ to vertex $j$. The diagonal elements are therefore the wanted numbers of cycles (loops).


text:
Q: PHP mistura códigos de orientação a objetos e linguagem procedural? Estou aprendendo PHP, e pelos exemplo que tenho visto na internet existe uma mistura na codificação dos programas, de orientação a objeto e procedimentos estruturados.
Isso é mesmo comum ou estou equivocado?
Se PHP é uma linguagem orientada a objetos, até que ponto é interessante ou não essa mistura?

A: TL;DR - Kind of
Não está totalmente equivocado, mas está um pouco.
Informalmente podemos dizer que é misturado mesmo, mas quase todas linguagens ditas orientadas a objeto fazem o mesmo. O grosso do código é procedural (ou mais precisamente, imperativo). A orientação a objeto entra em outro nível, mais na organização do código. Ele atua mais na estrutura de dados e onde vai colocar os algoritmos do que nos algoritmos em si, que são imperativos.
Alguns dizem que OOP nem é um paradigma completo.
Na própria documentação do PHP tem vários exemplos de escrever o mesmo código com o modo procedural e o modo OOP. Podemos aceitar esta definição, mas estritamente aquilo não é bem OOP. PHP é uma linguagem que não costuma seguir muito bem as definições corretas.
No fundo o que eles estão querendo dizer ali é que você pode escolher entre: 1) passar um objeto como parâmetro para um método; ou 2) usar uma sintaxe onde o método é invocado pelo objeto. O que na prática dá no mesmo por baixo dos panos. No fundo este último caso o método apenas terá um parâmetro extra chamado $this que fica escondido. Você só está trocando o parâmetro de lugar.
Isso tem alguma vantagem com ferramentas (IDE por exemplo) que podem ajudar codificar e analisar dados já sabendo do que se trata. Fora isso, não há vantagens reais. Individualmente pode haver alguma vantagem secundária que foi melhor resolvida no caso da sintaxe que destaca o objeto, mas foi algo adicional que aproveitaram e resolveram quando estavam criando essa camada extra. Pode haver uma desvantagem por gerar uma camada a mais.
A mistura de sintaxe não causa problemas, pelo menos não deveria. De paradigmas também não. A mistura é sempre boa se ela resolve melhor o problema, purismo é dogmático, é forçar algo pelo gosto e não pela necessidade.
O que é OOP?
Mas usar essa sintaxe não pode ser considerado programação orientada a objeto. No máximo, quem criou essas classes é que programou orientado a objeto, não quem consumiu. Mesmo isto é complicado dizer porque o uso de classes não define que está se programando orientado a objeto. Esse paradigma sequer exige a presença de classes.
OOP é algo muito mais complexo, e no fundo a maioria dos programadores nem fazem ideia de como programar desta forma. Isto inclui os que dizem que programam orientado a objeto e na verdade não o fazem, ou fazem de forma toda errada. Isso é explicado pelo efeito Dunning Kruger.
OOP é uma metodologia para organizar melhor o código e promover o seu reuso em uma forma específica.
Nem todo mundo concorda com todas as definições, inclusive o autor do termo diz que as definições que costumam usar estão erradas. Embora o uso de OOP, de alguma forma, antecede o uso o termo.
Uma das formas mais aceitas diz que OOP se dá quando há herança, polimorfismo e encapsulamento. Abstração e outros conceitos costumam ser incluídos em algumas definições, mas estas três alcançam mais consenso.
A maioria dos programadores que dizem usar OOP não usam ou não sabem usar corretamente os conceitos fundamentais. Então, podemos dizer que esta pessoa está usando OOP de fato?
Em geral elas apenas criam classes, o que pode atender o encapsulamento, se fizer certo. Mas isso é possível fazer em qualquer paradigma de uma forma ou de outra. No fundo, quando as pessoas fazem isso estão programando no paradigma modular.
Nessa pergunta (leia principalmente a parte de OOP, é importante para entender) eu até falo que uma das coisas que mais impulsionaram a programação é a modularização, e uma das formas de modularizar é encapsular. Isso não é exclusivo de OOP. De fato é algo muito importante.
Pra que OOP é boa?
Justamente por causa da herança OOP é uma mão na roda para representar hierarquias e relações complexas entre objetos. Ótimo para GUIs e alguns tipos de jogos (e outros tipos de aplicação, claro, não vou citar tudo). Mas não é tão bom assim para todos os problemas.
OOP realmente ajuda muito organizar grandes bases de código manipuladas por grandes equipes. Mas OOP tem um custo também.
Em cenários onde as hierarquias não são tão importantes, as relações não são tão complexas e o desenvolvimento é feito de forma individualizada ou por equipe muito pequena, ou pelo menos a aplicação é desenvolvida de forma muito fragmentada (modularização natural, típico de aplicações PHP, já que são scripts), OOP, de verdade, não é tão útil assim.
E é menos ainda quando a pessoa não tem um profundo entendimento do que está fazendo. E o que vemos aqui mesmo neste site é que as pessoas cometem muitos erros, alguns grotescos. Eu cometo erros, mesmo tendo estudado bastante o assunto, não é fácil acertar com esse paradigma, e ele precisa ser certo para aproveitá-lo bem, não é fácil corrigir depois se feito errado no começo, apesar de algumas pessoas acreditarem o contrário (se refatoração resolvesse tão bem então fazer procedural não seria problema também).
OOP burocratiza o desenvolvimento. Se isso é bom ou ruim depende de cada caso e não vou cravar uma posição.
O SOpt mesmo usa uma linguagem dita orientada a objeto (ainda que seja uma mentira classificar C# assim), e os engenheiros dele, alguns dos melhores do mundo, escolheram conscientemente não usar esse paradigma para sua construção, não seguiram folclores, e se beneficiaram muito disto. Se esse projeto, que não é nada simples, ficou melhor sem OOP, por que você acha que seu projeto web mais simples se beneficiará dele?
PHP é orientada a objeto?
PHP éera uma linguagem de script, éera uma linguagem sem cerimônia, ela brilha nisso, se não usar tanto cacareco que colocaram depois.
Ela executa pequenos trechos de código de cada vez e morrem. Esses scripts não duram na memória, não carregam tudo o que a aplicação fará, as execuções são mais estanques.
É muito mais fácil administrar esse tipo de código do que em um sistema ERP monolítico, por exemplo.
PHP faz uma modularização de forma natural, você usa só o que precisa para aquele contexto momentâneo. Você inclui o que quer de forma extremamente fácil, sem nada de OOP.
PHP não é orientada a objeto. Ela é originalmente imperativa/procedural e mais recentemente adotou, adicionalmente, conceitos de OO.
Essas extensões da linguagem para manipular OOP são ótimas para transformar PHP em uma linguagem de propósito geral, mas ajudam muito pouco no domínio onde ela tem sucesso, a web.
Essas extensões facilitam o uso de OOP, mas já era possível antes. Como as pessoas não entendem o que é OOP, elas achavam que não dava. As ferramentas só ficaram mais óbvias.
Na verdade PHP é uma das linguagens mais fáceis de adotar OOP mesmo antes de existir sintaxe específica para isto. Todo sistema de classes, herança, polimorfismo, etc. do PHP foi desenvolvido em cima dos arrays associativos (não estou dizendo que ele usa exatamente os mesmos arrays da linguagem, como o JavaScript faz, apenas é algo muito semelhante) e não é difícil simular todos conceitos OO usando esse mecanismo (tem exemplo ingênuo nessa pergunta). Só não tinha a sintaxe mais conveniente e já bem reconhecida em outras linguagens tradicionais que implementam classes.
PHP se beneficia de OOP?
Eu sou uma das poucas pessoas que já usou PHP para uma aplicação que não seja web, em que o código todo rodava junto por horas, então o código era mais "junto". E mesmo neste caso não senti falta de nada orientado a objeto, imagine em códigos efêmeros que é o caso típico das aplicações web.
A maioria dos códigos PHP que usam classes que eu vejo por aí não precisariam ser escritos desta forma e não teriam malefícios usarem o procedural puro, desde que feito do jeito certo. Programar certo é necessário em qualquer paradigma.
Muitos dizem que assim é mais organizado. Eu até concordo que OOP pode ajudar a organizar mais o código para quem não consegue organizar de outra forma. Eu entendo que as receitas de bolo em OOP costumam ser bem organizadas e as receitas que não usam OOP costumam ser mais desorganizadas, até porque elas foram feitas em uma época que as pessoas não dominavam tanto o que estavam fazendo, mas só ajuda se a pessoa é seguidora de receita.
Se o programador vai criar programas por conta própria, ele terá que aprender fazer direito, e pode fazer organizado nos dois paradigmas, na maioria dos cenários.
Para saber mais.
Padrões de projeto e frameworks
Os padrões de projeto famosos, gerais e mais úteis e arquiteturas - tipo MVC - podem ser muito bem aplicados em OOP ou procedural.
Muitos padrões de projeto também famosos só funcionam para OOP. Mas eles existem para resolver os problemas que OOP começou impor (informação complementar nos comentários by rray). Já virou meme o abuso destes padrões específicos.
Outros existem porque a linguagem é estática. Linguagens dinâmicas, como PHP, são bem mais flexíveis e exigem menos padrões de projeto "artificiais". Estão querendo "acabar" com isto também (até gosto de linguagem estática, mas PHP é o que é por ser dinâmica).
Princípios foram criados para ajudar as pessoas usarem OOP do jeito certo, mas a maioria os desconhece ou não sabem quando usar e quando deixar de lado.
Tudo isto acrescenta complexidade para o software. Quando ele precisa disso, ótimo, esta complexidade ajuda softwares que precisam ser complexos serem mais fáceis de dar manutenção. Se não precisava disso vira apenas complicação.
Concordo que OOP ajudou criar os frameworks atuais que fazem tanto sucesso. De fato esse paradigma ajuda esse tipo de software. Eu até questiono um pouco o uso deles. Não que não tenha vantagem, eles apenas não resolvem tudo. E é comum as pessoas os adotarem porque não sabem fazer as coisas direito, o motivo é errado.
Mas em códigos mais comuns vejo poucas vantagens no seu uso.
OOP não resolve tudo
Ao contrário do que algumas pessoas acreditam, OOP tá cheio de defeitos, bem cheio, e não resolve todos os problemas. A questão é saber quando ela tem mais vantagens que desvantagens, e escolher seu uso de forma consciente, e não porque ouviu dizer (ouviu de alguém que é apaixonado pela metodologia e muitas vezes ganha dinheiro disseminando ela, ouviu que é bom para você e vai resolver todos seus problemas).
Nunca ninguém apresentou provas, ou mesmo evidências empíricas, que OOP dá mais produtividade que outros paradigmas. Pelo contrário, há pelo menos um estudo mostrando que não há ganhos. Outro mostrando que as linguagens não se beneficiam fundamentalmente desse paradigma.
Mas a análise que mais gosto é do Paul Graham quando define a mediocridade como fator determinante para o sucesso do paradigma.
OOP não reproduz o mundo real como alguns pregam.
Note bem que não estou dizendo que OOP é uma porcaria que não deveria ser usada. Algumas pessoas tendem a enxergar só esta parte do que digo e não a ponderação, até porque elas não ponderam o uso. Elas pensam: "Ou você é amigo da OOP ou é inimigo". Eu uso OOP onde precisa.
Há um problema generalizado do entendimento do que é a computação e o processo científico como um todo. Então a pessoa lê um livro que dá uma visão, compra esta visão e passa repeti-la sem saber do que está falando. E olha que eu odeio academicismos. E os melhores programadores que conheço não são formados (isso tem mudado um pouco).
Há um artigo que reúne várias críticas fundamentas sobre o uso de OOP.
Conclusão
Eu fiz várias simplificações aqui. A intenção não é escrever uma tese, é alertar e tentar fazer a pessoa refletir e procurar mais informações, até mesmo fazendo novas perguntas mais específicas, até questionando o que eu disse, assim outras pessoas podem escrever e dar uma visão plural. É ruim quando se aceita cegamente a visão de uma pessoa, mesmo que seja a minha visão. Desconfie dela também. Seja proativo, só não seja teimoso, só você perde (se as pessoas que te contratam, estas perdem por tabela).
Use ambas. Aprenda o que tem de vantagem em cada uma e aproveita as vantagens. Evite o martelo dourado.

Coloquei no GitHub para referência futura.

A: Existem muitos exemplos internet a fora de como utilizar a linguagem de forma errada, como formatação de data, utilização de funções obsoletas, código vulnerável a sql injection etc.
A linguagem da suporte aos paradigmas orientado a objetos e procedural, a definição de qual escolher fica a cargo do programador. Procedural e OO são ideias de como organizar o código ou seja é possível programar de forma procedural em linguagens '100% OO' ou 'puras'.


text:
Q: Visual Studio 2010 Designer File Not Updating Please, please do not tell me to delete the designer file and convert the page to application - I have done this and it hasn't worked
I have a user control that I have programmatically added 2 ASP hyperlink controls. I cannot get the controls to appear in the designer file.
I've tried manually adding them to the designer file, but they are removed on build.
I've searched SO and seen the solution about deleting the designer file and converting the ASCX page to an application, this has not worked.
As such, on build, the project errors as it the code cannot find my controls.
<asp:HyperLink ID="hplSiteLink2" NavigateUrl='<%# GetSiteLink(Eval("SiteName"))%>' runat="server">VIEW SITE INFO</asp:HyperLink>

        protected void GetSiteLink(object SiteName)
    {
        string sn = string.Empty;

        if (SiteName is string)
        {
            sn = SiteName.ToString();

            if (sn == "redlionnewquay")
            {
                hplSiteLink.NavigateUrl = "http://www.redlionnewquay.co.uk";
                hplSiteLink2.NavigateUrl = "http://www.redlionnewquay.co.uk";
            }
            else
            {
                hplSiteLink.NavigateUrl = "~/Venue/Home/" + Eval("SiteNameUrl");
                hplSiteLink2.NavigateUrl = "~/Venue/Home/" + Eval("SiteNameUrl");
            }
        }
    }

If you have any ideas I'd be grateful.

A: Sometimes if you remove & re-add a control, and the designer doesn't get updated, it may be due to a permissions problem - are you sure that all the files are writable, and that you have permissions?
Do you have any other user controls that work properly?  I've seen cases where the extension (ascx) for some reason loses it's associations, so VS doesn't know how to handle it properly.  If you switch views, does that make any difference?  Any chance of a name collision in the project?
Finally, if nothing else works, try deleting the user control from the project, closing Visual Studio, then re-open the solution & try adding a new one.

A: Right, I think I've solved it. I was set on the right track by other topics on this subject stating if there are any errors in your code it will not generate the designer file.
With this in mind I looked over and over the procedure and realised I was running the Eval in the if statement - which is rubbish, so I changed the code to this:
        public string GetSiteLink(object SiteName)
    {
        string sn = string.Empty;
        string sHtml = string.Empty;

        if (SiteName is string)
        {
            sn = SiteName.ToString();

            if (sn == "redlionnewquay")
            {
                sHtml = "http://www.redlionnewquay.co.uk";
            }
            else
            {
                sHtml = "~/Venue/Home/" + SiteName;
            }
        }
        return sHtml;
    }

Which solved it, although it was not obvious as the previous code compiled without error, the Eval in code behind I guess is a 'soft' error.
Thanks for your help.


text:
Q: Querydsl : build case statement with varying number of when/then pairs Using querydsl, I came across a problem where I need to generate a case statement with varying number of when/then statements and an ultimate else expression.
As described here, I have been able to generate case statement with fixed number of when/then statements easily like this-
Expression<String> cases = customer.annualSpending
    .when(10000).then("Premier")
    .when(5000).then("Gold")
    .when(2000).then("Silver")
    .otherwise("Bronze");

This is the approach I have already tried with no success-
Map<BooleanBuilder,SimplePath<?>> caseExpressionMap = new LinkedHashMap<>();
CaseBuilder.Cases<?,?> caseExpression = null;
for(BooleanBuilder expression : caseExpressionMap.keySet()){
  if(caseExpression!=null)
    caseExpression = caseExpression.when(expression).then(caseExpressionMap.get(expression));
 else
    caseExpression = new CaseBuilder().when(expression).then(caseExpressionMap.get(expression));
}
cases=cases.otherwise(...)

I ran into some type issue -

The method then(capture#19-of ?) in the type
  CaseBuilder.CaseWhen is not
  applicable for the arguments (SimplePath)

Appreciate some help here.

A: Changing the generics of CaseBuilder did the job. This code will work-
Map<BooleanBuilder,String> caseExpressionMap = new LinkedHashMap<>();
CaseBuilder.Cases<String,SimpleExpression<String>> cases = null;
for(BooleanBuilder expression : caseExpressionMap.keySet()){
  if(caseExpression!=null)
    caseExpression = caseExpression.when(expression).then(caseExpressionMap.get(expression));
 else
    caseExpression = new CaseBuilder().when(expression).then(caseExpressionMap.get(expression));
}
cases=cases.otherwise(...)


text:
Q: Umbraco MVC 6.05 Getting IPublishedContent object through Surface Controller I am developping an umbraco mvc web site and im having troubles getting currentpage info within surface controller.
Here is my scenario:
I have a products page. And there are checkboxes which filters the product list. I wrote an ajax post function which fires on checkbox change event.
$.ajax({
            type: "POST",
            url: '/umbraco/Surface/ProductsSurface/Products',
            data: JSON.stringify({ some data }),
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            traditional: true,
            cache: false,
            beforeSend: function () {
                $("#imgAjaxLoader").css("display", "inline");
            },
            complete: function () {
                $("#imgAjaxLoader").css("display", "none");
            },
            success: function (data) {
                if (data.Status != null) {
                } else {
                }
            }
        });

What i want is filter product list, reproduce product list, send this data to a template page, render this page with product list and get rendered page string, and return this string to page with Json.
This is my render razor view method :
public string RenderRazorViewToString(string viewName, object model)
    {
        ViewData.Model = model;
        using (var sw = new StringWriter())
        {
            var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
            var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
            viewResult.View.Render(viewContext, sw);
            viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
            return sw.GetStringBuilder().ToString();
        }
    }

But the problem is even if my template page is not inherited from umbraco, it still wants a  model inherited from render model. So i inherited from it.
This is my model :
public class ProductListTemplateViewModel : RenderModel
{
    //Some Properties

    public ProductListTemplateViewModel() : this(new UmbracoHelper(UmbracoContext.Current).TypedContent(UmbracoContext.Current.PageId)) { }
    public ProductListTemplateViewModel(IPublishedContent content, CultureInfo culture) : base(content, culture) { }
    public ProductListTemplateViewModel(IPublishedContent content) : base(content) { }
}

But after i did that and render page, i ve got an error says Value Cannot Be NULL
That is because IPublishedContent content object is null so i have to bind this value to my view model.
IPublishedContent iPublishedContent = CurrentPage;

While executing this code nothing happens it s not stepping next code. Its like freezes there, getting into an infinite loop.
So i cannot get value. Nothing happens no error.
I am desperate now. Any help would be great.
Thanks.


text:
Q: ms-access VBA, can't unlock locked project I`m trying to edit a project in MS-access VBA. If I right click on the project and choose Properties , VBA shows a popup: Project is unviewable.

I cant even get to the screen to unlock anything or enter the unlock password. The file is a MDB file.
How should I go about solving this?

A: I fixed the issue by opening the MDB in a Hex editor and replace DBS with DBx.
This way I was able to remove the lock.


text:
Q: optional not found in g++ I have a c++ program which is using "optional".
I have imported it with #include <optional> at the top of the file (line 4) and i'm compiling with the line g++ -std=c++17 -o name.o -c source.cpp but even so I still get this error:
source.cpp:4:20: fatal error: optional: No such file or directory
 #include <optional>
                    ^
compilation terminated.

My OS: Debian GNU/Linux 9 (stretch) 64-bit
g++ version: 6.3.0
g++ was installed with sudo apt -y install build-essential
Does anyone have any idea what could be the problem?


text:
Q: How to return result out function javascript I would like to return result from response.on in the signIn function.
const signIn = async (password) => {
  var request = new DeviceAuthQuery();
  request.setPassword(password);
  var response = client.authenticate(request, {}, (err, response) => {
      console.log("Request Sent 1111");
  });

  response.on('data', function(reply) {
      console.log("Data Received 2222");
      console.log('Data: 22222'+ reply.getAuthjwt());
      var result = reply.getAuthjwt()
      return result
  });

  return result;
}

export {
    signIn
};

A: Your result variable is out of scope.
Define var result; outside of your response.on then set result = reply.getAuthjwt().
Otherwise, I believe that you should be able to return response.on and just return reply.getAuthjwt() within your function.
const signIn = async (password) => {
  var request = new DeviceAuthQuery();
  request.setPassword(password);
  var response = client.authenticate(request, {}, (err, response) => {
      console.log("Request Sent 1111");
  });
  return response.on('data', function(reply) {
      console.log("Data Received 2222");
      console.log('Data: 22222'+ reply.getAuthjwt());
      return reply.getAuthjwt()
  });
}

export {
    signIn
};

or
const signIn = async (password) => {
  var result;
  var request = new DeviceAuthQuery();
  request.setPassword(password);
  var response = client.authenticate(request, {}, (err, response) => {
      console.log("Request Sent 1111");
  });
  response.on('data', function(reply) {
      console.log("Data Received 2222");
      console.log('Data: 22222'+ reply.getAuthjwt());
      result = reply.getAuthjwt()
  });
  return result;
}

export {
    signIn
};

I also wonder if you can use
const signIn = async (password) => {
  var result;
  var request = new DeviceAuthQuery();
  request.setPassword(password);
  client.authenticate(request, {}, (err, response) => {
      response.on('data', function(reply) {
        console.log("Data Received 2222");
        console.log('Data: 22222'+ reply.getAuthjwt());
        result = reply.getAuthjwt()
     });
  });

  return result;
}

export {
    signIn
};


text:
Q: is it possible to run a completable future in the same thread in which it is created? Would like to know if a completablefuture can be run in the thread in which it was created. You might ask why would I need to do so since completablefuture is for async programming. The reason is that I have few async tasks and some tasks that I want to run in the spawning thread so that I can use allOf etc and maintain consistency in the code

A: When you say you want to know whether "a completablefuture can be run in the thread in which it was created", you are exhibiting a wrong mindset. A CompletableFuture doesn't run. A CompletableFuture just encapsulates a value or exception, which can be set at most one time, which we call completing it.
The API offers a lot of methods for scheduling completion attempts, potentially asynchronous, but you shouldn't get distracted from the fact that you decide how to complete it.
There are simple alternatives to asynchronous completion:
CompletableFuture<String> f = CompletableFuture.completedFuture("hello");

creates an immediately completed future. Java 9 adds failedFuture to support creating an immediately exceptionally completed future.
You can also easily create a future to be completed at a later time within the same thread:
CompletableFuture<String> f = new CompletableFuture<>();

// arbitrary actions

f.complete("hello");

You can also use the factory methods with an executor, immediately running the action in the initiating thread:
CompletableFuture<String> f
  = CompletableFuture.supplyAsync(() -> "hello", Runnable::run);

or
CompletableFuture<String> f
  = CompletableFuture.supplyAsync(() -> {
    if(Math.random() > 0.5) throw new IllegalStateException();
    return "hello";
  }, Runnable::run);

to demonstrate the difference to an invocation of complete or creating an immediately completed future.
Of course, these possibilities can be combined with the other features, like allOf:
CompletableFuture<String> a = new CompletableFuture<>();
CompletableFuture<String> b = new CompletableFuture<>();
CompletableFuture<String> c = new CompletableFuture<>();

CompletableFuture.allOf(a, b, c).whenComplete((__, t) -> {
  if(t != null) System.err.println("failed with "+t);
  else System.out.println("all completed "+a.join()+", "+b.join()+", "+c.join());
});

System.out.println("step 1");
a.complete("foo");
System.out.println("step 2");
b.complete("bar");
System.out.println("step 3");
c.complete("baz");

A: Yes, perfectly possible. Here is a sample program which demonstrates
private static ExecutorService executor = Executors.newSingleThreadExecutor();

public static void main(String[] args)
{
    executor.execute(() -> {
        System.out.println("Scheduling " + Thread.currentThread().getName());
        CompletableFuture.supplyAsync(() -> {
            System.out.println("Sleeping " + Thread.currentThread().getName());
            try {
                Thread.sleep(2000);
            }
            catch (InterruptedException e) {}

            System.out.println("Returning " + Thread.currentThread().getName());
            return 123;
        },
        executor)
        .thenAccept(retValue -> System.out.println("Got value " + retValue + " " + Thread.currentThread().getName()));
    });
}

Output
Scheduling pool-1-thread-1
Sleeping pool-1-thread-1
Returning pool-1-thread-1
Got value 123 pool-1-thread-1


text:
Q: Delete data from the database while clicking an action in sweet alert Basically, I am trying to create a sweetalert delete action while we click on delete(link button) inside GridView. While I'm clicking Delete Option on Sweetalert the record is not deleting.
This is my .aspx code
<asp:LinkButton OnClientClick="return deletealert(this);" ID="LinkButton2" CommandArgument='<%#Eval("EmployeeId")%>' runat="server" CommandName="CmdDelete" Text="Delete"  />

Here's my Code Behind Fired Method
protected void `gvEmployeeDetails_RowCommand`(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "CmdEdit")
            {
                Response.Redirect("EmployeeRegistration.aspx?ItemId=" + e.CommandArgument);
            }
            else if (e.CommandName == "CmdDelete")
            {
                int EmployeeId = Convert.ToInt32(e.CommandArgument);
                obj.Remove(EmployeeId);
                GetData();
            }
        }

This is the JavaScript Code
    function deletealert(ctl) {
            // STORE HREF ATTRIBUTE OF LINK CTL (THIS) BUTTON
            var defaultAction = $(ctl).prop("href");
            // CANCEL DEFAULT LINK BEHAVIOUR
            event.preventDefault();
            swal({
                title: "Are you sure?",
                text: "You will not be able to recover this imaginary   file!",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "Yes, delete it!",
                cancelButtonText: "No, cancel plx!",
                closeOnConfirm: false,
                closeOnCancel: false
            }, function (isConfirm) {
                if (isConfirm) {
                    swal("Deleted!", "Your imaginary file has been deleted.", "success");
                    // RESUME THE DEFAULT LINK ACTION
                    eval(defaultAction);
                    return true;
                } else {
                    swal("Cancelled", "Your imaginary file is safe ", "error");
                    return false;
                }
            });

Here's my output


text:
Q: Is it possible to get the CNF out of the DNF of this expression Can i get the CNF of the following expression if i know the DNF?
I've the following expression:
$$\Bigl(\bigl(A\rightarrow (\overline A \land B) \bigr)\land \bigl((\overline A \land B)\rightarrow A\bigr)\Bigr)\rightarrow\bigl(B\land \overline B\bigr)$$
The DNF will be:
$A\rightarrow B \Rightarrow \overline A \lor B:$
$$\Rightarrow\Bigl(\bigl(\overline A \lor(\overline A \land B)\bigr)\land \bigl((A\lor\overline B)\lor A\bigr)\Bigr)\rightarrow \bigl(B\land \overline B\bigr)$$
$\overline A \lor(\overline A \land B) \Rightarrow \overline A$
$(A\lor\overline B)\lor A \Rightarrow A\lor\overline B$
$$\Rightarrow \bigl(\overline A\land (A\lor \overline B)\bigr)\rightarrow (B\land \overline B) $$
$A\rightarrow B \Rightarrow \overline A \lor B:$
$$\Rightarrow\overline{\bigl(\overline A \land(A\lor\overline B)\bigr)}$$
$$\Rightarrow \bigl( A\lor(\overline A\land B)\bigr)$$
$$\Rightarrow (A\lor B)$$
So, As we can see, The DNF of this expression is $A\lor B$, My question: Is it correct to say that the CNF of this expression will be $\overline A\land \overline B$?
I looked at Graham Kemp's Answer for this question, And didn't successfully understood how an expression that has only the operator $\land$ can be both conjunction of two disjunctions of one literal and disjunction of two conjunctions of one literal at the same time.
Because as i know (Please correct me if i wrong), A CNF has the form of $A\land B\land C\land D$ Where $A,B,C,D$ are expressions of the form $x\lor y\lor z$, And DNF has the form of $A\lor B\lor C\lor D$ Where $A,B,C,D$ are expressions of the form $x\land y\land z$.
Thanks for reading the question so far, please correct me if i made any mistake.
Thanks!!!

A: First, the CNF of any expression is equivalent to that expression, and same for the DNF, meaning that the CNF and DNF should always be equivalent to each other as well.
So, if the DNF is $A \lor B$, then the CNF  cannot be $\neg A \land \neg B$, since that is the negation of it, i.e. not something that is equivalent.
Ok, so then what is the CNF?
Well, the CNF is just $A \lor B$ as well.  Think of it as a conjunctin that consists of a single conjunct. And, since that conjunct is a disjunctin of literals, it fits the definition of CNF just fine.


text:
Q: why does JSONDeserializer exclude xml tag from json input string I've below json string
{"metadata":"<xml><item><name>Memory</name><Fullname>NULL</Fullname></item></xml>"}

when I deserialize this using flexjson it is excluding all xml tags from above json and give this value "Memory NULL"


text:
Q: How to have a OR search while aggregating in Elasticsearch? I have this query which gets the aggregation of the mentions field for all the tweets with the text "CAT DOG". How can I edit my query such that I get the aggregation for all the tweets containing either "cat" or "dog".
{
    "size": 0,
    "query": {
        "filtered": {
           "query": {
                "match_all": {}
           },
           "filter": {"text" : "CAT DOG"}
        }
    },
    "aggs": {
        "tweet": {
            "terms": {
                "field": "hashtags",
                "size" : 50
            }
        }
    }
}

A: You need to use should query.
If something not clear fill free to ask.
Please attention to elasticsearch version.

A: Look to multi_match query it has option operator you should set it to or which means that any should match.
{
    "size": 0,
    "query": {
       "multi_match" : {
         "query":      "CAT DOG",
         "fields":     [ "text"],
         "operator":   "or"
     }
  },
    "aggs": {
        "tweet": {
            "terms": {
                "field": "hashtags",
                "size" : 50
            }
        }
    }
}

Other option in your case is bool query, but you should be aware that it will search for terms it means that if you are using default analyzer it will lowercase tokens and to match them you must lowercase user input, also you are responsible to split tokens from user input.
{
    "size": 0,
    "query": {
      "bool" : {
      "should" : [
        { "term" : { "text": "cat" } },
        { "term" : { "text" : "dog" } }
      ],
    }
  }
  },
    "aggs": {
        "tweet": {
            "terms": {
                "field": "hashtags",
                "size" : 50
            }
        }
    }
}


text:
Q: Dev Platform of choice for Windows and OS X desktop apps I'm about to write a small desktop app that should run on Windows and Mac OS X mainly. The choices I have so far are:

*

*I usually use Java + Swing for this type of stuff, but this app should be really tiny (about 1Mb) and I don't want to embed the ~26mb JRE on the Windows version or ask users to have it installed.

*I have good experience with Flex and AIR and users of this app will eventually use the Flash player (the app will output swf files most of the time). But performance is important (kinda), and I would like to write an app that have native look-and-feel.

*I've been also considering realBasic. It seems promising and easy to get started with. But, I really do not want to write basic. It's been a very long time since I wrote basic programs (about 10 years). Plus, I can't find many supporters of it.

I don't have any working experience in C/C++. And this is a very small project that I would like to finish in about a month. Any suggestions?

A: REALbasic can be a great way to create cross-platform apps.  The language is fully object-oriented and resembles Java far more than it does any version of BASIC that you may have used.
REALbasic does compile to native apps with a native look-and-feel, but the executables are not small.  Even an empty app will be more than 1MB.
However, given your app will output Flash files, it seems like Flex/AIR might make the most sense for this project.

A: I would say stick with Java + Swing, unlike contrary belief you can have great looking programs using swing. You need to put in some effort to set some properties and make sure where you create files depending on the os your on but it is much less work then say C++ or C.
Even if you do nothing you application will look the same and work on all major os's (Linux,Windows,Mac Os X).
For some reference check out mac-widgets these are no different from the os x supplied counterparts. The guy also has a blog where he explains how he did it. In java your can override anything to shape it into the way you want it to look.
As for JRE install os x comes pre installed with java no problem there for Windows you can use a exe wrapper and it checks the correct JRE and installs it for you, but as it's already pointed out most computer have java pre installed.

A: If you want a single code base running easily on both Windows and OS X you basically have two choices:

*

*Java

*a Web Application.

I have good experiences with the Java path.  Programs run reasonably well, and you have much power in the Swing GUI (but it takes some getting used to).  If you use Java Web Start for launching you have control on the deployment, users are easily prompted to download the JRE (the latest version is a much smaller download), and you can either go for the Nimbus look and feel (which I think is really nice) or a platform specific look and feel with a single line in your main method.
The only downside as I see it, is the JRE download.   I would accept that and get on with the project :)  You will not get anything better without a LOT of elbow grease.

A: Is the JRE really that rare among your Windows based target users? I'm fairly sure most manufactures now ship a recent version of Java on their machines. If it rare then using SWT and compiling to native might be an option¹.
¹ - SWT as (as I understand it) compiling the Swing stuff to native basically means you need the whole JRE. My failing memory tells me that this is due to some odd licence requirements.

A: How well would a web-app work for you? These days, the GUI capabilities of the browser is good enough for most things (provided the browser is not IE) other than high definition real time graphics like games. things like http://labs.mozilla.com/prism/ might fit the bill?


text:
Q: jsp, servlets, faces and beans? i´ve read a little about java's structure and could someone tell me if my view of all these components are correct:
JSP corresponds a View
Servlet corresponds a Controller
Bean corresponds a Model
Faces correspond layouts to render display

is this roughly correct?

A: JSPs are view technology - HTML with Java embedded in it.
Servlets should be used as controllers - they're Java classes that implement methods to read and write HTTP streams.
In a web app Javabeans are usually the model - JSPs and other Java view technologies understand how to access properties of Javabeans, bind them to forms, etc.
Faces is a separate stack JSF (Java Server Faces) is a component based web framework.

A: Yes, you're roughly correct.
Only, the Faces is more than just "layouts to render a display". JSF is a full fledged component based MVC framework which is built on top of the Servlet API. It uses the FacesServlet as the sole controller. It used to use JSP as view technology, which is now replaced by Facelets (XHTML) as per the new JSF 2.0 API. It uses the so-called backing beans as model. Then, you have taglibs/components which can be used in the view layer to generate HTML and uses Expression Language to associate the data/events with the model objects (the managed beans).


text:
Q: How to insert one more item in a json existing structure with gson? The code below generates correctly the first structure of the json file.
gson = new GsonBuilder().setPrettyPrinting().create();

AudDetHeader AudDetHeader = new AudDetHeader();

//ArrayList<OrderDetail> AudDetList = new ArrayList<OrderDetail>();
Map<String, AudDet> AudDetList = new HashMap<String, AudDet>();

AudDet AudDet = new AudDet();
AudDet.setLineId("1");
AudDet.setItemNumber("ABC");
AudDet.setQuantity(9);
AudDet.setPrice(10.00);

List<String> phones = new ArrayList<String>();
phones.add("24530001");
phones.add("24530002");
phones.add("24530003");
AudDet.setPhones(phones);

AudDetList.put("teste 2", AudDet);
AudDetHeader.setAudDetList(AudDetList);

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonString = gson.toJson(AudDetHeader);

BufferedWriter bufferedWriter = null;
try {

    File file = new File(Environment.getExternalStorageDirectory() + "/download/test/test.json");
    if(!file.exists()){
        file.createNewFile();
    }

    FileWriter fileWriter = new FileWriter(file);
    bufferedWriter = new BufferedWriter(fileWriter);
    bufferedWriter.write(jsonString);

} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        if (bufferedWriter != null){
            bufferedWriter.close();
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

The result of the code:
{
  "Results": {
    "teste 2": {
      "itemNumber": "ABC",
      "lineId": "1",
      "phones": [
        "24530001",
        "24530002",
        "24530003"
      ],
      "price": 10.0,
      "quantity": 9
    }
  }
}

I want to add a new item. My desire is to stay as the structure below.
{
   "Results":{
      "teste 2":{
         "itemNumber":"ABC",
         "lineId":"1",
         "phones":[
            "24530001",
            "24530002",
            "24530003"
         ],
         "price":10.0,
         "quantity":9
      },
      "teste 3":{
         "itemNumber":"DEF",
         "lineId":"2",
         "phones":[
            "30303030",
            "40404040",
            "505050"
         ],
         "price":11.0,
         "quantity":12
      }
   }
}

The AudDetHeader.class
public class AuditoriaDetalheHeader {

@SerializedName("Results")
private Map<String, AuditoriaDetalhe> AuditoriaDetalheList;
    ...
}

The AudDet.class
public class AuditoriaDetalhe {

 String lineId = null;
 String itemNumber = null;
 int quantity = 0;
 Double price = null;
 List<String> phones = new ArrayList<String>();
     ...
}

A: Worked for me with this code!!!
Main class
private static File fileJson = new File(Environment.getExternalStorageDirectory() + "/download/test/test.json");

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.teste_criajson);

createJsonStructure();

Button btnSave = (Button)findViewById(R.id.btSave);

btnSalvar.setOnClickListener( new View.OnClickListener() {
    public void onClick(View v) {

        try {
            String strFileJson = getStringFromFile(fileJson.toString());
            JSONObject jsonObj = new JSONObject(strFileJson);
            Gson gson = new Gson();
            JsonParser jsonParser = new JsonParser();
            String idAud = "10";

            AudDet ad = new AudDet();
            ad.setLineId("2");
            ad.setItemNumber("DEF");
            ad.setQuantity(22);
            ad.setPrice(22.22);

            List<String> phones = new ArrayList<String>();
            phones.add("22");
            phones.add("22");
            phones.add("22");
            ad.setPhones(phones);

            String jsonStr = jsonParser.parse(gson.toJson(ad)).toString();
            JSONObject JSONObject = new JSONObject(jsonStr);
            jsonObj.getJSONObject("Results").put(idAud, JSONObject);

            writeJsonFile(fileJson, jsonObj.toString());

        } catch (Exception e1) {
            e1.printStackTrace();
        }

    }
});

If do not exists json file, then i create with basic structure for insert the itens.
public static void createJsonStructure(){
    if(!fileJson.exists()){
        try {
            fileJson.createNewFile();

            String jsonString = "{\"Results\":{}}";

            writeJsonFile(fileJson, jsonString);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Open the json file to get the string format, and prepare to insert a new item:
public static String getStringFromFile (String filePath) throws Exception {
    File fl = new File(filePath);
    FileInputStream fin = new FileInputStream(fl);
    String ret = convertStreamToString(fin);
    //Make sure you close all streams.
    fin.close();
    return ret;
}
public static String convertStreamToString(InputStream is) throws Exception {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
      sb.append(line).append("\n");
    }
    return sb.toString();
}

Writes into the json file that already exists:
public static void writeJsonFile(File file, String json)
{
    BufferedWriter bufferedWriter = null;
    try {

        if(!file.exists()){
            file.createNewFile();
        }

        FileWriter fileWriter = new FileWriter(file);
        bufferedWriter = new BufferedWriter(fileWriter);
        bufferedWriter.write(json);

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (bufferedWriter != null){
                bufferedWriter.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}


text:
Q: Run Node.js next to IIS We are currently hosting a website on a server on port 80. Alongside that we would like to have a Node.js application running on the same port.
I already tried to use IISNode and run it as an application within the site, but without succes.
I keep getting the following error:
HRESULT: 0x2
HTTP status: 500
HTTP subStatus: 1001
HTTP reason: Internal Server Error
I was wondering wether anyone has accomplished the same with less effort?
Thanks


text:
Q: Optimizing Script for Downloading Files from Library with Folders Due to some extenuating circumstances we had to resort to migrating a teams content from one farm to another via locally downloading the files from their lists and shipping them. Unfortunately, this team used folders in their lists VERY heavily. And they wanted to maintain their folder structure for document organization purposes, so I had to come up with a script that could download the contents of a list, folders and all, while also maintaining that folder structure. I have years of SP admin experience, but my PS scripting has always been very basic to intermediate usage at best so I am reaching out to you all to help me optimize this script.
add-pssnapin microsoft.sharepoint.powershell
$w=get-spweb "http://URL"
$tlfolder=$w.getfolder("Old_Surveys")
$subfold=$tlfolder.subfolders|select *|?{$_.name -match "historical"}
$subfolders=$subfold.subfolders
foreach ($subfolder in $subfolders)
{
    new-item -path "D:\backups\Old_Surveys\Historical Company Surveys" -name $subfolder.name -itemtype "directory"

    #if the 2 level sub folder exists
    if ($subfolder.subfolders -ne $null)
    {
        $subfoldername=$subfolder.name

        $subsubfolders=$subfolder.subfolders
        foreach ($subsubfolder in $subsubfolders)
        {
            new-item -path "D:\backups\Old_Surveys\Historical Company Surveys\$subfoldername" -name $subsubfolder.name -itemtype "directory"

            # if the 3 level sub folder exists
            if ($subsubfolder.subfolders -ne $null)
            {
                $subsubfoldername=$subsubfolder.name

                $subsubsubfolders=$subsubfolder.subfolders
                foreach ($subsubsubfolder in $subsubsubfolders)
                    {
                        new-item -path "D:\backups\Old_Surveys\Historical Company Surveys\$subfoldername\$subsubfoldername" -name $subsubsubfolder.name -itemtype "directory"

                        #if the 3 level sub files exists
                        if ($subsubsubfolder.files -ne $null)
                        {
                            $subsubsubfiles=$subsubsubfolder.files
                            $subsubsubfoldername=$subsubsubfolder.name
                            foreach ($subsubsubfile in $subsubsubfiles)
                                {
                                    write-host $subsubsubfile.name
                                    $b=$subsubsubfile.openbinary()
                                    $fs=new-object system.io.filestream(("d:\backups\Old_Surveys\Historical Company Surveys\$subfoldername\$subsubfoldername\$subsubsubfoldername"+$subsubsubfile.name), [system.io.filemode]::create)
                                    $bw=new-object system.io.binarywriter($fs)
                                    $bw.write($b)
                                    $bw.close()
                                }
                        }
                    }
            }
            if ($subsubfolder.files -ne $null)
                   {
                        $subsubfiles=$subsubfolder.files
                        $subsubfoldername=$subsubfolder.name
                        foreach ($subsubfile in $subsubfiles)
                            {
                                write-host $subsubfile.name
                                $b=$subsubfile.openbinary()
                                $fs=new-object system.io.filestream(("d:\backups\Old_Surveys\Historical Company Surveys\$subfoldername\$subsubfoldername\"+$subsubfile.name), [system.io.filemode]::create)
                                $bw=new-object system.io.binarywriter($fs)
                                $bw.write($b)
                                $bw.close()
                            }
                    }
             }
        if ($subfolder.files -ne $null)
        {
            $subfiles=$subfolder.files
            $subfoldername=$subfolder.name
            foreach ($subfile in $subfiles)
                {
                    write-host $subfile.name
                    $b=$subfile.openbinary()
                    $fs=new-object system.io.filestream(("d:\backups\Old_Surveys\Historical Company Surveys\$subfoldername\"+$subfile.name), [system.io.filemode]::create)
                    $bw=new-object system.io.binarywriter($fs)
                    $bw.write($b)
                    $bw.close()
                }
        }
    }
}

The objective of the code was to iterate down thru any folders, and subfolders of the folders, and create them on the local drive and download any files that are in them at that level. I did this manually for up to 3-sub levels of folders, but if there are more levels lower than that then I would have had to keep manually adding all the code and going even longer. Surely there has to be a better way of doing this?


text:
Q: Want to delete some elements from a list that is existed in another list I have a list suppose
listA=[679,890,907,780,5230,781]

and want to delete some elements that is existed in another
listB=[907,5230]

in minimum time complexity?
I can do this problem by using two "for loops" means O(n2) time complexity, but I want to reduce this complexity to O(nlog(n)) or O(n)?
Is it possible?

A: It's possible - if one of the lists is sorted. Assuming that list A is sorted and list B is unsorted, with respective dimensions M and N, the minimum time complexity to remove all of list B's elements from list A will be O((N+M)*log(M)). The way you can achieve this is by binary search - each lookup for an element in list A takes O(log(M)) time, and there are N lookups (one for each element in list B). Since it takes O(M*log(M)) time to sort A, it's more efficient for huge lists to sort and then remove all elements, with total time complexity O((N+M)*log(M)).
On the other hand, if you don't have a sorted list, just use Collection.removeAll, which has a time complexity of O(M*N) in this case. The reason for this time complexity is that removeAll does (by default) something like the following pseudocode:
public boolean removeAll(Collection<?> other)
    for each elem in this list
        if other contains elem
            remove elem from this list

Since contains has a time complexity of O(N) for lists, and you end up doing M iterations, this takes O(M*N) time in total.
Finally, if you want to minimize the time complexity of removeAll (with possibly degraded real world performance) you can do the following:
List<Integer> a = ...
List<Integer> b = ...
HashSet<Integer> lookup = new HashSet<>(b);
a.removeAll(lookup);

For bad values of b, the time to construct lookup could take up to time O(N*log(N)), as shown here (see "pathologically distributed keys"). After that, invoking removeAll will take O(1) for contains over M iterations, taking O(M) time to execute. Therefore, the time complexity of this approach is O(M + N*log(N)).
So, there are three approaches here. One provides you with time complexity O((N+M)*log(M)), another provides you with time complexity O(M*N), and the last provides you with time complexity O(M + N*log(N)). Considering that the first and last approaches are similar in time complexity (as log tends to be very small even for large numbers), I would suggest going with the naive O(M*N) for small inputs, and the simplest O(M + N*log(N)) for medium-sized inputs. At the point where your memory usage starts to suffer from creating a HashSet to store the elements of B (very large inputs), I would finally switch to the more complex O((N+M)*log(M)) approach.
You can find an AbstractCollection.removeAll implementation here.
Edit:
The first approach doesn't work so well for ArrayLists - removing from the middle of list A takes O(M) time, apparently. Instead, sort list B (O(N*log(N))), and iterate through list A, removing items as appropriate. This takes O((M+N)*log(N)) time and is better than the O(M*N*log(M)) that you end up with when using an ArrayList. Unfortunately, the "removing items as appropriate" part of this algorithm requires that you create data to store the non-removed elements in O(M), as you don't have access to the internal data array of list A. In this case, it's strictly better to go with the HashSet approach. This is because (1) the time complexity of O((M+N)*log(N)) is actually worse than the time complexity for the HashSet method, and (2) the new algorithm doesn't save on memory. Therefore, only use the first approach when you have a List with O(1) time for removal (e.g. LinkedList) and a large amount of data. Otherwise, use removeAll. It's simpler, often faster, and supported by library designers (e.g. ArrayList has a custom removeAll implementation that allows it to take linear instead of quadratic time using negligible extra memory).

A: You can achieve this in following way
Sort second list( you can sort any one of the list. Here I have sorted second list). After that loop through first array and for each element of first array, do binary search in second array.
You can sort list by using Collections.sort() method.
Total complexity:-
For sorting :- O(mLogm) where m is size of second array. I have sorted only second array.
For removing :- O(nLogm)


text:
Q: php mongo client get yesterday recrods Could someone please let me know how to get yesterday records in Mongo DB using PHP Mongo client class.
Here is what I have tried but the result is 0(there are already records in yesterday date), I think I'm doing wrong.
$date = date('Y-m-d', strtotime("-1 days"));
$fromDate = $date." 00:00:00";
$toDate   = $date." 23:59:59";

$filters  = array(
                'orderDate'=>array(
                            '$lt'=>$fromDate,
                            '$gte'=>$toDate,
                       )
               );
$records  = $transCollec->find($filters);
echo $records->count(); //0

Update
I'm saving order date this way in mongo:
//This date is comming from third party
$transactionDate = new Zend_Date($transactionApi["Stat"]["datetime"], 'yyyy-MM-dd HH:mm:ss', 'en');
//this will save into mongodb
$transaction['orderDate'] = $transactionDate->toString("yyyy-MM-dd HH:mm:ss");
orderDate=date("Y-m-d H:i:s")

A: based on the posted question, the thing that immediately is noticeable is, you are trying to find records of previous day, but your condition is not matching, values of $lt and $gte need to be swapped, like:
$date = date('Y-m-d', strtotime("-1 days"));
$fromDate = $date." 00:00:00";
$toDate   = $date." 23:59:59";

$filters  = array(
    'orderDate'=> array(
        '$lt' => $toDate, //changed
        '$gte' => $fromDate, //changed
    )
);
$records  = $transCollec->find($filters);
echo $records->count();


text:
Q: Choose between facebook app and browser? I created a preference and I want back to my facebook page. I would like to click a user has the option to choose between the facebook app and the browser. Now part of the browser directly. The code is:
Facebook = (Preference) this.findPreference("facebook");
Facebook.setOnPreferenceClickListener( new OnPreferenceClickListener() {
    public boolean onPreferenceClick (Preference preference) {

Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/MyPageName"));
startActivity(browserIntent);
return false;
}
    });

A: This is how I check if Google Maps is installed. Modified for checking the Facebook app status.
// CHECK IF THE FACEBOOK APP IS INSTALLED
PackageManager pkManager = activity.getPackageManager();
try {
    PackageInfo pkgInfo = pkManager.getPackageInfo("com.facebook.katana", 0);
    String getPkgInfo = pkgInfo.toString();

    if (getPkgInfo.equals("com.facebook.katana"))   {
        // OPEN THE PAGE IN THE FACEBOOK APP
        String strPage = "fb://profile/" + YOUR_PAGE_ID;

        // CHECK IF THE "fb://profile/" IS CORRECT | REPLACE WITH "fb://page/"
        // NOT ENTIRELY SURE WHICH ONE WORKS

        Intent showPageInFB = new Intent(Intent.ACTION_VIEW, Uri.parse(strPage));
        startActivity(showPageInFB );
    } else {
        // OPEN THE PAGE IN A BROWSER
        Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/MyPageName"));
        startActivity(browserIntent);
    }
} catch (NameNotFoundException e) {
    e.printStackTrace();
}


text:
Q: Transform / rectify unprojected raster using target extent co-ordinates I have many unreferenced raster tiles that I am trying to procedurally georectify. For each tile I know the exact extent co-ordinates (xmin, xmax, ymin, ymax) in my target CRS.
How can I transform these rasters, translating their arbitrary pixel-based co-ordinates (e.g 0,0 | 0,1280 | etc.) to match those calculated from my extent values?
All the GRASS tools seem to want manually generated GCPs and I'm unsure which GDAL tools would be suitable, given the raster tiles are unprojected.
I am looking for python / command line solutions on OSX.

A: You can store the ground control points into your raw image with gdal_translate http://www.gdal.org/gdal_translate.html and if you want to warp the image into a north-up version you can do that with gdalwarp http://www.gdal.org/gdalwarp.html.
Usage:
gdal_translate -of VRT-gcp x y easting northing -gcp x y easting northing -gpc x y easting northing -gcp x y easting northing input.tif referenced_with_ground_control_points.vrt

The VRT file is a small xml file and you can open it now with QGIS and your image will appear georeferenced. But if you want to warp it physically materialize the VRT into a Geotiff. If the CRS of your ground control points were in EPSG:4326 the command would look like
gdalwarp -of GTiff -co tiled=yes -s_srs epsg:4326 -t_srs epsg:4326 referenced_with_ground_control_points.vrt warped.tif

There are many options in gdalwarp so read the manual page and make some tests with your own data.
It is also possible to do the same with GDAL and Python.

A: Besides the gdal_translate / VRT approach you can also use r.region to set the boundary definitions for a raster map.
You can assign to each unreferenced raster tile the N, S, W, E boundaries. See the manual page for an example.


text:
Q: ADF test, PP test, KPSS test: Which test to prefer? If a time series is tested for Unit Root (by ADF, PP, KPSS,...) problem is detected with some tests and not found by others. Which one is preferred? For example if ADF says us that there is a Unit root and PP says that is not problem. Which one of them would be preferred?

A: Generally, if there are multiple statistical tests that apply for the same thing and work differently, then a single significant result leads to rejection. It follows from the logic of hypothesis testing theory that failing to reject means that there has not been enough evidence. This is how normality is often tested.

A: I answered two verisimilar question:

*

*Contradictory results of ADF and KPSS unit root tests

*What is the difference between a stationary test and a unit root test?
(I summarized the most relevant part of this answer below)

How unit-root test and stationarity-test complement each other
If you have a time series data set how it usually appears in econometric time series I propose you should apply both a Unit root test: (Augmented) Dickey Fuller or Phillips-Perron depending on the structure of the underlying data and a KPSS test.
Case 1 Unit root test: you can't reject H0; KPSS test: reject H0. Both imply that series has unit root.
Case 2 Unit root test: Reject H0. KPSS test: don`t reject H0. Both imply that series is stationary.
Case 3 If we can't reject both test: data give not enough observations.
Case 4 Reject unit root, reject stationarity: both hypothesis are component hypothesis – heteroskedasticity in series may make a big difference; if there is structural break it will affect inference.
Power problem: if there is small random walk component (small variance σ 2 u ), we can't reject unit root and can't reject stationarity.
Economics: if the series is highly persistence we can't reject H0 (unit root) – highly persistent may be even without unit root but it also means we shouldn't treat/take data in levels.
General rule about statistical testing You cannot proof a null hypothesis you can only affirm it. However if you reject a null hypothesis you can be very sure that the null hypothesis is really not true. Thus alternative hypothesis is always a stronger hypothesis than the null hypothesis.


text:
Q: Android - rendering same video on Multiple views I have a media datasource, and I am playing the media using android MediaPlayer.
How can I display the video output from the MediaPlayer to multiple views in the same Activity, is there any alternative ways to do this?
I want the video part of the media to be rendered in two different views without reading multiple times from data source.
Current Code :
TextureView mTextureView1;
TextureView mTextureView2;

mTextureView1.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
        @Override
        public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
            mMediaPlayer = new MediaPlayer(AppActivity.this);
            try {
                mMediaPlayer.setDataSource(getApplicationContext(), Uri.parse(path));
            } catch (IOException e) {
                e.printStackTrace();
            }
            mMediaPlayer.setSurface(new Surface(surface));
            mMediaPlayer.setLooping(true);
            mMediaPlayer.prepareAsync();

            mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mp.start();
                }
            });
        }

A: You're currently playing into a TextureView, which receives the frames in a SurfaceTexture and then renders them onto the View UI layer.
One approach is to create your own SurfaceTexture to receive the frames, and then use OpenGL ES to render the frames however you like.  For an example, see the "texture from camera" activity in Grafika.  It can position, rotate, and scale the input from the camera; you can easily change this to receive input from the MediaPlayer, and render the texture twice onto a SurfaceView.
If you want to render it onto different Views, you could set up a couple of TextureViews and render to them.  Use a single EGL context with a different EGL surface for each View.


text:
Q: Passar match.params para dentro de outro componente Estou com o seguinte problema:
Tenho um componente de step e dentro desse componente tenho outro componente chamado form que renderiza um dos passos do step.
Pois bem, no step eu consigo obter o id passado com o código this.props.match.params.id só que nesse step eu tenho outro componente chamado form e nesse form eu perco a referência do id passado para o step.
Eu sei que poderia mudar na rota para que chamasse direto o form e assim eu teria o id, mas preciso que seja renderizado o setp e dentro dele o form.
Como faço pra passar o id do step para o form?
Minha rota está assim:
<Route path="/stepAluno/(new|edit)/:id?" component={StepAluno} />

A: Consegui resolver da seguinte forma:
depois de obter o id pelo match.params, passei o id via props para o componente form.


text:
Q: Checklist database design. One to many relationship and storing user information I am basically designing a web checklist. The process is as follows: User logs in, selects the "Job Name" for a list, clicks on it, goes to next page, selects "Procedure list" from a list, clicks on it, goes to next page, there he sees a checklist where he can basically add comments, and click check box on individual listings.
I know how to code most of it, but at the moment i'm trying to figure out how to setup the
relationships + what extra tables to add to hold the information.
General layout I have at the moment:
Table: User_list
User_ID
Username

Table: Job_list
Job_ID
Job Name

Table: Procedure_List
Procedure_ID
Procedure Name
Job_ID

Table: Check_List
Job_ID
Checklist_ID
Description

Job_ID -> Procedure_ID -> Checklist_ID is one to many... but how to add the user list in order to store all the changes done by the user.
So you can basically have one page where you see:
Job Name
Procedure
Checklist done

and all the details done by the users.

A: I'm assuming the relationships are Job 1:m Procedure 1:m Checklist. And a user may choose any number of jobs. The combination of Job/Procedure/Checklist is chosen by the user. For example, I assume a Job may have 10 associated procedures and the user selects 1 or more of these. Same for Procedure: A given procedure has certain checklists associated with it and the user may select any number of these checklists.
Use "join tables".

*

*User_Job table. A user may be associated with any job or any number of jobs. The user_ID and job_ID go into the User_Job table. Make the primary key the User_ID + job_ID.

*Job_Procedure table. Put the User_Job key (both columns) and procedure_id in this table. Make the primary key User_ID, Job_ID, Procedure_ID

*Procedure_Checklist table. Put the Job_procedure key (all columns) & the checklist_id in this table. Make the primary key a compound using all the columns.

Primary Keys thoughts
A sequence number for a primary key for each table will limit the number of columns in the related tables. However this key has no real meaning and if you're looking at the Procedure_Checklist table, for example, you cannot tell which job & user without querying the other tables - PITA. It's also meaningless to sort such a key. And it does not prevent duplicate rows.