text:
Q: How to clear React Json Array with a custom input hook I am a learning react and have hit a snag. I have created a custom hook to handle all my input which works fine but am having trouble clearing the form after submit. Here is my custom input hook.
export function useFormFields(initialState) {
  const [fields, setValues] = useState(initialState);

  return [
    fields,
    function(event) {
      try {
        const { name, value, type, checked } = event.target;
        setValues({
          ...fields,
          [name]: type === "checkbox" ? checked : value,
        });
      } catch (err) {
        console.log(err);
      }
    },
  ];
}

This is how am calling the react hook in my component.
function NewMachine() {
  let data = {
    user_level:"",
    name: "",
    email: "",
  };
  let [formData, setFormData] = useFormFields(data);
  const [reset, setReset] = useState(false)
   const handleSubmit = (e) => {
    e.preventDefault();
    console.log(formData);
    setFormData(data);//getting error here

  };
  return (

    <form onSubmit={handleSubmit} autoComplete="off">
     <input
                      placeholder="Enter Name"
                      className="form-control"
                      id="name"
                      name="name"
                      onChange={setFormData}
                      required
                    />
                    ...>other fields
                          <button className="float-right btn btn-secondary" type="submit">

                Create New User
              </button>
    </form>

    );

This is the error am getting

A: You're passing a object with the new values and it is expecting a React.ChangeEvent which has a target with the name, value, type, checked values.
Something you can do is check if the event is a actual React Event. If it is a actual event do your event.target stuff else just set the values.
return [
  fields,
  function (event) {
    if ("_reactName" in event) {
      // the check
      try {
        const { name, value, type, checked } = event.target;
        setValues({
          ...fields,
          [name]: type === "checkbox" ? checked : value,
        });
      } catch (err) {
        console.warn(err);
      }
    } else {
      setValues(event);
    }
  },
];

Note that currently the input has no value prop so when resetting the values it will not update the input.
return (

    <form onSubmit={handleSubmit} autoComplete="off">
      <input
        placeholder="Enter Name"
        className="form-control"
        id="name"
        name="name"
        value={fields["name"]} // add this here
        onChange={onChange}
        required
      />
      <button className="float-right btn btn-secondary" type="submit">
        Create New User
      </button>
    </form>

);

This is a way you could go but I recommend creating a reset function which you return from the hook to handle the resetting. Since we're returning multiple values we can return them as a object {} instead of a array, in case we don't need the reset in some other form.
function useFormFields(initialState) {
  const [fields, setValues] = useState(initialState);

  const reset = (newValues = initialState) => {
    setValues(newValues);
  };

  const onChange = (event) => {
    try {
      const { name, value, type, checked } = event.target;
      setValues({
        ...fields,
        [name]: type === "checkbox" ? checked : value,
      });
    } catch (err) {
      console.error(err);
    }
  };

  return { fields, onChange, reset };
}

Which you can use like
let { fields, onChange, reset } = useFormFields(data);
const handleSubmit = (e) => {
  e.preventDefault();
  console.log(fields);
  reset(data);
  // reset(); // or like this since the default values to reset to is the initialState
};
return (

    <form onSubmit={handleSubmit} autoComplete="off">
      <input
        placeholder="Enter Name"
        className="form-control"
        id="name"
        name="name"
        value={fields["name"]}
        onChange={onChange}
        required
      />
      <button className="float-right btn btn-secondary" type="submit">
        Create New User
      </button>
    </form>

);


text:
Q: What pattern to use, when relating objects by composition, to facilitate communication between the objects Say I have a python class: Foo(), that has a member self.bar which is assigned at initialisation of Foo() to be an instance of Bar(). So something like this:
class Foo:
    def __init__(self):
        self.bar = Bar()
        self.other_member = 0

Then say I bind some method of Bar() to a signal/callback and when triggered (externally) I want it to make a change to some other member of Foo().
My question is: is this a crazy thing to want to do? And if not, is there an advised pattern to follow when implementing something like this?

A: U can use Inheritance to establish Trait behavior, and register newly-created container objects to Trait static variables.
In this example:

*

*Parent class Trait is where all the logic resides.

*Define trait specific behavior in child classes inheriting from Trait, e.g Trait_Meow.

*Use composition to tie each animal class to its traits.

*U can reference the container objects of class Cat from inside trait events (methods) using self.animal().

from weakref import WeakSet, ref as weakref

class Trait:
  def register_animal(self):
    try:
      self.__class__.live_animals.add(self)
    except AttributeError as e:
      self.__class__.live_animals = WeakSet([self])

  def __init__(self, animal):
    self.animal = weakref(animal)
    self.register_animal()

class Trait_Meow(Trait):
  def meow(self):
    print('{} says: meoooooow'.format(self.animal().name))

  def all_meow():
    for animal in Trait_Meow.live_animals:
      animal.meow()

class Cat:
  def __init__(self, name):
    self.name = name
    self.traits = set([Trait_Meow(self)])

if __name__ == '__main__':
  cat1 = Cat('cat1')
  cat2 = Cat('cat2')

  Trait_Meow.all_meow()

# output
# cat2 says: meoooooow
# cat1 says: meoooooow

redpajama_set_name: RedPajamaStackExchange


text:
Q: Fetch file name from another path unix How can i grep file name (which is in another path).
Example:
My file is in a directory
/export/home/test -> under this directory i do have a file called file_test
I want to grep for a file name file_test  from another path /export/home, how could this be done?

A: Do you mean sym-links?
You can register one like this:
ln -s /export/home/test /export/home
Generic way:
ln -s <destination> <link-name>

A: you can use ls /export/home/file_test for that.
man ls


text:
Q: No view found for a Drawer Screen in android What i am doing:: I am inflating the menu drawer activity in this screen
What is happening:: I am getting the error as shown in log as no view,
What is happening & How to resolve this

MainActivity.java
public class MainActivity extends FragmentActivity {
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;

    // nav drawer title
    private CharSequence mDrawerTitle;

    // used to store app title
    private CharSequence mTitle;

    // slide menu items
    private String[] navMenuTitles;
    private TypedArray navMenuIcons;

    private ArrayList<NavDrawerItem> navDrawerItems;
    private NavDrawerListAdapter adapter;

    FragmentTransaction ft;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.hive_activity_main);

        mTitle = mDrawerTitle = getTitle();

        // load slide menu items
        navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);

        // nav drawer icons from resources
        navMenuIcons = getResources()
                .obtainTypedArray(R.array.nav_drawer_icons);

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.list_slidermenu);

        navDrawerItems = new ArrayList<NavDrawerItem>();

        // adding nav drawer items to array
        // Home
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
        // Find People
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
        // Photos
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
        // Communities, Will add a counter here
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1), true, "22"));
        // Pages
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
        // What's hot, We  will add a counter here
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, "50+"));

        // Recycle the typed array
        navMenuIcons.recycle();

        mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

        // setting the nav drawer list adapter
        adapter = new NavDrawerListAdapter(getApplicationContext(),
                navDrawerItems);
        mDrawerList.setAdapter(adapter);

        // enabling action bar app icon and behaving it as toggle button
        getActionBar().setDisplayHomeAsUpEnabled(true);
        //getActionBar().setHomeButtonEnabled(true);

        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                R.drawable.ic_drawer, //nav menu toggle icon
                R.string.app_name, // nav drawer open - description for accessibility
                R.string.app_name // nav drawer close - description for accessibility
                ) {
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(mTitle);
                //// calling onPrepareOptionsMenu() to show action bar icons
                invalidateOptionsMenu();
            }

            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle(mDrawerTitle);
                // calling onPrepareOptionsMenu() to hide action bar icons
                invalidateOptionsMenu();
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        if (savedInstanceState == null) {
            // on first time display view for first nav item
            displayView(0);
        }
    }

    /**
     * Slide menu item click listener
     * */
    private class SlideMenuClickListener implements
    ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {
            // display view for selected nav drawer item
            displayView(position);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // toggle nav drawer on selecting action bar app icon/title
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        // Handle action bar actions click
        switch (item.getItemId()) {
        case R.id.action_settings:
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    /* *
     * Called when invalidateOptionsMenu() is triggered
     */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // if nav drawer is opened, hide the action items
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
        menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }

    /**
     * Diplaying fragment view for selected nav drawer list item
     * */
    private void displayView(int position) {
        // update the main content by replacing fragments

        ft = getSupportFragmentManager().beginTransaction();

        switch (position) {
        case 0:
            MenuDrawerFragSortingHome fragment0 = MenuDrawerFragSortingHome.newInstance("SELECT * FROM buffets ORDER BY rating ASC","PRESSED_RATE_ASC-NULL_PRICE_NULL-NULL_DISTANCE_NULL-DATA");
            ft.replace(R.id.content_frame, fragment0);
            ft.addToBackStack(null);
            break;
        case 1:
            MenuDrawerFragAccount fragment1=MenuDrawerFragAccount.newInstance();
            ft.replace(R.id.content_frame, fragment1);
            ft.addToBackStack(null);
            break;
        case 2:
            MenuDrawerFragSortingHome fragment2 = MenuDrawerFragSortingHome.newInstance("SELECT * FROM buffets ORDER BY rating ASC","PRESSED_RATE_ASC-NULL_PRICE_NULL-NULL_DISTANCE_NULL-DATA");
            ft.replace(R.id.content_frame, fragment2);
            ft.addToBackStack(null);
            break;
        case 3:
            MenuDrawerFragment4 fragment3=MenuDrawerFragment4.newInstance("SELECT * FROM buffets ORDER BY rating ASC","PRESSED_RATE_ASC-NULL_PRICE_NULL-NULL_DISTANCE_NULL-DATA");
            ft.replace(R.id.content_frame, fragment3);
            ft.addToBackStack(null);
            break;
        case 4:
            FilterBuffetFragment fragment4=FilterBuffetFragment.newInstance();
            ft.replace(R.id.content_frame, fragment4);
            ft.addToBackStack(null);
            break;

        case 5:
            MenuDrawerFragSearch fragment5=MenuDrawerFragSearch.newInstance();
            ft.replace(R.id.content_frame, fragment5);
            ft.addToBackStack(null);
            break;
        /*case 6:
            MenuDrawerFragFeatured fragment6=MenuDrawerFragFeatured.newInstance();
            ft.replace(R.id.content_frame, fragment6);
            ft.addToBackStack(null);
            break;
        case 7:
            MenuDrawerFragDeals fragment7=MenuDrawerFragDeals.newInstance();
            ft.replace(R.id.content_frame, fragment7);
            ft.addToBackStack(null);
            break;
        case 8:
            MenuDrawerFragInvite fragment8=MenuDrawerFragInvite.newInstance();
            ft.replace(R.id.content_frame, fragment8);
            ft.addToBackStack(null);
            break;  */
        }
        ft.commit();

        // update selected item and title, then close the drawer
        mDrawerList.setItemChecked(position, true);
        mDrawerList.setSelection(position);
        setTitle(navMenuTitles[position]);
        mDrawerLayout.closeDrawer(mDrawerList);

}

@Override
public void setTitle(CharSequence title) {
    mTitle = title;
    getActionBar().setTitle(mTitle);
}

/**
 * When using the ActionBarDrawerToggle, you must call it during
 * onPostCreate() and onConfigurationChanged()...
 *///

@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    // Sync the toggle state after onRestoreInstanceState has occurred.
    mDrawerToggle.syncState();
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    // Pass any configuration change to the drawer toggls
    mDrawerToggle.onConfigurationChanged(newConfig);
}

}

Log::
05-19 22:15:53.998: E/AndroidRuntime(1138): FATAL EXCEPTION: main
05-19 22:15:53.998: E/AndroidRuntime(1138): java.lang.RuntimeException: Unable to start activity ComponentInfo{info.androidhive.slidingmenu/info.androidhive.MenuDrawer.MainActivity}: java.lang.IllegalArgumentException: No view found for id 0x7f0a003c (info.androidhive.slidingmenu:id/content_frame) for fragment MenuDrawerFragSortingHome{415cad70 #0 id=0x7f0a003c}
05-19 22:15:53.998: E/AndroidRuntime(1138):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1955)
05-19 22:15:53.998: E/AndroidRuntime(1138):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
05-19 22:15:53.998: E/AndroidRuntime(1138):     at android.app.ActivityThread.access$600(ActivityThread.java:122)
05-19 22:15:53.998: E/AndroidRuntime(1138):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)
05-19 22:15:53.998: E/AndroidRuntime(1138):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-19 22:15:53.998: E/AndroidRuntime(1138):     at android.os.Looper.loop(Looper.java:137)
05-19 22:15:53.998: E/AndroidRuntime(1138):     at android.app.ActivityThread.main(ActivityThread.java:4340)
05-19 22:15:53.998: E/AndroidRuntime(1138):     at java.lang.reflect.Method.invokeNative(Native Method)
05-19 22:15:53.998: E/AndroidRuntime(1138):     at java.lang.reflect.Method.invoke(Method.java:511)
05-19 22:15:53.998: E/AndroidRuntime(1138):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
05-19 22:15:53.998: E/AndroidRuntime(1138):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
05-19 22:15:53.998: E/AndroidRuntime(1138):     at dalvik.system.NativeStart.main(Native Method)
05-19 22:15:53.998: E/AndroidRuntime(1138): Caused by: java.lang.IllegalArgumentException: No view found for id 0x7f0a003c (info.androidhive.slidingmenu:id/content_frame) for fragment MenuDrawerFragSortingHome{415cad70 #0 id=0x7f0a003c}
05-19 22:15:53.998: E/AndroidRuntime(1138):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:919)
05-19 22:15:53.998: E/AndroidRuntime(1138):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
05-19 22:15:53.998: E/AndroidRuntime(1138):     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
05-19 22:15:53.998: E/AndroidRuntime(1138):     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1460)
05-19 22:15:53.998: E/AndroidRuntime(1138):     at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:556)
05-19 22:15:53.998: E/AndroidRuntime(1138):     at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1133)
05-19 22:15:53.998: E/AndroidRuntime(1138):     at android.app.Activity.performStart(Activity.java:4475)
05-19 22:15:53.998: E/AndroidRuntime(1138):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1928)
05-19 22:15:53.998: E/AndroidRuntime(1138):     ... 11 more

hive_activity_main.xml
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- Framelayout to display Fragments -->
    <FrameLayout
        android:id="@+id/frame_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <!-- Listview to display slider menu -->
    <ListView
        android:id="@+id/list_slidermenu"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:choiceMode="singleChoice"
        android:divider="@color/list_divider"
        android:dividerHeight="1dp"
        android:listSelector="@drawable/list_selector"
        android:background="@color/list_background"/>
</android.support.v4.widget.DrawerLayout>

A: In a DrawerLayout, the FragmentTransaction replaces the FrameLayout with the Fragment. So in your java code in ft.replace(R.id.content_view......) R.id.content_view is the FrameLayout. And the id of your FrameLayout is R.id.frame_container. Make that change and your code will work

A: The error occurs because there is no View with the id R.id.content_frame in your layout. You only have a View called R.id.frame_container. Your FragmentTransactions need to look like this:
switch (position) {
    case 0:
        MenuDrawerFragSortingHome fragment0 = MenuDrawerFragSortingHome.newInstance("SELECT * FROM buffets ORDER BY rating ASC", "PRESSED_RATE_ASC-NULL_PRICE_NULL-NULL_DISTANCE_NULL-DATA");
        ft.replace(R.id.frame_container, fragment0);
        ft.addToBackStack(null);
        break;

    case 1:
        MenuDrawerFragAccount fragment1 = MenuDrawerFragAccount.newInstance();
        ft.replace(R.id.frame_container, fragment1);
        ft.addToBackStack(null);
        break;

    case 2:
        MenuDrawerFragSortingHome fragment2 = MenuDrawerFragSortingHome.newInstance("SELECT * FROM buffets ORDER BY rating ASC", "PRESSED_RATE_ASC-NULL_PRICE_NULL-NULL_DISTANCE_NULL-DATA");
        ft.replace(R.id.frame_container, fragment2);
        ft.addToBackStack(null);
        break;

    case 3:
        MenuDrawerFragment4 fragment3 = MenuDrawerFragment4.newInstance("SELECT * FROM buffets ORDER BY rating ASC", "PRESSED_RATE_ASC-NULL_PRICE_NULL-NULL_DISTANCE_NULL-DATA");
        ft.replace(R.id.frame_container, fragment3);
        ft.addToBackStack(null);
        break;

    case 4:
        FilterBuffetFragment fragment4 = FilterBuffetFragment.newInstance();
        ft.replace(R.id.frame_container, fragment4);
        ft.addToBackStack(null);
        break;

    case 5:
        MenuDrawerFragSearch fragment5 = MenuDrawerFragSearch.newInstance();
        ft.replace(R.id.frame_container, fragment5);
        ft.addToBackStack(null);
        break;
}

I hope I could help you and if you have any further questions or problems feel free to ask!


text:
Q: how to avoid to Specify a username and password for datasource in SSRS? I am using SSRS as a part of my project for displaying reports. It accesses data from SQL data source.Here my problem is that each time I view my report on the browser, it asks me like this
"Specify a user name and password for data source"
I need to avoid this prompt while seeing my report on the browser. Kindly suggest what should i do to get rid of my problem.

A: Yes this can be fixed..  You should

*

*Go into your DataSource properties

*Select Credentials

*Select "Use this user name and password"

*Enter the credentials that you want to use with the report

*Save the report (or DataSource if it's a shared DataSource)

The default option for data sources is to prompt for credentials, so this is expected behavior unless you change it.


text:
Q: AS3 TextField doesn't show new text at all even though it's there I have a textfield in a MovieClip that I'm trying to change out from an external class. It appears to return back as empty on the stage, but if I trace what's inside there it gives me the correct value, it just doesn't show up.
My code is this:
((this.parent.parent.getChildByName('bottomBar') as MovieClip).getChildByName('area_txt') as TextField).text = 'test';

So if I trace "((this.parent.parent.getChildByName('bottomBar') as MovieClip).getChildByName('area_txt') as TextField).text" it returns "test" but it doesn't display on the stage, it's just blank.
Any idea what's going on?

A: The font needs to be embedded, also a bit of a sidenote if you're using defaultTextFormat function you need to call it before setting the text, if you use setTextFormat then you do it after
textfield.embedFonts          = true;
textfield.defaultTextFormat   = format;          // option 1
textfield.text                = "Hello World";
textfield.setTextFormat (format);                // option 2


text:
Q: Custom callbacks in VBA Note the tag: VBA, not VB6, not VB.NET.
This is specific to VBA in MS Access. I've built a collection of methods in an module I call "Enumerable". It does a lot of things reminiscent of the Enumerable classes and interfaces in .NET. One thing I want to implement is a ForEach method, analagous to the .NET Enumerable.Select method.
I built a version that uses the Application.Run method to call a function for each element, but Application.Run only works with user-defined methods. For example, the following works:
' User-defined wrapper function:
Public Function MyReplace( _
    Expression As String, Find As String, StrReplace As String, _
    Optional Start As Long = 1, _
    Optional Count As Long = 1, _
    Optional Compare As VbCompareMethod = vbBinaryCompare)
    MyReplace = Replace(Expression, Find, StrReplace, Start, Count, Compare)
End Function

' Using Application.Run to call a method by name
Public Sub RunTest()
    Debug.Print Run("MyReplace", "Input", "In", "Out")
End Sub

RunTest prints "Output", as expected. The following does NOT work:
Debug.Print Run("Replace", "Input", "In", "Out")

It throws run-time error 430: "Class does not support Automation or does not support expected interface". This is expected, because the documentation states that Application.Run only works for user-defined methods.
VBA does have an AddressOf operator, but that only works when passing function pointers to external API functions; function pointers created using AddressOf are not consumable in VBA. Again, this is noted in the documentation (or see for example VBA - CallBacks = Few Cents Less Than A Dollar?).
So is there any other way to identify and call a method using a variable? Or will my callback-ish attempts be limited to user-defined functions via the Application.Run method?

A: No other answers in a week...for resolution's sake here's the best I could come up with:

*

*I built a helper module that resolves a ParamArray to individual arguments for the sake of calling CallByName. If you pass a ParamArray through to CallByName it will mash all the arguments into a single, actual Array and pass that to the first argument in the method you attempt to invoke.

*I built two ForEach methods: one that invokes Application.Run, and another that invokes CallByName. As noted in the question, Application.Run only works for user-defined global (public module) methods. In turn, CallByName only works on instance methods, and requires an object argument.

That still leaves me without a way to directly invoke built-in global methods (such as Trim()) by name. My workaround for that is to build user-defined wrapper methods that just call the built-in global method, for example:
Public Function FLeft( _
   str As String, _
   Length As Long) As String
    FLeft = Left(str, Length)
End Function

Public Function FLTrim( _
   str As String) As String
    FLTrim = LTrim(str)
End Function

Public Function FRight( _
   str As String, _
   Length As Long) As String
    FRight = Right(str, Length)
End Function

...etc...

I can now use these to do things like:
' Trim all the strings in an array of strings
trimmedArray = ForEachRun(rawArray, "FTrim")

' Use RegExp to replace stuff in all the elements of an array
' --> Remove periods that aren't between numbers
Dim rx As New RegExp
rx.Pattern = "(^|\D)\.(\D|$)"
rx.Global = True
resultArray = ForEachCallByName(inputArray, rx, "Replace", VbMethod, "$1 $2")

A: Very old question but for those looking for a more general approach please use stdCallback and stdLambda alongside stdICallable. These can be found as part of the stdVBA library (a library largely maintained by myself).
sub Main()
  'Create an array
  Dim arr as stdArray
  set arr = stdArray.Create(1,2,3,4,5,6,7,8,9,10) 'Can also call CreateFromArray

  'Demonstrating join, join will be used in most of the below functions
  Debug.Print arr.join()                                                 '1,2,3,4,5,6,7,8,9,10
  Debug.Print arr.join("|")                                              '1|2|3|4|5|6|7|8|9|10

  'Basic operations
  arr.push 3
  Debug.Print arr.join()                                                 '1,2,3,4,5,6,7,8,9,10,3
  Debug.Print arr.pop()                                                  '3
  Debug.Print arr.join()                                                 '1,2,3,4,5,6,7,8,9,10
  Debug.Print arr.concat(stdArray.Create(11,12,13)).join                 '1,2,3,4,5,6,7,8,9,10,11,12,13
  Debug.Print arr.join()                                                 '1,2,3,4,5,6,7,8,9,10 'concat doesn't mutate object
  Debug.Print arr.includes(3)                                            'True
  Debug.Print arr.includes(34)                                           'False

  'More advanced behaviour when including callbacks! And VBA Lamdas!!
  Debug.Print arr.Map(stdLambda.Create("$1+1")).join          '2,3,4,5,6,7,8,9,10,11
  Debug.Print arr.Reduce(stdLambda.Create("$1+$2"))           '55 ' I.E. Calculate the sum
  Debug.Print arr.Reduce(stdLambda.Create("Max($1,$2)"))      '10 ' I.E. Calculate the maximum
  Debug.Print arr.Filter(stdLambda.Create("$1>=5")).join      '5,6,7,8,9,10

  'Execute property accessors with Lambda syntax
  Debug.Print arr.Map(stdLambda.Create("ThisWorkbook.Sheets($1)")) _
                .Map(stdLambda.Create("$1.Name")).join(",")            'Sheet1,Sheet2,Sheet3,...,Sheet10

  'Execute methods with lambdas and enumerate over enumeratable collections:
  Call stdEnumerator.Create(Application.Workbooks).forEach(stdLambda.Create("$1#Save")

  'We even have if statement!
  With stdLambda.Create("if $1 then ""lisa"" else ""bart""")
    Debug.Print .Run(true)                                              'lisa
    Debug.Print .Run(false)                                             'bart
  End With

  'Execute custom functions
  Debug.Print arr.Map(stdCallback.CreateFromModule("ModuleMain","CalcArea")).join  '3.14159,12.56636,28.274309999999996,50.26544,78.53975,113.09723999999999,153.93791,201.06176,254.46879,314.159

  'Creating from an object property
  Debug.Print arr.Map(stdCallback.CreateFromObjectProperty(arr,"item", vbGet))  '1,2,3,4,5,6,7,8,9,10

  'Creating from an object method
  Debug.Print arr.Map(stdCallback.CreateFromObjectMethod(someObj,"getStuff"))
End Sub

Public Function CalcArea(ByVal radius as Double) as Double
  CalcArea = 3.14159*radius*radius
End Function


text:
Q: WndProc override odd message, cant be proper I am looking at the code posted here, specifically  SyntaxRichTextBox.cs at the overriden method WndProc.
Is this just a typo in the code? What windows msg is 0x00f? Did they mean 0x0f for WM_PAINT? And what is the author of the code catching that message?
Code:
protected override void WndProc(ref System.Windows.Forms.Message m)
{
    if (m.Msg == 0x00f)
    {
        if (m_bPaint)
            base.WndProc(ref m);
        else
            m.Result = IntPtr.Zero;
    }
    else
        base.WndProc(ref m);
}

A: First off, as James McNellis suggested in the comment above, 0x00f and 0x0f indicate the same number. I didn't check the value of WM_PAINT message, but the code looks like it is handling this message.
It looks like a simple optimization: if m_bPaint is false, skip the base.WndProc() call. Probably m_bPaint is a flag that indicates there is something that needs to be redrawn.


text:
Q: Importing a module does not run the code inside it when running a few unittest files using pytest I have a few files with tests and an imported file:
# test1.py
print("running test1.py")

import unittest
import imported

class MyTest1(unittest.TestCase):
    def test_method1(self):
        assert "love" == "".join(["lo", "ve"])

    def test_fail1(self):
        assert True, "I failed!"

and
# test2.py
print("running test2.py")

import unittest
import imported

class MyTest2(unittest.TestCase):
    def test_ok2(self):
        self.assertEqual(True, 2==2, "I will not appear!")

    def test_fail2(self):
        self.assertFalse(False, "Doh!")

and
# imported.py
import sys

# Here I am accessing the module that has imported this file
importing = sys.modules[sys._getframe(6).f_globals['__name__']]
print(importing.__name__ + " imported this file")

When I run pytest -s test1.py test2.py, I get this result:
=============================== test session starts ================================
platform darwin -- Python 3.6.0, pytest-3.7.1, py-1.5.4, pluggy-0.7.1
rootdir: /Users/ibodi/MyDocs/progs/Python/unittest_test, inifile:
collecting 0 items                                                                 running test1.py
test1 imported this file
collecting 2 items                                                                 running test2.py
collected 4 items

test1.py ..
test2.py ..

============================= 4 passed in 0.08 seconds =============================

importing variable in imported.py corresponds to the module that has imported the imported.py module.
And the problem is that the line import imported in test2.py doesn't cause test2 imported this file to appear in the logs. Why is that?


text:
Q: Programmatically created CardView doesn't appear So, I've made a program that automatically creates CardViewes to store Date and Name of Birthdays in them and add them to the Relative Layout in my Main Activity via this Guide: https://android--code.blogspot.com/2015/12/android-how-to-create-cardview.html. I had many many errors and fixed all of them until now I just don't have an error Message to work with. As the title might tell, the CardViews just won't appear on my Main Activity. I would be very glad if someone could help me out with this. By the way, I'm pretty new to coding and don't have much experience so that might also be the problem.
Main Activity Java:
package com.myuserwithoutme.birthdayremember;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.myuserwithoutme.birthdayremember.CreateActivity.*;

public class MainActivity extends AppCompatActivity{
private Context mContext;
RelativeLayout mRelativeLayout;
Boolean pressed = false;
String mEditText1;
String mEditText2;

/
private static final String TOAST_TEXT = "Test ads are being shown. "
        + "To show live ads, replace the ad unit ID in res/values/strings.xml with your own ad unit ID.";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mContext = getApplicationContext();
    mRelativeLayout = findViewById(R.id.RelativeLayout);

    AdView adView = findViewById(R.id.adView);
    AdRequest adRequest = new AdRequest.Builder()
            .setRequestAgent("android_studio:ad_template").build();
    adView.loadAd(adRequest);

    Toast.makeText(this, TOAST_TEXT, Toast.LENGTH_LONG).show();

    FloatingActionButton fab1 = findViewById(R.id.fab1);
    fab1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent createIntent = new Intent(MainActivity.this,CreateActivity.class);
            startActivity(createIntent);
        }
    });

    Intent newcard = getIntent();
    for (int x = 1; x <= 0; x++) {
        if (newcard != null) {
            pressed = newcard.getExtras().getBoolean("card");
        }
    }
    Intent strings = getIntent();
    for (int x = 1; x <= 0; x++) {
        if (strings != null) {
            mEditText1 = strings.getExtras().getString("Name");
            mEditText2 = strings.getExtras().getString("Date");
        }
    }

        if (pressed != false) {
            CardView card = new CardView(mContext);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
            );
            card.setLayoutParams(params);
            card.setRadius(9);
            card.setContentPadding(15, 15, 15, 15);

            card.setCardBackgroundColor(Color.parseColor("#d3e8e7"));
            card.setMaxCardElevation(15);
            card.setCardElevation(9);
            TextView text = new TextView(mContext);
            text.setLayoutParams(params);
            text.setText(mEditText1 + "\n" + mEditText2);
            text.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 30);
            text.setTextColor(Color.parseColor("#308985"));

            card.addView(text);
            mRelativeLayout.addView(card);
        }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();

    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}
Xml Main Activity:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/RelativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<!-- view for AdMob Banner Ad -->
<LinearLayout
    android:id="@+id/layout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Testing" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

<com.google.android.gms.ads.AdView
    android:id="@+id/adView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    ads:adSize="BANNER"
    ads:adUnitId="@string/banner_ad_unit_id" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab1"
    android:layout_width="56dp"
    android:layout_height="56dp"
    android:layout_alignParentBottom="true"
    android:layout_alignParentEnd="true"
    android:layout_marginBottom="62dp"
    android:layout_marginEnd="15dp"
    android:clickable="true"
    android:src="@drawable/ic_baseline_add_24px"
    ads:backgroundTint="@android:color/darker_gray"
    ads:rippleColor="@android:color/background_light" />

Thanks for the help
EDIT:
Second Activity:
package com.myuserwithoutme.birthdayremember;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.util.TypedValue;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

public class CreateActivity extends AppCompatActivity {

private EditText mEditText1;
private EditText mEditText2;
private String name;
private String date;

public boolean newcard;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_create);

    mEditText1 = findViewById(R.id.editText1);
    mEditText2 = findViewById(R.id.editText2 );
    name = mEditText1.getText().toString();
    date = mEditText2.getText().toString();

    final Intent newcard = new Intent(CreateActivity.this, MainActivity.class);
    FloatingActionButton fab2 = findViewById(R.id.fab2);
    fab2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent mainIntent = new Intent(CreateActivity.this,MainActivity.class);
            startActivity(mainIntent);

            newcard.putExtra("card", true);

            Intent strings = new Intent(CreateActivity.this, MainActivity.class);
            strings.putExtra("Name", name);
            strings.putExtra("Date", date);
            startActivity(strings);

        }
    });

}
}

Second Xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/rl2"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<!-- view for AdMob Banner Ad -->
<com.google.android.gms.ads.AdView
    android:id="@+id/adView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_alignParentBottom="true"
    ads:adSize="BANNER"
    ads:adUnitId="@string/banner_ad_unit_id" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentEnd="true"
    android:layout_marginBottom="61dp"
    android:layout_marginEnd="17dp"
    android:clickable="true"
    android:src="@drawable/ic_baseline_save_24px"
    ads:backgroundTint="@android:color/darker_gray"
    ads:rippleColor="@android:color/background_light" />

<EditText
    android:id="@+id/editText1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:layout_marginTop="60dp"
    android:ems="10"
    android:hint="Name"
    android:inputType="textPersonName" />

<EditText
    android:id="@+id/editText2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:layout_marginTop="126dp"
    android:ems="10"
    android:hint="DD/MM/YYYY"
    android:inputType="date" />

<TextView
    android:id="@+id/textView3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:layout_marginStart="18dp"
    android:layout_marginTop="24dp"
    android:text="Gib die Daten der Person ein" />

A: You must start the activity with startActivityForResult and not startActivity and this activity will return result values to MainActivity and not extras:
https://developer.android.com/training/basics/intents/result
What are you doing with these loops:
Intent newcard = getIntent();
for (int x = 1; x <= 0; x++) {
    if (newcard != null) {
        pressed = newcard.getExtras().getBoolean("card");
    }
}
Intent strings = getIntent();
for (int x = 1; x <= 0; x++) {
    if (strings != null) {
        mEditText1 = strings.getExtras().getString("Name");
        mEditText2 = strings.getExtras().getString("Date");
    }
}

They are not executed since the starting value is x = 1 and it will never be x <= 0.
Maybe try without the loops:
Intent newcard = getIntent();
if (newcard != null) {
    pressed = newcard.getExtras().getBoolean("card");
}

Intent strings = getIntent();
if (strings != null) {
    mEditText1 = strings.getExtras().getString("Name");
    mEditText2 = strings.getExtras().getString("Date");
}

A: So, I will try to help. As it was mentioned in the comment, probably your code is not reaching the part it is creating the card, it means pressed is never true.
Since I do not have the code of your other activity, I would guess you can get rid of the problem by deleting this loop that does not seem
First Activity
Intent intent = getIntent();
    if (intent != null) {
        pressed = intent.getExtras().getBoolean("card");
        mEditText1 = intent.getExtras().getString("Name");
        mEditText2 = intent.getExtras().getString("Date");
    }

getIntent will return the intent from the activity you are coming from. You do not need to creat two intents as you did, since they will be the same.
EDIT
Second Activity
Your code is never reaching the "puts" because you navigate to another activity before. You should do that.
    FloatingActionButton fab2 = findViewById(R.id.fab2);
    fab2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent intent = new Intent(CreateActivity.this, MainActivity.class);
            intent.putExtra("card", true);
            intent.putExtra("Name", name);
            intent.putExtra("Date", date);
            startActivity(intent);

        }
    });

Also some hints for your code.
Instead of
if (pressed != false)
// This means pressed is true.

use
if (pressed)
// This also means pressed is true.

A: Just a quick edit for people that have the same problem, the startActivityForResult didnt worked at first because i had an outdated version, i updated jdk and android studio to the newest version and it worked. Thanks everybody :D


text:
Q: Overriding Default.xml removes Sign In link from header - Magento 2.2.3 I'm building a theme off the back of Luma. I'm mainly doing a few colour changes and moving a few elements around.
When I override the following, it removes the 'Sign In' link from the header:
Magento_Theme/layout/default.xml
Another weird behaviour is:
If I take out my overriding default.xml, redeploy the website (flush the cache etc), the link comes back, then when I put my default.xml back in and redeploy, the link stays until I flush the cache, it then disappears.

A: Do not override whole Magento_Theme/layout/default.xml in your theme. just put which content you want to change


text:
Q: Why does running Minecraft create window tearing/lag I have a Titan X graphic card running on Ubuntu 18.04 + Xfce4 desktop, and I experience tearing while dragging windows when Minecraft is open. I have two monitors, and it seems to always happen to the Minecraft window on my main monitor, but to all windows as soon as I drag them to my secondary monitor. The other windows on my main monitor are a bit irregular.
Before installing these two: sudo apt install nvidia-cuda-toolkit gcc-6, as suggested on this post, I only experienced lag between mouse/window, but now I experince tearing/shadows too. Still laggy.
I have tried forcing full composition pipeline on my x-server too, and saving it to my X11 file, as suggested on this other post, but no apparent change was to be seen after applying and experiencing a small black-monitor delay (I assume X11 reset).
As soon as I close Minecraft, the issues disappear. I'm uncertain on what Minecraft uses for their graphics, but I've been emulating games in Proton through Steam without any issue alike this one. As soon as I enter the menu of the game, the tearing returns. I don't need to enter a world, so I really don't believe it's a resource problem.
I'm not completely certain which repository I used to install my Nvidia drivers, but apt list nvidia* gives me a fairly long list of bionic,bionic-updates nvidia versions:
nvidia-304/bionic 304.137-0ubuntu2 amd64
nvidia-304-dev/bionic 304.137-0ubuntu2 amd64
nvidia-304-updates/bionic 304.137-0ubuntu2 amd64
nvidia-304-updates-dev/bionic 304.137-0ubuntu2 amd64
nvidia-331/bionic-updates,bionic 340.107-0ubuntu0.18.04.2 amd64
nvidia-331-dev/bionic-updates,bionic 340.107-0ubuntu0.18.04.2 amd64
nvidia-331-updates/bionic-updates,bionic 340.107-0ubuntu0.18.04.2 amd64
nvidia-331-updates-dev/bionic-updates,bionic 340.107-0ubuntu0.18.04.2 amd64
nvidia-331-updates-uvm/bionic-updates,bionic 340.107-0ubuntu0.18.04.2 amd64
nvidia-331-uvm/bionic-updates,bionic 340.107-0ubuntu0.18.04.2 amd64
nvidia-340/bionic-updates,bionic 340.107-0ubuntu0.18.04.2 amd64
nvidia-340-dev/bionic-updates,bionic 340.107-0ubuntu0.18.04.2 amd64
nvidia-340-updates/bionic-updates,bionic 340.107-0ubuntu0.18.04.2 amd64
nvidia-340-updates-dev/bionic-updates,bionic 340.107-0ubuntu0.18.04.2 amd64
nvidia-340-updates-uvm/bionic 340.96-0ubuntu2 amd64
nvidia-340-uvm/bionic-updates,bionic 340.107-0ubuntu0.18.04.2 amd64
nvidia-346/bionic 352.63-0ubuntu3 amd64
nvidia-346-dev/bionic 352.63-0ubuntu3 amd64
nvidia-346-updates/bionic 352.63-0ubuntu3 amd64
nvidia-346-updates-dev/bionic 352.63-0ubuntu3 amd64
nvidia-352/bionic 361.45.11-0ubuntu4 amd64
nvidia-352-dev/bionic 361.45.11-0ubuntu4 amd64
nvidia-352-updates/bionic 361.45.11-0ubuntu4 amd64
nvidia-352-updates-dev/bionic 361.45.11-0ubuntu4 amd64
nvidia-361/bionic 367.57-0ubuntu5 amd64
nvidia-361-dev/bionic 367.57-0ubuntu5 amd64
nvidia-361-updates/bionic 361.45.11-0ubuntu4 amd64
nvidia-361-updates-dev/bionic 361.45.11-0ubuntu4 amd64
nvidia-367/bionic 375.82-0ubuntu3 amd64
nvidia-367-dev/bionic 375.82-0ubuntu3 amd64
nvidia-375/bionic 384.111-0ubuntu1 amd64
nvidia-375-dev/bionic 384.111-0ubuntu1 amd64
nvidia-384/bionic-updates,bionic-security,bionic 390.116-0ubuntu0.18.04.1 amd64
nvidia-384-dev/bionic-updates,bionic-security,bionic 390.116-0ubuntu0.18.04.1 amd64
nvidia-387/bionic 390.87-0ubuntu0~gpu18.04.2 amd64
nvidia-387-dev/bionic 390.87-0ubuntu0~gpu18.04.2 amd64
nvidia-390/bionic 390.87-0ubuntu0~gpu18.04.2 amd64
nvidia-390-dev/bionic 390.87-0ubuntu0~gpu18.04.2 amd64
nvidia-cg-dev/bionic 3.1.0013-3 amd64
nvidia-cg-doc/bionic,bionic 3.1.0013-3 all
nvidia-cg-toolkit/bionic 3.1.0013-3 amd64
nvidia-common/bionic-updates 1:0.5.2.3 amd64
nvidia-compute-utils-390/bionic-updates,bionic-security,bionic 390.116-0ubuntu0.18.04.1 amd64
nvidia-compute-utils-396/bionic 396.54-0ubuntu0~gpu18.04.1 amd64
nvidia-compute-utils-410/bionic 410.104-0ubuntu0~18.04.1 amd64
nvidia-compute-utils-415/bionic 415.27-0ubuntu0~gpu18.04.2 amd64
nvidia-compute-utils-418/bionic,now 418.56-0ubuntu0~gpu18.04.1 amd64 [installed,automatic]
nvidia-compute-utils-430/bionic 430.09-0ubuntu0~gpu18.04.1 amd64
nvidia-cuda-dev/bionic,now 9.1.85-3ubuntu1 amd64 [installed,automatic]
nvidia-cuda-doc/bionic,bionic,now 9.1.85-3ubuntu1 all [installed,automatic]
nvidia-cuda-gdb/bionic,now 9.1.85-3ubuntu1 amd64 [installed,automatic]
nvidia-cuda-toolkit/bionic,now 9.1.85-3ubuntu1 amd64 [installed]
nvidia-current/bionic 304.137-0ubuntu2 amd64
nvidia-current-dev/bionic 304.137-0ubuntu2 amd64
nvidia-dkms-390/bionic-updates,bionic-security,bionic 390.116-0ubuntu0.18.04.1 amd64
nvidia-dkms-396/bionic 396.54-0ubuntu0~gpu18.04.1 amd64
nvidia-dkms-410/bionic 410.104-0ubuntu0~18.04.1 amd64
nvidia-dkms-415/bionic 415.27-0ubuntu0~gpu18.04.2 amd64
nvidia-dkms-418/bionic,now 418.56-0ubuntu0~gpu18.04.1 amd64 [installed,automatic]
nvidia-dkms-430/bionic 430.09-0ubuntu0~gpu18.04.1 amd64
nvidia-driver-390/bionic-updates,bionic-security,bionic 390.116-0ubuntu0.18.04.1 amd64
nvidia-driver-396/bionic 396.54-0ubuntu0~gpu18.04.1 amd64
nvidia-driver-410/bionic 410.104-0ubuntu0~18.04.1 amd64
nvidia-driver-415/bionic 415.27-0ubuntu0~gpu18.04.2 amd64
nvidia-driver-418/bionic,now 418.56-0ubuntu0~gpu18.04.1 amd64 [installed]
nvidia-driver-430/bionic 430.09-0ubuntu0~gpu18.04.1 amd64
nvidia-headless-390/bionic-updates,bionic-security,bionic 390.116-0ubuntu0.18.04.1 amd64
nvidia-headless-396/bionic 396.54-0ubuntu0~gpu18.04.1 amd64
nvidia-headless-410/bionic 410.104-0ubuntu0~18.04.1 amd64
nvidia-headless-415/bionic 415.27-0ubuntu0~gpu18.04.2 amd64
nvidia-headless-418/bionic 418.56-0ubuntu0~gpu18.04.1 amd64
nvidia-headless-430/bionic 430.09-0ubuntu0~gpu18.04.1 amd64
nvidia-headless-no-dkms-390/bionic-updates,bionic-security,bionic 390.116-0ubuntu0.18.04.1 amd64
nvidia-headless-no-dkms-396/bionic 396.54-0ubuntu0~gpu18.04.1 amd64
nvidia-headless-no-dkms-410/bionic 410.104-0ubuntu0~18.04.1 amd64
nvidia-headless-no-dkms-415/bionic 415.27-0ubuntu0~gpu18.04.2 amd64
nvidia-headless-no-dkms-418/bionic 418.56-0ubuntu0~gpu18.04.1 amd64
nvidia-headless-no-dkms-430/bionic 430.09-0ubuntu0~gpu18.04.1 amd64
nvidia-kernel-common-390/bionic-updates,bionic-security,bionic 390.116-0ubuntu0.18.04.1 amd64
nvidia-kernel-common-396/bionic 396.54-0ubuntu0~gpu18.04.1 amd64
nvidia-kernel-common-410/bionic 410.104-0ubuntu0~18.04.1 amd64
nvidia-kernel-common-415/bionic 415.27-0ubuntu0~gpu18.04.2 amd64
nvidia-kernel-common-418/bionic,now 418.56-0ubuntu0~gpu18.04.1 amd64 [installed,automatic]
nvidia-kernel-common-430/bionic 430.09-0ubuntu0~gpu18.04.1 amd64
nvidia-kernel-source-390/bionic-updates,bionic-security,bionic 390.116-0ubuntu0.18.04.1 amd64
nvidia-kernel-source-396/bionic 396.54-0ubuntu0~gpu18.04.1 amd64
nvidia-kernel-source-410/bionic 410.104-0ubuntu0~18.04.1 amd64
nvidia-kernel-source-415/bionic 415.27-0ubuntu0~gpu18.04.2 amd64
nvidia-kernel-source-418/bionic,now 418.56-0ubuntu0~gpu18.04.1 amd64 [installed,automatic]
nvidia-kernel-source-430/bionic 430.09-0ubuntu0~gpu18.04.1 amd64
nvidia-libopencl1-304/bionic 304.137-0ubuntu2 amd64
nvidia-libopencl1-304-updates/bionic 304.137-0ubuntu2 amd64
nvidia-libopencl1-331/bionic-updates,bionic 340.107-0ubuntu0.18.04.2 amd64
nvidia-libopencl1-331-updates/bionic-updates,bionic 340.107-0ubuntu0.18.04.2 amd64
nvidia-libopencl1-340/bionic-updates,bionic 340.107-0ubuntu0.18.04.2 amd64
nvidia-libopencl1-340-updates/bionic-updates,bionic 340.107-0ubuntu0.18.04.2 amd64
nvidia-libopencl1-346/bionic 352.63-0ubuntu3 amd64
nvidia-libopencl1-346-updates/bionic 352.63-0ubuntu3 amd64
nvidia-libopencl1-352/bionic 361.45.11-0ubuntu4 amd64
nvidia-libopencl1-352-updates/bionic 361.45.11-0ubuntu4 amd64
nvidia-libopencl1-361/bionic 367.57-0ubuntu5 amd64
nvidia-libopencl1-361-updates/bionic 361.45.11-0ubuntu4 amd64
nvidia-libopencl1-367/bionic 375.82-0ubuntu3 amd64
nvidia-libopencl1-375/bionic 384.111-0ubuntu1 amd64
nvidia-libopencl1-384/bionic-updates,bionic-security,bionic 390.116-0ubuntu0.18.04.1 amd64
nvidia-libopencl1-387/bionic 390.87-0ubuntu0~gpu18.04.2 amd64
nvidia-libopencl1-390/bionic 390.87-0ubuntu0~gpu18.04.2 amd64
nvidia-modprobe/bionic 384.111-2 amd64
nvidia-nsight/bionic 9.1.85-3ubuntu1 amd64
nvidia-opencl-dev/bionic,now 9.1.85-3ubuntu1 amd64 [installed,automatic]
nvidia-opencl-icd-304/bionic 304.137-0ubuntu2 amd64
nvidia-opencl-icd-304-updates/bionic 304.137-0ubuntu2 amd64
nvidia-opencl-icd-331/bionic-updates,bionic 340.107-0ubuntu0.18.04.2 amd64
nvidia-opencl-icd-331-updates/bionic-updates,bionic 340.107-0ubuntu0.18.04.2 amd64
nvidia-opencl-icd-340/bionic-updates,bionic 340.107-0ubuntu0.18.04.2 amd64
nvidia-opencl-icd-340-updates/bionic-updates,bionic 340.107-0ubuntu0.18.04.2 amd64
nvidia-opencl-icd-346/bionic 352.63-0ubuntu3 amd64
nvidia-opencl-icd-346-updates/bionic 352.63-0ubuntu3 amd64
nvidia-opencl-icd-352/bionic 361.45.11-0ubuntu4 amd64
nvidia-opencl-icd-352-updates/bionic 361.45.11-0ubuntu4 amd64
nvidia-opencl-icd-361/bionic 367.57-0ubuntu5 amd64
nvidia-opencl-icd-361-updates/bionic 361.45.11-0ubuntu4 amd64
nvidia-opencl-icd-367/bionic 375.82-0ubuntu3 amd64
nvidia-opencl-icd-375/bionic 384.111-0ubuntu1 amd64
nvidia-opencl-icd-384/bionic-updates,bionic-security,bionic 390.116-0ubuntu0.18.04.1 amd64
nvidia-opencl-icd-387/bionic 390.87-0ubuntu0~gpu18.04.2 amd64
nvidia-opencl-icd-390/bionic 390.87-0ubuntu0~gpu18.04.2 amd64
nvidia-prime/bionic-updates,bionic-updates,now 0.8.8.2 all [installed,automatic]
nvidia-profiler/bionic,now 9.1.85-3ubuntu1 amd64 [installed,automatic]
nvidia-settings/bionic,now 418.56-0ubuntu0~gpu18.04.1 amd64 [installed,automatic]
nvidia-utils-390/bionic-updates,bionic-security,bionic 390.116-0ubuntu0.18.04.1 amd64
nvidia-utils-396/bionic 396.54-0ubuntu0~gpu18.04.1 amd64
nvidia-utils-410/bionic 410.104-0ubuntu0~18.04.1 amd64
nvidia-utils-415/bionic 415.27-0ubuntu0~gpu18.04.2 amd64
nvidia-utils-418/bionic,now 418.56-0ubuntu0~gpu18.04.1 amd64 [installed,automatic]
nvidia-utils-430/bionic 430.09-0ubuntu0~gpu18.04.1 amd64
nvidia-visual-profiler/bionic,now 9.1.85-3ubuntu1 amd64 [installed,automatic]

Any suggestions?

A: There is a good chance that your system actually allows Optimus to work! Be glad for that, as Optimus doesn't work 99% of the time on *nix.
in doing so, all nVidia chipsets of any kind don't have support for V-Sync at all, on any Linux distro. Chances are that it's using Intel HD until Optimus goes "oh wait, i need to do this one" and then it swaps over, and since there is no V-Sync at all on nVidia, the entire screen tears.


text:
Q: CursorAdapter with images are loading weird I have a simple CursorAdapter that gets a title and image.
It shows the title and then loads the image from the Internet.
However, when I call the image loader the image is loaded at the wrong place, and it starts going really wild: see here.
My complete code is here.
The adapter is RestaurantListActivityCursorAdapter
public class RestaurantListActivityCursorAdapter extends CursorAdapter {
    /* Api variables */
    String websiteURL   = "http://cicolife.com";

    public RestaurantListActivityCursorAdapter(Context context, Cursor cursor) {
        super(context, cursor, 0);
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        return LayoutInflater.from(context).inflate(R.layout.activity_main_list_item, parent, false);
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        // Extract properties from cursor
        int get_Id = cursor.getInt(cursor.getColumnIndexOrThrow("_id"));
        String getTitle = cursor.getString(cursor.getColumnIndexOrThrow("title"));
        String getImage = cursor.getString(cursor.getColumnIndexOrThrow("image"));

        // Name
        TextView listViewTitle = (TextView) view.findViewById(R.id.listViewTitle);
        listViewTitle.setText(getTitle);

        // Img
        ImageView listViewImage = (ImageView) view.findViewById(R.id.listViewImage);
        if(getImage != null) {
            if (!(getImage.equals(""))) {
                String destinationPath = android.os.Environment.getExternalStorageDirectory().getPath()+ File.separatorChar+"/Android/data/com.nettport.restaurants/imgs";
                File file = new File (destinationPath, getImage);
                if (file.exists ()){
                    Bitmap myBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
                    listViewImage.setImageBitmap(myBitmap);
                }
                else {
                    String loadImage = websiteURL + "/_cache/" + getImage;
                    new HttpRequestImageLoadTask(context, loadImage, listViewImage, getImage,"imgs").execute();
                }
            }
        }
    }
}

The image loader HttpRequestImageLoadTask
public class HttpRequestImageLoadTask extends AsyncTask<Void, Void, Bitmap> {

    private String url;
    private ImageView imageView;
    private LinearLayout linearLayout;
    private Resources resources;

    private Context context;
    private String storeDirectory;
    private String imageName;

    public interface TaskListener {
        void onFinished(String result);
    }

    public HttpRequestImageLoadTask(Context ctx, String url, ImageView imageView, String imgName, String storeDirectory) {
        this.context = ctx;
        this.url = url;
        this.imageView = imageView;
        this.imageName = imgName;
        this.storeDirectory = storeDirectory;
    }

    public HttpRequestImageLoadTask(Context ctx, String url, LinearLayout linearLayout, Resources resources, String imgName, String storeDirectory) {
        this.context = ctx;
        this.url = url;
        this.linearLayout = linearLayout;
        this.imageName = imgName;
        this.storeDirectory = storeDirectory;
    }

    @Override
    protected Bitmap doInBackground(Void... params) {
        if (checkIfCacheExists(imageName)) {

            String destinationPath = android.os.Environment.getExternalStorageDirectory().getPath()+File.separatorChar+"/Android/data/com.nettport.restaurants/" + storeDirectory;
            File file = new File (destinationPath, imageName);
            Bitmap myBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
            return myBitmap;
        } else {
            try {
                URL urlConnection = new URL(url);
                HttpURLConnection connection = (HttpURLConnection) urlConnection
                        .openConnection();
                connection.setDoInput(true);
                connection.connect();
                InputStream input = connection.getInputStream();
                Bitmap myBitmap = BitmapFactory.decodeStream(input);

                saveImage(myBitmap);

                return myBitmap;
            } catch(Exception e){
                e.printStackTrace();
            }
        }

        return null;
    }

    @Override
    protected void onPostExecute(Bitmap result) {
        super.onPostExecute(result);
        if(imageView != null) {
            imageView.setImageBitmap(result);
        } else {
            if(linearLayout != null){

                BitmapDrawable background = new BitmapDrawable(resources, result);
                linearLayout.setBackground(background);
            }
        }
    }

    public boolean checkIfCacheExists(String imgName){
        String destinationPath = android.os.Environment.getExternalStorageDirectory().getPath()+File.separatorChar+"/Android/data/com.nettport.restaurants/" + storeDirectory;
        File file = new File (destinationPath, imgName);
        return file.exists();
    }

    private void saveImage(Bitmap finalBitmap) {
        // Make dir
        String destinationPath = android.os.Environment.getExternalStorageDirectory().getPath()+File.separatorChar+"/Android/data/com.nettport.restaurants/" + storeDirectory;
        File folder = new File(destinationPath);
        try {
            if (!folder.exists()) {
                // Make Android
                destinationPath = android.os.Environment.getExternalStorageDirectory().getPath()+File.separatorChar+"/Android";
                folder = new File(destinationPath);
                if (!folder.exists()) {
                    folder.mkdir();
                }

                // Make Android/data
                destinationPath = android.os.Environment.getExternalStorageDirectory().getPath()+File.separatorChar+"/Android/data";
                folder = new File(destinationPath);
                if (!folder.exists()) {
                    folder.mkdir();
                }

                // Make Android/data/com.nettport.restaurants
                destinationPath = android.os.Environment.getExternalStorageDirectory().getPath()+File.separatorChar+"/Android/data/com.nettport.restaurants";
                folder = new File(destinationPath);
                if (!folder.exists()) {
                    folder.mkdir();
                }

                // Make Android/data/com.nettport.restaurants/storeDirectory
                destinationPath = android.os.Environment.getExternalStorageDirectory().getPath()+File.separatorChar+"/Android/data/com.nettport.restaurants/" + storeDirectory;
                folder = new File(destinationPath);
                if (!folder.exists()) {
                    folder.mkdir();
                }
            }
        } catch (Exception e){
            Toast.makeText(context, "Could not create directory:\n" + e.toString(), Toast.LENGTH_LONG).show();
        }

        if(imageName != null) {
            File file = new File(destinationPath, imageName);
            if (file.exists()) file.delete();
            try {
                FileOutputStream out = new FileOutputStream(file);
                finalBitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
                out.flush();
                out.close();

            } catch (Exception e) {
                // Toast.makeText(context, "Cant save image\n" + e.toString(), Toast.LENGTH_LONG).show();
            }
        }
    }
}

A: You have not put any else condition for your ImageView in your adapter. I see there are several else blocks are missing here.
if(getImage != null) {
    if (!(getImage.equals(""))) {
        String destinationPath = android.os.Environment.getExternalStorageDirectory().getPath()+ File.separatorChar+"/Android/data/com.nettport.restaurants/imgs";
        File file = new File (destinationPath, getImage);
        if (file.exists()){
            Bitmap myBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
            listViewImage.setImageBitmap(myBitmap);
        } else {
            String loadImage = websiteURL + "/_cache/" + getImage;

            // Add nothing here when the image is being fetched
            listViewImage.setImageBitmap(null);

            new HttpRequestImageLoadTask(context, loadImage, listViewImage, getImage,"imgs").execute();
        }
    } else {
        // Add an else block here when image is equals ""
        listViewImage.setImageBitmap(null);
    }
} else {
    // Add an else block here when image is null
    listViewImage.setImageBitmap(null);
}

You need to specify every possible combination in your adapter while loading the images in your ImageView.
And if you have the image url from server, just use Glide to load the images when they are not available in cache.


text:
Q: uploading full directories from app root to S3 using laravel filesystem? It is possible to do the following code snippet but using Laravel filesystem?
        try {
            $s3 = AWS::createClient( 's3' );
            $s3->uploadDirectory( env('AMAZON_LOCATION'), env('AMAZON_BUCKET'), $this->key_prefix, [
                'params'      => [ 'ACL' => 'public-read'],
                'concurrency' => 20,
                'debug'       => true
            ] );
        }catch (S3Exception $e){

        }

I just don't feel like using a package more, but I cant manage to replicate the same functions with laravel file system, has anyone done it before or have a good pointer on how to do it?

A: The only possible solution that I could come out with was the following:
            $files = File::files('/directory/path') );
            if ( sizeof( $files ) > 0 ) {
                $disk = Storage::disk( 'api_s3' );
                foreach ( $files as $file ) {
                    $path_info = pathinfo( $file );
                    $file_name = $path_info[ 'filename' ] . '.' . $path_info[ 'extension' ];
                    $disk->put( $file_name, file_get_contents( $file ) );
                }
            }

Is not the best solution ever, but it does work.


text:
Q: Outputting XML feed breaks when executing PHP syntax I am trying to MVC a simple XML feed of images based on this structure.
This will always go from 1 - 20.
<image1>http://test.url/test.jpg</image1>
<caption1>This is a test caption <caption1 />
<credit1>This is a test credit</credit1>

and here's my script:
echo "<images>";
for($i = 1; $i <= 20; $i++) {
   $imageUrl = "image$i";
   $caption = "caption$i";
   $credit = "credit$i";
   echo "<image no='$i'>";
   echo "<imageurl>" . $gallery->$imageUrl . "</imageurl>";
   echo "<caption>" . $gallery->$caption . "</caption>";
   echo "<credit>" . $gallery->$credit . "</credit>";
   echo "</image>";
}
echo "</images>";

That gets returned as a variable $xml which I output like this:
$xmlProcessor = new GalleryXMLProcessor();
$xml = $xmlProcessor->processFeed("http://testurlexport.php");
header('Content-Type: text/xml;  charset=UTF-8');
echo $xml;

However, I simply get the output returned as text and not XML. It appears to simply echo. I have an XML viewer on Chrome and that doesn't render the XML into its intended UI. Before I started adding images, this worked fine (see below)

A: Sounds like the echo is returning text/xml. Try changing the mime type of the returned xml to application/xml


text:
Q: Drawing app for android using libGDX I am new to the libGdx framework but i have been developing android apps for couple months now. The problem that i'm facing is that i'm unable to get a way to make an app where i can draw the items as user make using gestures.
    I have searched a lot but couldn't find a work around to do the following using libgdx framework.
Basically what my plan is:

*

*I will check if the user is dragging "isdragging()", if yes i want to use either "DDA algorithm" to create the lines as per the inputs received from the "dragstart()" from the "Gesturedetection" interface but i'm not receiving any data from the methods.

*based on the user's action the pixmap will be rendered.
Any sort of help will be helpful.

A: assuming you are using Scene2D you can easily use DragListener binded with your stage to get (x,y) pointer position whenewer user will touch down the stage and move his pointer
stage.addListener(
    new DragListener()
    {
        public void drag(InputEvent event, float x, float y, int pointer)
        {
            Vector2 v = new Vector2(x, y);
            positionArray.add(v); //positionArray is Array<Vector2> type in this example
        }
    }
);

then you can just remember the position in an Array for example (Array seems to be nice choose) and in the render part you can use ShapeRenderer or some another tool to render these points. Because you have all points remembered you can easily remove them when using "rubber".
Regards,
Michał


text:
Q: How does std::vector resize its internal buffer? As far as I know, C++ does not support an operator like 'realloc(void *, size_t)' in C language.
However, std::vector should have a buffer to contain data, and the buffer should be expanded or compacted.
Then how could it be done to resize the buffer of std::vector without 'realloc' function?
Is it be done just by allocating new buffer, copy or move all elements and destructing previous buffer?
I think it is inefficient.

A:
As far as I know, C++ does not support an operator like 'realloc(void *, size_t)'

C++ does have std::realloc. But it is not (typically?) used to implement resizing of vector.

Then how could it be done to resize the buffer of std::vector without 'realloc' function?

Using following algorithm:

*

*allocate new array

*copy or move contents to the new array

*deallocate old array

Is it be done just by allocating new buffer, copy or move all elements and destructing previous buffer?

Yes.

I think it is inefficient.

Why do you think so? That's exactly what realloc does. Sure, realloc may sometimes be able to skip the copying depending on memory layout, which vector generally cannot. This is an unfortunate downside of vector compared to manually mallocated dynamic array, but it's not necessarily a significant downside.
There have been proposals to add reallocation support to standard allocators, which would allow the same optimisation if adopted into the standard: http://open-std.org/JTC1/SC22/WG21/docs/papers/2019/p0894r1.md

A: std::realloc is never used unless the container knows that the objects are TriviallyCopiable.
Source: https://en.cppreference.com/w/cpp/memory/c/realloc

Because reallocation may involve bytewise copying (regardless of
  whether it's to expand or to contract), only the objects of
  TriviallyCopyable types are safe to access in the preserved part of
  the memory block after a call to realloc.
Some non-standard libraries define a type trait "BitwiseMovable" or
  "Relocatable", which describes a type that doesn't have:

If the container cannot know that the objects are trivially copiable, then using realloc to expand the memory might result in corrupted data.
If is_trivially_copiable can be used on the container, then yes, using realloc is possible. Otherwise it will led to undefined behaviour.
Otherwise, the container a) creates new memory, b) calls copy or move constructor of the elements to move them to new memory c) frees old memory.

A: In case of a std::vector<bool> in theory there is nothing against the fact an equivalent of realloc is used internally, but looking at the implementation for g++ ( gcc version 6.3.0 20170516 / Raspbian ):
  template<typename _Alloc>
    void
    vector<bool, _Alloc>::
    _M_reallocate(size_type __n)
    {
      _Bit_pointer __q = this->_M_allocate(__n);
      iterator __start(std::__addressof(*__q), 0);
      this->_M_impl._M_finish = _M_copy_aligned(begin(), end(), __start);
      this->_M_deallocate();
      this->_M_impl._M_start = __start;
      this->_M_impl._M_end_of_storage = __q + _S_nword(__n);
    }

so it is based on a new allocation then copy then deallocation

A: std::vector has a resize function that allows you to expand or compact the array as needed.  If a reallocation does occur, it copy/moves the elements to the new allocation automatically.  This is a reason why iterators can become invalid.


text:
Q: \thepage cannot refer the roman page number I want to write 'A' in odd page number and 'B' in even page number. This code below only apply for arabic page number, but the roman page number can't. How to write 'A' in odd page number and 'B' in even page number for roman page?
\documentclass[a4paper,twoside,12pt]{book}
\usepackage[left=3cm,right=3cm,top=3cm,bottom=3cm]{geometry}
\usepackage{graphicx}
\usepackage{graphics}
\usepackage{xcolor}
\usepackage{background}
\usepackage{ifthen}

\backgroundsetup%
{   angle=0,
    opacity=1,
    scale=1,
    color=black,
    contents=%
    {
        \ifthenelse{\isodd{\thepage}}{%
            {\Huge A}
        }{
            {\Huge B}
        }
    }
}

\begin{document}
    \frontmatter
    \chapter{PREFACE}
    \newpage
    \chapter{ABC}
    \mainmatter
    \chapter{TEST1}
    \newpage
    \chapter{TEST2}
\end{document}

A: \thepage is the print form so i for roman which is not odd, use \value{page} which is the underlying number in the count register.


text:
Q: I'm trying to sort my files by date, how can I get the result into a table view? I have a tableview that's is been filled with .csv files from document directory. So far I'm able to get the date and sort them but not sure how to get the result in to an array and then into the tableview.
EDIT: i'm able to get it into an array but now when i try to get the files in the table view i got this error:
Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '-[NSURL length]: unrecognized selector sent to instance 0x1c00ba040'

Code:
--data
    NSMutableArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSFileManager *manager = [NSFileManager defaultManager];
NSMutableArray*   fileList = [manager contentsOfDirectoryAtPath:documentsDirectory error:nil];
//--- Listing file by name sort
NSLog(@"\n File list %@",fileList);

//---- Sorting files by extension
NSMutableArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:nil];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF EndsWith '.csv'"];
filePathsArray =  [filePathsArray filteredArrayUsingPredicate:predicate];
NSLog(@"\n\n Sorted files by extension %@",filePathsArray);

///
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleTableIdentifier = @"SimpleTableItem";
////gettime

NSArray  *paths3 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* fullPath = [paths3 objectAtIndex:0];
fullPath = [fullPath stringByAppendingPathComponent: [self.dirList objectAtIndex:indexPath.row]];
NSLog(@"%@", fullPath);

NSMutableArray *titleArray=[[NSMutableArray alloc]init];

NSString *fileDataString=[NSString stringWithContentsOfFile:fullPath encoding:NSUTF8StringEncoding error:nil];
NSArray *linesArray=[fileDataString componentsSeparatedByString:@"\,"];

int k=0;
for (id string in linesArray)
    if(k<[linesArray count]-1){

        NSString *lineString=[linesArray objectAtIndex:k];
        NSLog(@"%@",lineString);
        NSArray *columnArray=[lineString componentsSeparatedByString:@"\,"];
        [titleArray addObject:[columnArray objectAtIndex:0]];
        k++;

    }

NSLog(@"%@",[titleArray objectAtIndex:1]);

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier ];
if (cell == nil) {

    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];

cell.textLabel.text = [titleArray objectAtIndex:1 ];

cell.detailTextLabel.text = [self.dirList objectAtIndex:indexPath.row];

cell.textLabel.textColor = [UIColor colorWithRed:(0.0/255.0) green:(0.0/255.0) blue:(0.0/255.0) alpha:1];
cell.textLabel.font=[UIFont systemFontOfSize:8.0];

cell.detailTextLabel.font=[UIFont systemFontOfSize:15.0];
cell.detailTextLabel.textColor = [UIColor colorWithRed:(235.0/255.0) green:(120.0/255.0) blue:(33.0/255.0) alpha:1];

return cell;

}
////
- (IBAction) sortBydate: (id) sender
{

    NSError *err;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSURL *documentDirectoryURL = [fileManager URLForDirectory:NSDocumentDirectory
                                                      inDomain:NSUserDomainMask
                                             appropriateForURL:nil
                                                        create:false
                                                         error:&err];
    NSMutableArray *files = [[fileManager contentsOfDirectoryAtURL:documentDirectoryURL
                                        includingPropertiesForKeys:@[NSURLCreationDateKey]
                                                           options:0
                                                             error:&err] mutableCopy];

    [files sortUsingComparator:^(NSURL *lURL, NSURL *rURL) {
        id lDate = [lURL resourceValuesForKeys:@[NSURLCreationDateKey] error:nil][NSURLCreationDateKey];
        id rDate = [rURL resourceValuesForKeys:@[NSURLCreationDateKey] error:nil][NSURLCreationDateKey];
        return [lDate compare:rDate];
    }];

    NSLog(@"%@", files);

      self.dirList = [files mutableCopy];
    //
        self.data.reloadData;
   // NSLog(@"Sorted Array : %@",filePathsArray);

}

A: First of all NSSearchPathForDirectoriesInDomains is outdated. As you are using FileManager anyway use the modern URL related API URLForDirectory:inDomain:appropriateForURL:create:error:
Your code uses NSMutableDictionary which is useless because dictionaries are unordered.
To sort URLs you have to write a comparator which gathers and compares the  NSURLCreationDateKey resource.
The code make the files array mutable and sorts the URLs in place.
NSError *err;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *documentDirectoryURL = [fileManager URLForDirectory:NSDocumentDirectory
                                                  inDomain:NSUserDomainMask
                                         appropriateForURL:nil
                                                    create:false
                                                     error:&err];
NSMutableArray *files = [[fileManager contentsOfDirectoryAtURL:documentDirectoryURL
                           includingPropertiesForKeys:@[NSURLCreationDateKey]
                                              options:0
                                                error:&err] mutableCopy];

BOOL ascending = YES;

[files sortUsingComparator:^(NSURL *lURL, NSURL *rURL) {
    NSDate *lDate, *rDate;
    [lURL getResourceValue:&lDate forKey:NSURLCreationDateKey error:nil];
    [rURL getResourceValue:&rDate forKey:NSURLCreationDateKey error:nil];
    return ascending ? [lDate compare:rDate] : [rDate compare:lDate];
}];

NSLog(@"%@", files);


text:
Q: Book recommendations for Geometry I would like to know if there is a book on Geometry from a modern point of view which can guide me through the basics of the subject into more advanced graduate level material. I'm looking for a book on geometry that as closely resembles the books on Analysis by Herbert Amann and Joachim Escher in structure and presentation as possible because I really like those texts.
Do tell me about any other valuable sources that can help me with this
Thank you :)

A: I'm not familiar with Amann and Escher's book, but the classic introductory text to modern (algebraic) geometry is Hartshorne's book "Algebraic Geometry". This requires a good background in commutative algebra and basic topology, but it is worthwhile. Other texts that come to mind would be Eisenbud and Harris' "The Geometry of Schemes", Shafarevich's "Basic Algebraic Geometry", or Mumford's "Red Book of Varieties and Schemes". Also, though I'm not as familiar with it, I have heard that Ravi Vakil's book "The Rising Sea: Foundations of Algebraic Geometry" (available for download online) is very good.
If you're interested more in differential geometry, perhaps Lee's "Introduction to Smooth Manifolds" might be a good place to start, but maybe others have better suggestions in this respect.
A more comprehensive list of texts can be found in the responses here.


text:
Q: Status 404 error on AJAX list request in Laravel web.php
Route::group(['middleware' =>
    ['auth']], function () {

    Route::get(
        '/ajax-users/{$id}',
        'DashboardController@indexUsersAjax'
    )->name('ajax.users.index')
        ->middleware(['permission:Access Client Details Edit']);

Controller
/**
 * Display a listing of the resource Ajax.
 *
 * @param $id
 * @return json
 */
public function indexUsersAjax($id)
{
    $users = User::all();

    $defaultUser = Clients::find($id)
        ->default_user;

    return response()->json($users, $defaultUser);
}

AJAX
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        $.ajax({
            url: "{{ route('ajax.users.index',[1]) }}",
            type: 'GET',
            dataType: 'json',
            success: function(result){
                console.log(result);
            },
            error: function (data) {
                console.log('Error:', data);
            }});

Result on developer tools
GET http://localhost:8123/ajax-users/1 404 (Not Found)
Error: {readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}

I have added the Laravel code which I'm working on, couldnt find issue where doing wrong.

A: Parameters in Laravel routes don't include a dollar sign.
Replace '/ajax-users/{$id}' with '/ajax-users/{id}' and it should work.
In addition, the second parameter of response()->json() is the HTTP status. If you want to return both variables you have to put them into an array, for example:
return response()->json([$users, $defaultUser]);

A: Delete the $ from $id inthe route definition:
Route::get(
    '/ajax-users/{id}',
    'DashboardController@indexUsersAjax'
)->name('ajax.users.index')
    ->middleware(['permission:Access Client Details Edit']);

Delete if present the file bootstrap/cache/routes.php
Execute: php artisan route:list | grep /ajax-users/{id} and check it is present


text:
Q: Understanding what appears to be an instantiation of a method I am currently trying to understand how well regarded lightbox, ColorBox, works so that I can attempt to make a development to it. However I am struggling with a couple of concepts within the code. The following is where I am stuck:
I have the following function being declared:
publicMethod = function() {…}

Then after all that this function:
publicMethod.init = function() {…}

And finally at the end of the script the following command is run:
$(publicMethod.init);

Now I am not 100% sure what this last command is doing, I assume it is instanciating the method. But I would assume that you should be able to do that by just doing:
publicMethod.init;
Why is it wrapped inside a jQuery parentheses? What is the result of this?
Also, if I am correct in saying that it is instanciating publicMethod.init, does that mean that publicMethod is being instanciated first before publicMethod.init?

A: Haven't seen the code, but from your description:
publicMethod = function() { ... }
Declares and instantiated the function object named publicMethod. This obviously happens before declaring publicMethod.init since the latter is the init property of the object publicMethod, so the object publicMethod must exist for it to have properties augmented to it.
Regarding the $(publicMethod.init), that line would be executing the jquery function with a function parameter (not sure what "wrapping" means, this is exactly like executing jQuery(publicMethod.init) which is a function call).
Maybe it would look more familiar like this: $(function(){ ... }), or a similar and almost equivalent form: $(document).ready(function(){ ... }).
When the jquery function $ receives a function as its argument it adds a DOM ready handler, which is a function that will execute when the document is ready. That makes perfect sense with the code you pasted, since it passes the init method to be the one to execute when the document is ready.


text:
Q: Variable not found when pasting My code is supposed to export a picture, ranges and text boxes from Excel to PowerPoint. I am getting an error though where it's supposed to paste the ranges as bitmap. The error states that a variable is not found. I am new to VBA and needs some assistance if possible.
Here is the code I am using:
Option Explicit

Dim PPApp As PowerPoint.Application
Dim PPPres As PowerPoint.Presentation
Dim PPSlide As PowerPoint.Slide

Sub copy_to_ppt()

Dim wsname As String
Dim Shapes  As Shape
Dim Range As Range
Dim a, b As Integer

    Set PPApp = New PowerPoint.Application
    PPApp.Visible = True

    Set PPPres = PPApp.Presentations.Open("C:\Users\gdjwherr\Desktop\Brazil Reports\TRP     File\TRP Test Template.pptx")

    Sheets("Sheet1").Select

    '-----------------------------

    ActiveSheet.Shapes("Picture 1").Select
    Selection.Copy

            Set PPSlide = PPPres.Slides _
            (PPApp.ActiveWindow.Selection.SlideRange.SlideIndex)
            PPApp.ActiveWindow.ViewType = ppViewSlide
            PPSlide.Shapes.PasteSpecial(ppPasteJPG).Select

            PPApp.ActiveWindow.Selection.ShapeRange(1).Top =    PPApp.ActiveWindow.Selection.ShapeRange(1).Top + 60
            PPApp.ActiveWindow.Selection.ShapeRange(1).Left = PPApp.ActiveWindow.Selection.ShapeRange(1).Left + 20

ActiveSheet.Range("D3:E8").Select
Selection.Copy

        Set PPSlide = PPPres.Slides _
        (PPApp.ActiveWindow.Selection.SlideRange.SlideIndex)
        PPApp.ActiveWindow.ViewType = ppViewSlide
        Selection.PasteSpecial DataType:=wdPasteBitmap ```This is where the error occurs stating variable not defined and highlights wdPasteBitmap

        PPApp.ActiveWindow.Selection.ShapeRange(1).Top = PPApp.ActiveWindow.Selection.ShapeRange(1).Top + 60
        PPApp.ActiveWindow.Selection.ShapeRange(1).Left = PPApp.ActiveWindow.Selection.ShapeRange(1).Left + 0

    ActiveSheet.Range("G3:H8").Select
    Selection.Copy

            Set PPSlide = PPPres.Slides _
            (PPApp.ActiveWindow.Selection.SlideRange.SlideIndex)
            PPApp.ActiveWindow.ViewType = ppViewSlide
            Selection.PasteSpecial DataType:=wdPasteBitmap

            PPApp.ActiveWindow.Selection.ShapeRange(1).Top =    PPApp.ActiveWindow.Selection.ShapeRange(1).Top + 60
            PPApp.ActiveWindow.Selection.ShapeRange(1).Left = PPApp.ActiveWindow.Selection.ShapeRange(1).Left - 20

            Set PPSlide = Nothing
            Set PPPres = Nothing
            Set PPApp = Nothing

End Sub

A: A little bit of refactoring...
Sub copy_to_ppt()

    Dim PPApp As PowerPoint.Application
    Dim PPPres As PowerPoint.Presentation
    Dim ppSlide As PowerPoint.Slide
    Dim wsname As String
    'Dim Shapes  As Shape 'don't do this!
    'Dim Range As Range 'don't do this!
    Dim a, b As Integer
    Dim oLayout

    Set PPApp = New PowerPoint.Application
    PPApp.Visible = True

    Set PPPres = PPApp.Presentations.Open("C:\Users\gdjwherr\Desktop\Brazil Reports\TRP     File\TRP Test Template.pptx")
    PPApp.ActiveWindow.ViewType = ppViewSlide
    Set ppSlide = PPPres.Slides _
        (PPApp.ActiveWindow.Selection.SlideRange.SlideIndex)

    Sheets("Sheet1").Shapes("Picture 1").Copy
    PP_Paste ppSlide, ppPasteJPG, 100, 100

    Sheets("Sheet1").Range("D3:E8").Copy
    PP_Paste ppSlide, ppPasteBitmap, 100, 300

    Sheets("Sheet1").Range("G3:H8").Copy
    PP_Paste ppSlide, ppPasteBitmap, 100, 500

    Set ppSlide = Nothing
    Set PPPres = Nothing
    Set PPApp = Nothing

End Sub

Sub PP_Paste(ppSlide As PowerPoint.Slide, fmt, posTop, posLeft)
    With ppSlide.Shapes.PasteSpecial(fmt)
        .Top = posTop
        .Left = posLeft
    End With
End Sub


text:
Q: Difficulties with a++, ++a I start programming about one month ago, and i have some difficulties with the operators ++a, a++ in java.
Can someone explain me line by line this program?
import java.util.Scanner;
public class Number {
 public static void main(String[] args) {
 Scanner keyboard = new Scanner(System.in);
 int number = keyboard.nextInt();
 int division1 = (number++) % 10;
 number = number / 10;
 System.out.println(number % 10+division1);
 }
}

A: ++a is a pre-incrementation. Which means that a is incremented before returning the value of a.
a++ is a post-incrementation. Which means that a is incremented after returning the value of a.
In other words, a++ gives the current value of a and then increment it. While ++a directly increment a. If a=42 then System.out.println(a++) gives 42 while System.out.println(++a) gives 43 and in both cases, a=43 now.
OP also asked for a line by line explanation of that code:
import java.util.Scanner;

public class Number {
 public static void main(String[] args) {
   Scanner keyboard = new Scanner(System.in);
   int number = keyboard.nextInt();
   int division1 = (number++) % 10;
   number = number / 10;
   System.out.println(number % 10+division1);
 }
}

I guess, only the code inside the main function need some explanations :
   // Create a Scanner object that read from the standard input.
   Scanner keyboard = new Scanner(System.in);

   // Read an integer.
   int number = keyboard.nextInt();

   // put (number % 10) into variable division1 and then increment `number`.
   int division1 = (number++) % 10;

   // Divide number by 10.
   number = number / 10;

   // Print that expression :
   System.out.println(number % 10+division1);

The line int division1 = (number++) % 10; might not be very clear. It would be simpler to read like that:
int division1 = number % 10;
number += 1;

Now, the explanation of what the function does:
If number = 142, we put 2 into variable division1, then number is incremented and divided by 10. So number gets the value 14 ((142+1) / 10). And now we print number % 10 + division1 which is 4 + 2 = 6.
Here some examples of results (I've compiled the code myself):
3 => 3
9 => 10
10 => 1
248 => 12

A: int division1 = (number++) % 10;

Is equivalent to :
int division1 = number % 10;
number += 1;

While
int division1 = (++number) % 10;

Would be equivalent to :
number += 1;
int division1 = number % 10;

Basically, your code is equivalent to :
int number = new java.util.Scanner(System.in).nextInt();
System.out.println( ((number + 1) / 10) % 10 + number % 10 );

A: Literally line-by-line explanation:
import java.util.Scanner; // Import Scanner
public class Number {     // Create Java class called Number
    public static void main(String[] args) {  // Define the main function
        Scanner keyboard = new Scanner(System.in); // Initialize the scanner
        int number = keyboard.nextInt();   // Read an integer from standard input
        int division1 = (number++) % 10;   // Take the unit digit of number, then increase number by 1
        number = number / 10; // Divide number by 10
        // Take the tens digit of the original number (or tens digit + 1, if the unit was 9), sum with the unit digit previously stored in division1
        System.out.println(number % 10+division1);
        // The result would sum the last two digit of number if it doesn't end with 9, or sum the last two digit +1 if the unit was 9.
    }
}

Some cases:

f(1) = 1
f(124) = 2+4 = 6
f(39) = 4+9 = 13
f(5248) = 4+8 = 12

A: ++a is a pre-incrementation. Which means that a is incremented before the expression is evaluated.
a++ is a post-incrementation. Which means that a is incremented after the expression is evaluated.
One thing where beginners might be confused is what is this 'expression' after which the increment takes place
It is actually the ;
When you use a++, it is after the ";" when the increment actually takes place
and when you use ++a; it is just as you inserted a statement before this one saying a=a+1 and then your expression comes.

A: I think, the interesting part for you are the following lines:
int number = keyboard.nextInt();

Here, you get an input from the user. Say, he enters 12
int division1 = (number++) % 10;

division1 will become 2, because 12 mod 10 equals 2.
After this, number will be incremented by 1, so it is now 13
Let's now assume there would be a ++number instead of number++. In this case, we would increment number before the modulo operation. So, first, number becomes 13, then we assign 3 to division1.
And that's the basic thing about a++ and ++a - the time, when the value is incremented. a++ means, all operations use a as it is and as a last step, a is incremented. ++a works in the other order.


text:
Q: Does CFT in AdS/CFT live in flat spacetime? As the title says, does CFT in AdS/CFT live in flat spacetime, or is it only approximately flat?

A: The CFT in AdS/CFT lives on the asymptotic boundary of the AdS space. The asymptotic boundary is a conformal manifold associated to any "visibility manifold". See this paper of Eberlein and O'Neil (1973), section 1. They define points on the asymptotic boundary as equivalence classes of geodesic rays where geodesic rays are considered equivalent if their distance is asymptotically bounded from above.
One can thus think about the tangent space of the asymptotic boundary to be the normal directions to a geodesic along which nearby geodesics can diverge. This lets one define a conformal structure. There is clearly no natural Riemannian structure on the boundary (and reparametrizations of the geodesics act like Weyl transformations) so if the boundary theory is to be defined in terms of the bulk, it has to be conformally invariant.
However this classical picture breaks slightly when quantizing, and in the end we do have to choose a metric to regulate our theory (this is the case with almost all CFTs). Then we get some mild dependence on the chosen metric through the Weyl anomaly.


text:
Q: How to use JOptionPane.showMessageDialog once in the prograde How many times have you used the statement:
JOptionPane.showMessageDialog? If your answer is more than once go back and
revise your code so that you only use ONE JOptionPane.showMessageDialog
Hint: consider using a variable of type String named output
Code
if(credit >= 120)
  {

     JOptionPane.showMessageDialog(null,"You've graduated!");

  }//end if

  else if(credit >= 90)

  {

     JOptionPane.showMessageDialog(null,"You're a senior.");

  }//end if

  else if(credit >= 60)

  {

     JOptionPane.showMessageDialog(null,"You're a junior.");

  }//end if

  else if(credit >= 30)

  {

     JOptionPane.showMessageDialog(null,"You're a sophomore.");

  }//end if

  else if(credit >=0)

  {

     JOptionPane.showMessageDialog(null,"You're a freshment.");

  }//end if

  else

  {
     JOptionPane.showMessageDialog(null,"invalid input");

A: Use the if-else statements to generate the String to show, then use a single line to call showMessageDialog() using the String.

A: //don't forget to import the JOptionPane library
//also I have no clue how you used your credit variable
public class prograde
{
    public void showJoption(String position)
    {
        JOptionPane.showMessageDialog(null, position);
    }
public static void main(String[] args)
{
    //this is the class object that you can use to call the showJoption() method.
    prograde display = new prograde();

    if(credit >= 120)
    {
        display.showJoption("You've graduated!");
    }
    else if (credit >= 90)
    {
        display.showJoption("You're a senior.");
    }
    else if (credit >= 60)
    {
        display.showJoption("You're a junior.");
    }
    else if (credit >= 30)
    {
        display.showJoption("You're a sophomore.");
    }
    else if (credit >= 0)
    {
        display.showJoption("You're a freshment.");
    }
    else {
        display.showJoption("invalid input");
    }
}

}


text:
Q: QtCreator does not open terminal for building I was using qmake build system in my QtCreator 4.1.0-beta1, everything was fine. When I ran my project, a new terminal popped up.
When I switched to CMake build system, no new terminal window was created anymore. How can I force QtCreator to run the build in a new terminal window like it does with qmake?

A: Projects -> Build & Run -> Run -> Check "Run in terminal"


text:
Q: Ajax call form different domain with jQuery not rendering proper data I have this code in javascript
var url = 'http://mydomain.com:3000';
url += "/user";

jQuery.ajax({
  url: url,
  type: "GET",
  dataType: "jsonp",
  async: false,
  success: function (data) {alert(1);
    console.log(data);
  }
});

where my site runs on http://mydomain.com:80 so they are not in the same server.
http://mydomain.com:3000 is served by nodejs with the code
app.get('/user',function(req,res){
  var result = {
    result:-1
  };
  res.json(result);
  res.writeHead(200, {"Content-Type": "application/json"});
});

When I call the ajax I get from the chrome preview response
{
  "result": -1
}

but in the console of the javascript I got the error
Uncaught SyntaxError: Unexpected token : user:2

and I don't get any alert message.
I even tried in nodejs
res.end("'"+JSON.stringify(result)+"'");

and the chrome preview response is
'{"result":-1}'

and the console error is gone but still the alert is not triggered

A: res.json() sends the response immediately. You have to set headers before using this.
res.json(result);
res.writeHead(200, {"Content-Type": "application/json"}); //Response already sent before.

So res.writeHead() does not set header in response. The error that you are getting means that there is some illegal character code in your response.

Uncaught SyntaxError: Unexpected token : user:2

Try setting headers before, browser will then correctly identify your message as JSON.
Update
On checking your code again I saw that you are sending response as res.json() but in your AJAX recieving it as jsonp. The two are different json and jsonp. There is a res.jsonp() you can use in node or change datatype in your AJAX query as json.