text:
Q: Can't figure why my dynamically concatenation of JSX elements doesn't work How can I dynamically create JSX elements, such that some of the string is bold and some is code? For some reason my algorithm doesn't really works.
In other words, I receive a string that looks like this:
Hello *Stackoveflow*, I try to do `React.js` today.

I try to dynamically parse this string and make it looks like this:
Hello Stackoveflow, I try to do React.js today.

For some reason it doesn't work.
I parse my string & try to return the JSX element I created:
export const Description = (props) => {
  const description = props.currentDescription.toString();

  let descriptionContent = "";

  let stringFlag = true;
  let stringContent = "";
  let codeFlag = false;
  let codeContent = "";
  let boldFlag = false;
  let boldContent = "";
  let char = "";

  for (let i = 0; i < description.length; i++) {
    char = description[i];

    if (char === "`") {
      codeFlag = !codeFlag;

      if (codeFlag) {
        stringFlag = false;
        descriptionContent += stringContent;
        stringContent = "";
      } else {
        descriptionContent += {codeContent};
        stringFlag = true;
        codeContent = "";
      }
    } else if (char === "*") {
      boldFlag = !boldFlag;

      if (boldFlag) {
        stringFlag = false;
        descriptionContent += stringContent;
        stringContent = "";
      } else {
        descriptionContent += {boldContent};
        stringFlag = true;
        boldContent = "";
      }
    } else {
      if (codeFlag) {
        codeContent += char;
      }

      if (boldFlag) {
        boldContent += char;
      }

      if (stringFlag) {
        stringContent += char;
      }
    }
  }
  stringFlag = false;
  descriptionContent += stringContent;
  stringContent = "";

  return
{descriptionContent}
;
};

However, in return, I receive this result:
Hello [Object object], I try to do [Object object] today.

Could anyone help me figure this out?

A: You can't concat (+=) JSX as they are objects. By using dangerouslySetInnerHTML you can render the HTML elements from a string (but only HTML elements, not components).
So this fix should work:

Notice that its a usecase for Regex, so you can simplify the logic much more:
const generateReplacer = (regex, element) => (match) => {
  const fixedWord = match.replaceAll(regex, "");
  return `<${element}>${fixedWord}</${element}>`;
};

export const Description = (props) => {
  const description = props.currentDescription;

  return (

      <div
        dangerouslySetInnerHTML={{
          __html: description
            .replace(/\*.+\*/, generateReplacer("*", "strong"))
            .replace(/`.+`/, generateReplacer("`", "code"))
        }}
      />

  );
};

I suggest checking markdown-to-html libraries that already implementing it.

A: One option could be to create an array of JSX elements from the string instead of concatenating the string together.
export const Description = (props) => {
  const description = props.currentDescription.toString();

  let descriptionContent = [];

  let stringFlag = true;
  let stringContent = "";
  let codeFlag = false;
  let codeContent = "";
  let boldFlag = false;
  let boldContent = "";
  let char = "";

  for (let i = 0; i < description.length; i++) {
    char = description[i];

    if (char === "`") {
      codeFlag = !codeFlag;

      if (codeFlag) {
        stringFlag = false;
        descriptionContent.push(stringContent);
        stringContent = "";
      } else {
        descriptionContent.push({codeContent});
        stringFlag = true;
        codeContent = "";
      }
    } else if (char === "*") {
      boldFlag = !boldFlag;

      if (boldFlag) {
        stringFlag = false;
        descriptionContent.push(stringContent);
        stringContent = "";
      } else {
        descriptionContent.push({boldContent});
        stringFlag = true;
        boldContent = "";
      }
    } else {
      if (codeFlag) {
        codeContent += char;
      }

      if (boldFlag) {
        boldContent += char;
      }

      if (stringFlag) {
        stringContent += char;
      }
    }
  }
  stringFlag = false;
  descriptionContent.push(stringContent);
  stringContent = "";

  return
{descriptionContent}
;
};

See demo here


text:
Q: Top-Down navigation drawer following image is a top down sliding navigation drawer (after click on navigation icon action bar become to menu), how can I modify navigation drawer to be something like this? is there any library for it?
thanks.

A: You could try to use a "reversed" Bottom Sheet component and fill it with a custom ListView as a menu.
I've found this repository on github for building a "top sheet", hope it helps!

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the suitable type for renderHook in react-testing-library and TypeScript? I wanna test a custom hook with react-testing-library therefore, I add this code into beforeEach:
let renderedHook ;

beforeEach(() => {
  renderedHook = renderHook(() => useFetch());
});

test('.....', () => {
  expect(renderedHook.current.data).toBe(1);
});

the above code works well! but I'm using TypeScript, what's the suitable type for let renderedHook  in this case?

A: If your IDE or editor supports the "Go to Definition" feature, you can check the TS type of renderHook.
The return type of renderHook is RenderHookResult
E.g.
import { Renderer, renderHook, RenderHookResult } from '@testing-library/react-hooks';
import { useState } from 'react';

const useFetch = () => {
  const [data] = useState(1);
  return { data };
};

let renderedHook: RenderHookResult<unknown, { data: number }, Renderer<unknown>>;

describe('72601993', () => {
  beforeEach(() => {
    renderedHook = renderHook(() => useFetch());
  });

  test('.....', () => {
    expect(renderedHook.result.current.data).toBe(1);
  });
});

package version:
"@testing-library/react-hooks": "^8.0.0",

A: Though the Question is about suitable types, anyone who wants beforeEach functionality in tests and don't want to find suitable types from IDE support, you can create a function like setup
const setup = () => {
   const {result} = renderHook(() => useFetch());
}

Now you can use it every test without thinking about suitable test and it will show intellisense as well. The usage of the setup is shown below
it('should return data equal to 1' => {
  result = setup();
  expect(result.current.data).toBe(1)
})


text:
Q: Create element wise dictionary from python arrays From these arrays:
t = ["A","B","C"]
a = [1,2,3]
b = [4,5,6]
c = [7,8,9]

how can I obtain a list like this
[
  { 'A':1, 'B':4, 'C':7},
  { 'A':2, 'B':5, 'C':8},
  { 'A':3, 'B':6, 'C':9},
]

so that it is more useful one dumped in JSON?

A: You can do this:
t_data = [a, b, c]
[{u:v for u, v in zip(t, xs)} for xs in zip(*t_data)]


text:
Q: How do I deal with the edge tile? How do I build/dig on the edge tile of a map? My dwarves are walking around the edge of a moat; I assume invaders will too.

A: You can't. You'll have to find another way to block off access. Sounds like you might be able to build a wall up to your moat; get creative!

A: You cannot dig or build on the edge tile, to prevent you from completely cutting yourself off from the world (for good or ill).  Most people simply dig a most 4-10 tiles in from the edge of the map.

A: According to the DF wiki, "You're not allowed to wall within five squares of the edge of the map... but this rule has more loopholes than the US federal income tax code."
Some tactics allowed by DF that may apply to this problem:
1) You can build floors all the way to map edge. A floor built over a ramp that is then removed, removes the ramp. Removing ramps at map edge may stop the ability of foes to path-find into your map.
2) You can smooth un-mined stone and then fortify it even if the tile is at the map edge.
3) You can build a drawbridge at map edge. A raised drawbridge acts as a wall. This won't stop flying foes, but it works against normal goblin sieges.


text:
Q: Request with status:401 and popup message fails Have assertion with 401 request, which passes, but want, also, to confirm popup error which appears (that part fails). Below are screenshots of page layout and test results:

And code which wrote:
it('should not be loaded any data without mocks', () => {
cy.visit('/partURL');
cy.server();
cy.route({
  method: 'GET',
  url: '**/forms?workspace?**',
}).as('myUrlAlias');
cy.wait('@myUrlAlias')
  .its('status')
  .should('eq', 401);
 cy.get('div.inner_page__content div.embedded_alert__wrapper img')
  .should('have.attr', 'src')
  .and('include', 'alt');
  });

A: It seems to me your chain on the target element is wrong. .and() checks for assertion on the original element, if you wana check the attr - you should chain a second .should(). Here an alternative idea:
it('should not be loaded any data without mocks', () => {
    cy.visit('/partURL');
    cy.server();
    cy.route({
        method: 'GET',
        url: '**/forms?workspace?**',
    }).as('myUrlAlias');
    cy.wait('@myUrlAlias')
        .its('status')
        .should('eq', 401);
    cy.get('img[alt="Warning icon"]')
        .should('exist')
});


text:
Q: Creating a Menu in Android Activity - WindowManager$BadTokenException I have an activity that shows the option menu. The only option I have currently is "stop". The goal is to stop a service that is running when "stop" is selected.
Here is my code:
public class MenuActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onResume() {
        openOptionsMenu();
        super.onResume();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.stop, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection.
        switch (item.getItemId()) {
            case R.id.stop:
                stopService(new Intent(this, MyService.class));
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onOptionsMenuClosed(Menu menu) {
        // Nothing else to do, closing the Activity.
        finish();
    }

}

When I run this, I see that first "onCreate: is called, then "onResume" is called, then "onCreateOptionsMenu" is called. But after this I am getting this error:
W/WindowManager(  439): Failed looking up window
W/WindowManager(  439): java.lang.IllegalArgumentException: Requested window null does not exist
W/WindowManager(  439):   at com.android.server.wm.WindowManagerService.windowForClientLocked(WindowManagerService.java:8108)
W/WindowManager(  439):   at com.android.server.wm.WindowManagerService.addWindow(WindowManagerService.java:2150)
W/WindowManager(  439):   at com.android.server.wm.Session.addToDisplay(Session.java:160)
W/WindowManager(  439):   at android.view.IWindowSession$Stub.onTransact(IWindowSession.java:111)
W/WindowManager(  439):   at com.android.server.wm.Session.onTransact(Session.java:123)
W/WindowManager(  439):   at android.os.Binder.execTransact(Binder.java:351)
W/WindowManager(  439):   at dalvik.system.NativeStart.run(Native Method)
D/AndroidRuntime( 3109): Shutting down VM
W/dalvikvm( 3109): threadid=1: thread exiting with uncaught exception (group=0x2b590930)
W/WindowManager(  439): Attempted to add window with token that is not a window: null.  Aborting.
E/AndroidRuntime( 3109): FATAL EXCEPTION: main
E/AndroidRuntime( 3109): java.lang.RuntimeException: Unable to resume activity {com.google.glass.myapp/com.google.glass.myapp.MenuActivity}: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
E/AndroidRuntime( 3109):  at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2742)
E/AndroidRuntime( 3109):  at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2771)
E/AndroidRuntime( 3109):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2235)
E/AndroidRuntime( 3109):  at android.app.ActivityThread.access$600(ActivityThread.java:141)
E/AndroidRuntime( 3109):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
E/AndroidRuntime( 3109):  at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime( 3109):  at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime( 3109):  at android.app.ActivityThread.main(ActivityThread.java:5041)
E/AndroidRuntime( 3109):  at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime( 3109):  at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime( 3109):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
E/AndroidRuntime( 3109):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
E/AndroidRuntime( 3109):  at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime( 3109): Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
E/AndroidRuntime( 3109):  at android.view.ViewRootImpl.setView(ViewRootImpl.java:590)
E/AndroidRuntime( 3109):  at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:246)
E/AndroidRuntime( 3109):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
E/AndroidRuntime( 3109):  at com.android.internal.policy.impl.PhoneWindow.openPanel(PhoneWindow.java:655)
E/AndroidRuntime( 3109):  at com.android.internal.policy.impl.PhoneWindow.openPanel(PhoneWindow.java:523)
E/AndroidRuntime( 3109):  at android.app.Activity.openOptionsMenu(Activity.java:2819)
E/AndroidRuntime( 3109):  at com.google.glass.myapp.MenuActivity.onResume(MenuActivity.java:44)
E/AndroidRuntime( 3109):  at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1187)
E/AndroidRuntime( 3109):  at android.app.Activity.performResume(Activity.java:5183)
E/AndroidRuntime( 3109):  at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2732)
E/AndroidRuntime( 3109):  ... 12 more
W/ActivityManager(  439):   Force finishing activity com.google.glass.myapp/.MenuActivity

What's going on here? Any help will be much appreciated. Thanks!

A: The problem is in your onResume method. Try calling the super method first.
    @Override
    public void onResume() {
        super.onResume();
        openOptionsMenu();
    }

instead of
    @Override
    public void onResume() {
        openOptionsMenu();
        super.onResume();
    }


text:
Q: Is it possible to completely turn off nvidia GPU to be able to run wayland? I'm about to buy a new laptop that is being used with Linux only. Unfortunately finding a Linux laptop is not simple at all, and it seems the only option I found includes a nvidia Quadro M1200 and an Intel HD 630.
I know that it is very complex/impossible to properly run wayland (Ubuntu for instance) on nvidia. Actually I don't care in any way about the nvidia GPU, the Intel GPU should be more than sufficient. But is it possible to completely disable the nvidia GPU to let wayland run properly on the Intel GPU? I read about nvidia prime: can I use it like this? Can I completely disable nvidia and just forget about it, like it was not even there?

A: The answer was simple: just install nvidia drivers, open the nvidia settings page and set to use the Intel HD GPU only. Login again and you are done. Works perfectly. Battery lasts much much longer and wayland works properly.
As soon as the nvidia GPU is enabled, it seems that the fan turns on immediately, and keeps running even when idle. That is probably a large part of battery consumption. I'm wondering if that is reasonable or not: is that fan really always needed?
NOTE: I recently discovered that what I described is a Ubuntu specific patch applied to the nvidia config app. Other distros may not include it entirely. Manjaro, for instance, is not including it in any way. It is probably possible to setup manually, but I didn't succeed.
NOTE2: blacklisting nvidia and nouveau is sufficient to run on Intel only. Not sure how to run on nVidia only.

A: I am just here to answer this question
Although I have not used a Optimus laptop for years. Bumblebee community created a kernel module bbswitch
https://github.com/Bumblebee-Project/bbswitch
You can turn off the nvidia card as long as a driver is not loaded.
 # to check status
 $ cat /proc/acpi/bbswitch

 # to turn off or on respectably
 $tee /proc/acpi/bbswitch <<<OFF
 $tee /proc/acpi/bbswitch <<<ON

If I knew there was a thread, I would had posted the answer much earlier.
I guess I am fighting against https://xkcd.com/979/

A: On some notebooks (the venerable Lenovo TP 520W being an example), one can select which graphics board to use in the BIOS setup (in this example "Auto", "Discrete" (NVIDIA), "Internal" (Intel) - IIRC).
Setting to internal will save a lot of power, make installation easier, but might impede the use of external displays.

A: To gather information about the laptop model, install dmidecode. For the DSDT/SSDT
files, install the acpidump and iasl tools:
sudo apt-get install acpidump iasl dmidecode

or (on Fedora):
sudo yum install pmtools iasl dmidecode

Then use the script from http://lekensteyn.nl/files/get-acpi-info.sh to create the
tarball containing information about the laptop model, PCI hardware and ACPI tables.
To do so, run the following commands in a terminal:
wget http://lekensteyn.nl/files/get-acpi-info.sh
sh get-acpi-info.sh

This will create a tar.gz file that you can attach to the bug report. In the comment itself, please include a link to the product page of the model (if available).
Given this information, it will be possible to know if there is any existing software that can switch off your Nvidia graphics card or if the software needs to be adapted to be compatible with the BIOS of your laptop.


text:
Q: How to catch angularfire2 error I am trying to add to a firebase database.
It adds all well and I get success in my promise then function.
However when I intentionally try to throw and error, then .catch callback doesn't log any error. Instead it refreshes the page.
Here is my component :
 submitForm(value: any){
    this._someService.listPlaces(pName.value, pCategory.value, pAddress.value, this.lat, this.lng)
    .then(_ => console.log('success'))
    .catch(err => console.log(err, 'Failed!'));
  }

And here is my _someService service :
listPlaces(name, cat, add, lat, lng) {
  return this.places.set({
            placeID: this.placeID,
            placeName: name,
            placeCat: cat,
            placeAdd: add,
            authorID: this.uid,
            author: this.username,
            lat: lat,
            lng: lng,
            rating: 0.5,
            listDate: firebase.database.ServerValue.TIMESTAMP
        });
    }

What Is it am doing wrong? How can I catch the angularfire2 return catch error in a promise and prevent my page from refreshing.


text:
Q: Google Cloud DNS & ProtonMail DKIM records ProtonMail has rolled out support for receiving mail from custom domains, and I'm adding the necessary records to my project's Cloud DNS settings from within Google Cloud Platform. I added the MX and SPF records, and they checked out, but when I try to add the DKIM records I get a "Not Properly Set" error from ProtonMail's end. I followed the same format, putting protonmail._domainkey in the hostname, adding it as a TXT record, and including v=DKIM1; k=rsa; p=... in the record value.
ProtonMail technical support wasn't very helpful, replying with a "we don't see your TXT DKIM records, please ensure they are being properly propagated" response.
I can provide the other records I've set if anyone thinks it would be helpful.

A: Your DKIM record may need to be wrapped in quotes.
Try:
"v=DKIM1; k=rsa; p=..."

I had the exact same issue with DKIM on protonmail. Protonmail support suggested verifying the records via mxtoolbox.com. Since I could see that my TXT record wasn't showing up as I had written it, I emailed my domain provider for help. They added quotes to the TXT record, and then I could see the record properly on mxtoolbox.com.

A: Are you able to retrieve your DKIM record with this tool:
http://mxtoolbox.com/dkim.aspx
Enclosing your DKIM TXT entry in quotes may solve the issue. Many DKIM libraries have issues with spaces after the semicolons.
Did you attempt to use a key larger than 1024 bits?
If you provide the domain name that your are having an issue with, I will look at the DKIM information in the zone.


text:
Q: loading a List from datatable with generic method I load 10 different List< T > with datatable.
The datatable is loaded from a Sqlite Database.
To do this, I'm repeating 10 times the same method.
Here is an example of my code:
//List to be load
public static List<AircraftModel> Aircraft = new List<AircraftModel>();
public static List<AirlineModel> Airline = new List<AirlineModel>();

//Method to load the list Aircraft with the datatable
public void LoadAircraft(DataTable data)
    {
       foreach (DataRow row in data.Rows)
        {
          Aircraft.Add(new AircraftModel
            {
                Id = Int32.Parse(row["id"].ToString()),
                Registration = row["registration"].ToString(),
                Capacity = Int32.Parse(row["capacity"].ToString()),
                Type = row["type"].ToString()
            });
        }
    }

//Method to load the List Airline with datatable
public void LoadAirline(DataTable data)
    {
        foreach (DataRow row in data.Rows)
        {
            Airline.Add(new AirlineModel
            {
                Code = row["code"].ToString(),
                AirlineName = row["name"].ToString()
            });
        }
    }

Would it be possible to optimize my code with a generic method like this:
//call method to load the List
 GetData<AircraftModel>(Aircraft, datatable);
 GetData<AirlineModel>(Airline, datatable);

//Unique generic method to load the 10 List < T >
public void GetData<T>(List< T > ListToBeLoad, DataTable table)
       where T : class, new()
    {

        foreach (DataRow row in table.Rows)
        {
            ListToBeLoad.Add( new T
            {
              ......
              HELP NEEDED PLEASE
              ......
            }
        }
    }

thanks in advance for your reply and propositions
Cyrille

A: You have couple of methods, you can create a mapping method and pass it as an argument, or you can use AutoMapper.
Here is 2 examples of the first solution (Without AutoMapper)
Example of populating to existing list
PopulateList(list, dataTable, (row) =>
    new AircraftModel
    {
        Id = int.Parse(row["id"].ToString()),
        Registration = row["registration"].ToString(),
        Capacity = int.Parse(row["capacity"].ToString()),
        Type = row["type"].ToString()

    }
);

public static void PopulateList<T>(List<T> list, DataTable data, Func<DataRow, T> mapFunc)
    where T : new()
{
    foreach (DataRow row in data.Rows)
    {
        list.Add(mapFunc(row));
    }
}

Example of creating a new list and mapping the rows.
var list2 = Map(dataTable, (row) =>
    new AircraftModel
    {
        Id = int.Parse(row["id"].ToString()),
        Registration = row["registration"].ToString(),
        Capacity = int.Parse(row["capacity"].ToString()),
        Type = row["type"].ToString()

    }
);

public static IEnumerable<T> Map<T>(DataTable data, Func<DataRow, T> mapFunc)
    where T : new()
{
    foreach (DataRow row in data.Rows)
    {
        yield return mapFunc(row);
    }
}

A: As you may have noticed, the issue is that you need to know the columns in order to get the right data, and to know the properties in order to store it in the right place. As a result, your code needs to be aware of each of the individual classes - and that's fine: You're not going to get rid of this code.
Generally, when you want to construct something, you may want to think of a factory, that is, a method (or class) that is capable of constructing an instance of a specific type. A factory class, in your case, could look like the following:
public abstract class Factory<T>
{
    public T Create(DataRow row);
}

Now the next thing you would do is creating specific instances for each type you want to create, e.g.
public sealed class AirlineModelFactory : Factory<AirlineModel>
{
    public override AirlineModel Create(DataRow row)
    {
        return new AirlineModel
        {
            Code = row["code"].ToString(),
            AirlineName = row["name"].ToString()
        };
    }
}

Now the boilerplate code is this:
public void GetData<T>(List<T> list, DataTable table, Factory<T> factory)
where T : class, new()
{
    foreach (DataRow row in table.Rows)
    {
        list.Add(factory.Create(row));
    }
}

and you may call it as
GetData(AirlineList, table, new AirlineModelFactory());
GetData(AirpoirtList, table, new AirportModelFactory());
// etc.

although, arguably, you may want to keep your factory instances around (or even inject them for inversion of control) to avoid the new.
However, as you will notice, you still need to create N classes / methods for N types.
To automate things a bit more, you could introduce a "generic" base class to your factories, e.g.
public abstract class GenericFactory
{
    public abstract object CreateObject(DataRow row);
}

and then implement
public abstract class Factory<T> : GenericFactory
{
    public override object CreateObject(DataRow row) => Create(row);
    // ...
}

With this, you could think of a lookup dictionary Dictionary<Type, GenericFactory>. By picking the right type and then casting to the right T, you get your correct instance. This is, however, a service locator pattern - a code smell, because a missing registration in the dictionary leads to an error at runtime - but depending on your needs, it could still be of help.


text:
Q: NN type/architecture needed for inverse covariance matrix approximation The idea is to construct a neural network (NN) that takes N series of financial returns as input and returns the (approximation of the) inverse of the sample covariance matrix (an N times N matrix). I was wondering if there are any heuristics/rules of thumb for the architecture (depth, width) and type (convolutional, recurrent etc.) of NN suitable for such a task.

A: Related to your question, there are times when you want to use something like inverse covariance estimation to perform link prediction across time series.
For this you can include an inverse covariance layer in a neural network that takes as input time series:
https://proceedings.neurips.cc/paper/2014/file/8b16ebc056e613024c057be590b542eb-Paper.pdf


text:
Q: Office JavaScript API running under the hood Please correct me if I am wrong, I am pretty confused as to how Office Add-in works under the hood:-

*

*When I made a Office JavaScript API call within an Office Addin (which is an embedded browser), the request is being handled by Node.js and will be routed to the proper destination in the Office desktop application?

*Then, how will the Office desktop application process with the request? Are there any ways to look into the source code on what code it would run based on the specific javascript call?

A: *

*Your JavaScript code that calls Office JavaScript APIs runs in the JavaScript runtime of the embedded browser, not in Node.js. (Node.js does not run in a browser or embedded browser.)

*Office.js uses the JavaScript runtime's ability to call out to its host to call out to the hosting Office application. Office translates the call into a C++ call to the Office application's DLLs. If the call returns anything, this is passed by Office back to the JavaScript runtime, which passes it back to your calling code. The Office Suite is not open source and I don't think there is any public mapping of the Office JavaScript APIs to the internal C++ code.


text:
Q: scanner continues scanning few more pages even after stopping by setting CancelAll to false in TransferReady NTWAIN I am stopping the scanning by the below code
_twain.TransferReady += (s, ev) => { ev.CancelAll = true; };
The status changes to end scanning and it no more takes any pages from scanner but still the scanner feeder takes few more pages from Scanner device without sending it to driver.
I am using NTwain Version 3.0.0.0
Can anyone please help me on this ?


text:
Q: Why do lasers from Kyber crystals in lightsabers repel noisily but lasers from Kyber crystals in the Death Star combine? Rogue One introduced the idea of Kyber Crystals in the Star Wars movie Canon.
In the 1977 movie A New Hope - we see Obi-Wan Kenobi and Darth Vader battle with lightsabers and the blades repel with a 'clashing' sound.

Also in the 1977 movie A New Hope, they introduce the Death Star. According to Rogue One the laser in this was also built using Kyber Crystals. We see in this the laser beams coming together to combine into one large beam:

My question is: Why do lasers from Kyber crystals in light-sabers repel noisily but lasers from Kyber crystals in the Death Star combine?

A: Lightsabers and "Lasers" (AKA blasters) in Star Wars both work on the principles of trapping plasma in a powerful electromagnetic field.  No doubt Kyber crystals are used to somehow generate the exceedingly powerful electromagnetic fields.  The field tells the plasma where to go.  A lightsaber is designed to trap the plasma in a long narrow blade, and when two lightsabers strike each other, their electromagnetic fields repel each other.  This is like how two bar magnets will repel each other if you try to bring both their North (or South) poles together.  The Death Star works on the same principle but it is engineered so that the electromagnetic field generated by the Kyber crystals takes many small beams of plasma, combines them into one larger beam, and then shoots that beam out to blow up planets.

A: Because lightsabers are not made of lasers
According to Wookieepedia, which cites Star Wars Rebels: Visual Guide, the lightsaber blades are made from plasma. According to some pre-Disney explanations the lightsaber blades are made of plasma which is contained via an electromagnetic field; I assume the blades repel each other because of this field.
As for the Death Star, its main weapon is a superlaser - a big laser beam made of smaller laser beams. Combining laser beams is a real thing, though in the real world it requires a lens.

A: Kyber crystals in lightsabers are made from blown up Stars the kyber crystals in the Death Star were artificially made to do what they need to do so then they can combine


text:
Q: Hide particular div if all elements have the same class I have a bunch of same elements on the page. All those elements have this particular structure:

                        Some random text goes here   x 1

                        Some random text goes here   x 2

                        Some random text goes here   x 2

All the cards (example above) have common class = globalcardclass (it's only way to track that 'card elements')
All lines in a card could be (or not!) contains class = hidden
So I want a script to hide the whole card if all  elements (lines) have the class = hidden
If one or two  elements (lines) do not have class hidden -- the card is shown.
I need to add another hide class to a particular card if all its children elements have  class hidden.
Here I try something but It doesn't work at all. The hard part is... when the card element gets  elements (lines) with class hidden that card must show up again...
Please, help.

UPD!
Here is new way to solve my problem:
jsfiddle.net/q6cekb18
But it also doesn't work...
UPD 2 (!)
Finally! I've got some progress!
   $(".globalcardclass").filter(function(){
    return $(this).find(".smoothmaion:visible").length == 0;
}).hide();

That code is working... All the card are hiding... But...
A card (.globalcardclass) is not showing up if 'line' element (.smoothmaion) becomes visible again... How to make it some sort of a... toggle?
Yeah... I can:

But... When I use another button to filter different type of elements... That 'toggle' thing brings back that hidden element 'cause it has not change so ... toggle..
What can I do?


text:
Q: UIWebView On Button Click Event I have done this Example for implementation of the WebView. here is the link
But in My application i want to set it to load on the Button click event.
If the Above link Example there is no any xib file needed. But in My Application i have made the XIB file to load. So How can i implement it on My own XIB file on button pressed Event ???

A: Open your xib file and use the assistant editor to create an IBAction for your UIButton. Then in the method that is created for you in your .m file instantiate and present the WebView.


text:
Q: Moving domain user with linked mailbox My organisation currently has two domains, one of which is slowly being fased out.
What I need to do is the following:
User "test" from DomainA needs to move to DomainB.
"test" has a linked mailbox to his disabled account on DomainB.
User "test" currently has the following accounts:
DomainA\test

DomainB\da-test(disabled)

LinkedMailbox "da-test"

I have already created a new user account on DomainB: "DomainB\test"
What is the best way to convert the linked mailbox "da-test" to a user mailbox "test", which should be connected to the new user "DomainB\test"?
This has to be done for all users from DomainA.
Thanks

A: You can disable the linked mailbox "da-test", and then reconnect the disabled mailbox to the new user account on DomainB "DomainB\test". Details see:Connect a disabled mailbox


text:
Q: Loading all symbols of a particular type in a package I would like to load all symbols of a type from a golang testing package.
What I would like to accomplish is something like pytest's fixtures, where I define an interface
type Fixture func(...Fixture) interface{}
var MyFixture = func() interface{} {
        return 1}

and then to use reflection on the package to load all fixtures and inject them into the test using the test runner.
(I know the reflect package won't give me the parameter names, thats a separate problem i need to solve).
I have two issues, reading Go (reflect): How to discover all package types at runtime?, I tried to use the Default() importer, but I always get a panic:
pkg, err := importer.Default().Import("fmt")
// error was nil
// pkg is nil

randomly prints the following string from somewhere can't find import:


text:
Q: Set div height to 100% of parent I want the following layout for my web page:
|         header       |
| navigation | details |
|            |         |

Where the navigation pane (content dynamically generated) contains hundreds of elements. I want a vertical scroll bar to be created on the navigation pane such that the pane has the height of the window minus the height of the header.
My page roughly has the following structure:

With the following CSS:
#navigation {
    float: left;
    width: 400px;
    height: 100%;
    overflow: auto;
}

#details {
    margin-left: 420px;
}

This mostly works except that the navigation pane gets 100% of the height of the window, not 100% of the height of the window minus the height of the header. I'd rather not explicitly set the height of the header if I can avoid it. I am completely new to web development so I don't mind doing some reading. What do I need to do to achieve the layout that I want?

A: You must ensure your body tag and content container also have heights of 100%.  You must explicitly set the height of the parent element(s) for the child to obey.
body {
    height: 100%;
}

#content {
    height: 100%;
}

This does not, however, take into consideration positioning of the header.  The following post demonstrates a technique utilizing the min-height fast hack by Dustin Diaz and a negative margin on the content container to achieve 100% height while not interfering with the header:
http://www.thechoppr.com/blog/2009/02/08/3-column-fluid-layout-100-height/

A: You said "I'd rather not explicitly set the height of the header if I can avoid it."  I'm pretty sure you can't avoid it without switching to tables. That said, here is an example of how you can do it using divs with the header's height set to 50px:

One note:  If you want to add backgrounds to the navigation and/or details areas, you will have to actually apply those to the their respective shell divs that encase them.  All actual content, however, would go in the inner divs.

A: You have to set BOTH html and body height to 100%: html, body {height: 100%;}


text:
Q: Rails 4.2 getting segmentation fault while running tests at active-support I am trying to build Rails from source for the latest stable (4.2) version from the branch 4-2-stable; however I am getting a segmentation fault at 'activesupport' for rake tests.
The details of error log are as below:

Platform I am trying on: Ubuntu 14.10 Rails Version: 4.2.3 Ruby
  Version: 2.2.2 & 2.1.6 (on both versions getting same trace)

Log:

** Invoke test (first_time)
** Execute test
/home/test/.rvm/rubies/ruby-2.1.6/bin/ruby -w -I"lib:test"
  -I"/home/test/.rvm/gems/ruby-2.1.6/gems/rake-10.4.2/lib" "/home/test/.rvm/gems/ruby-2.1.6/gems/rake-10.4.2/lib/rake/rake_test_loader.rb"
  "test/**/*_test.rb"

Run options: --seed 36135
Running:
................................................................................................................................................................................  Segmentation fault
rake aborted!

Command failed with status (139): [ruby -w -I"lib:test"
  -I"/home/test/.rvm/gems/ruby-2.1.6/gems/rake-10.4.2/lib" "/home/test/.rvm/gems/ruby-2.1.6/gems/rake-10.4.2/lib/rake/rake_test_loader.rb"
  "test/**/*_test.rb" ]
/home/test/.rvm/gems/ruby-2.1.6/gems/rake-10.4.2/lib/rake/testtask.rb:108:in
  `block (3 levels) in define'

Can anyone provide any pointers so as to fix this?


text:
Q: How do I get an aggregate of all the stats from all uWSGI vassals using uwsgitop? TL;DR
Can anyone tell me how I may get uwsgitop to monitor all of my vassals in my emperor-vassal setup in one shot?

I have an emperor-vassal setup for my uWSGI server, and I need to monitor all my vassals. I could always check my application logs for the various data, but it is more convenient to have a real-time updating, comprehensive display of all statistics.
So, I tried a couple of things:

*

*I created a common .ini file which contains the following:
[uwsgi]
stats = stats_vassal.sock

Then, in each vassal's .ini file I include that common .ini file. The problem with this approach is that I don't get any meaningful data when I run uwsgitop with the stats_vassal.sock file. My hypothesis as to why this is happening is that the data in that socket keeps getting overwritten by stats from some vassal that isn't in use.
So then I switched to....

*In each vassal's .ini file, I set an option stats = stats_%n.sock. Now, I can run uwsgitop on each stats_*.sock file to monitor that specific vassal.
But I want to be able to monitor all vassals in one go. uwsgitop seems to accept only one argument.
I've looked into uWSGI's Metrics subsystem, and the "file" stats pusher seems to be what I want since it keeps appending to one file. However, when I tried to put stats-push = file:path=stats_%n.sock,freq=1 in each of my vassal .ini files OR when I tried to put stats-push = file:path=stats_vassal.sock,freq=1 in my common vassal .ini file, I get the following error when I restart uWSGI:

unable to find "file" stats_pusher

I then tried to include the stats_pusher_file plugin in the same .ini file, but got the following error:

!!! UNABLE to load uWSGI plugin: ./stats_pusher_file_plugin.so: cannot
  open shared object file: No such file or directory !!!

And this is where I hit a dead end.

A: Unfortunately uwsgitop didn't have such possibilities, but i wrote "patch" and with my changes there is ability to use uwsgitop this way : uwsgitop /var/stats and it shows all vassal workers information separately on one screen.
You can check code here
Sample


text:
Q: Plone portlet using plone.namedfield.field.NamedImage I'm running Plone 4.3 and have been trying to create a custom portlet. The portlet is simple and should allow the user to upload an image and provide some descriptive text which can be displayed beneath the image.
Here's the code I have so far:
from zope.interface import implements
from zope.formlib import form
from zope import schema
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from plone.app.portlets.portlets import base
from plone.memoize.instance import memoize
from plone.namedfile.field import NamedImage
from plone.directives import form
from z3c.form import field
from plone.app.portlets.browser import z3cformhelper

class IMyImagePortlet(form.Schema):

    myimagetitle = schema.TextLine(
        title=u"Image title",
        description=u"Enter the image title",
        default=u"",
        required=True)

    myimagedescription = schema.TextLine(
        title=u"Image text",
        description=u"Enter the text which appears below the image",
        default=u"",
        required=True)

    myimage = NamedImage(
        title=u"My image",
        description=u"Upload an image",
        required=True)

class Assignment(base.Assignment):
    implements(IMyImagePortlet)

    header = u"My Image"
    myimagetitle = u""
    myimagedescription = u""
    myimage = u""

    def __init__(self, myimagetitle=None, myimagedescription=None, myimage=None):
        self.myimagetitle = myimagetitle
        self.myimagedescription = myimagedescription
        self.myimage = myimage

    @property
    def title(self):
        """This property is used to give the title of the portlet in the
        "manage portlets" screen.
        """
        return u"My image"

class Renderer(base.Renderer):

    _template = ViewPageTemplateFile('templates/myimage_portlet.pt')

    def __init__(self, *args):
        base.Renderer.__init__(self, *args)

    @memoize
    def myimagetitle(self):
        return self.data.myimgaetitle

    @memoize
    def myimagedescription(self):
         return self.data.myimagedescription

    @memoize
    def myimage(self):
        return self.data.myimage

    def render(self):
        return self._template()

class AddForm(z3cformhelper.AddForm):
    fields = field.Fields(IMyImagePortlet)

    label = u"Edit image"
    description = u"A portlet which can display image with text"

    def create(self, data):
        return Assignment(**data)

class EditForm(z3cformhelper.EditForm):
    fields = field.Fields(IMyImagePortlet)

    label = u"Edit image"
    description = u"A portlet which can display image with text"

This seems to work as expected and allows me to add a new portlet with a title, image, and image description. However, I've been reading the docs and I couldn't find many examples of creating a portlet with an image upload field, so there may be a better way of doing this.
My issue is that I can't seem to render the image in the template. I've been referring to the docs at https://developer.plone.org/reference_manuals/external/plone.app.dexterity/advanced/files-and-images.html and have the following in my template, but the image is not being displayed:
<div tal:define="picture nocall:context/myimage"
     tal:condition="nocall:picture">
    <img tal:attributes="src string:${context/absolute_url}/@@download/myimage/${picture/filename};
                     height picture/_height | nothing;
                     width picture/_width | nothing;"
    />
</div>

A: We did exactly what you want.
https://github.com/4teamwork/ftw.subsite/tree/master/ftw/subsite/portlets
It's a teaser portlet, unfortunately not in a single package. but you can adapt the code to your needs.
We defined a browser view in image.py:
from Acquisition import aq_inner
from zope.publisher.browser import BrowserView

class ImageView(BrowserView):
    """View the image field of the image portlet. We steal header details
    from zope.app.file.browser.file and adapt it to use the dublin
    core implementation that the Image object here has."""

    def __call__(self):
        context = aq_inner(self.context)
        image = context.image
        self.request.response.setHeader('Content-Type', image.contentType)
        self.request.response.write(image.data)

Register with zcml (Important the image view is for your portlet Assignment):
<browser:page
    for=".yourportlet.Assignment"
    name="image"
    class=".image.ImageView"
    permission="zope.Public"
 />

In your portlet Renderer you have to define a method, which gets the image (traverse).
from plone.app.portlets.portlets import base

class MyPortletRenderer(base.Renderer)

    def image_tag(self):
        state = getMultiAdapter((self.context, self.request),
                                name="plone_portal_state")
        portal = state.portal()
        assignment_url = \
            portal.unrestrictedTraverse(
            self.data.assignment_context_path).absolute_url()

        return "<img src='%s/%s/@@image' alt=''/>" % (
            assignment_url,
            self.data.__name__)

Now you are able to use the image in your portlet:
<tal:image content="structure view/image_tag />

I don't know if there is a simpler solution.
Naming could be better :-)
But it works and it's tested https://github.com/4teamwork/ftw.subsite/blob/master/ftw/subsite/tests/test_subsiteportlet.py


text:
Q: Dealing with timezones for sending sms -python /django I need to send sms globally to different timezones  to each customer registered online
The messages are scheduled to be send each month.
I have the country details of each cutomer . I would be writing a python script and add it to cronjobs for sending sms.
The issue I am facing is knowing a safe time ( sometime during the day)  based on the country for sending the SMS.
MY server runs in Australian/Melbourne timezone.What is the best way for me to find the safe time to send SMS to a customer from another country

A: You probably want to store each user's timezone in your database and then you can change a particular datetime object's timezone by using datetime.astimezone(tz) .
Now deciding what a good time to to sms them is entirely up to you.


text:
Q: In Minecraft, I want to testfor if a player is on one team or the other I want to testfor if a player is on team 1, but if he is on team 2, then the comparator will still activate. I tried: testfor @p[team=1,team=2]
It only works for team 2 though. Probably because it is at the end. or something. Is it even possible for what I'm doing. Is there a different way maybe?

A: Use two seperate commandblocks /testfor @p[team=1] and /testfor @p[team=2] ,then connect the comparator outputs


text:
Q: panda read_excel index_col seems to skip a row I am trying to get a multi level index and column pandas data frame from an excel file, but oddly it seems that it is skipping a row. Consider the following:

This is my code
df = pd.read_excel(r"https://buy-and-hold-strategy.s3.eu-central-1.amazonaws.com/example.xls",
                   skiprows=2,
                   sheet_name='Sheet1',
                   index_col=[0, 1],
                   header=[0, 1])
df.head()

returns
Out[46]:
b        1          2
sub      0    1     0    1
1 1
1 2  value  1.0   NaN  NaN
  3    NaN  NaN   NaN  NaN
2 1    NaN  NaN  text  2.0
  2    NaN  NaN   NaN  NaN
3 1    NaN  NaN   NaN  NaN

It seems that the first row of data 1.1 is stored as the index name:
 df.index.names
Out[49]: FrozenList([1, 1])

A: I think your excel file has a wrong structure.. maybe you can adjust the structure of the Excel file like this:

Afterwards you can read your file like you aready did:
df = pd.read_excel((r"https://buy-and-hold-strategy.s3.eu-central-1.amazonaws.com/example.xls",
               skiprows=2,
               sheet_name='Sheet1',
               index_col=[0,1],
               header=[0,1])
df.head()

And you get the following result:
df.head()
b           1          2
sub2        0    1     0    1
q sub1
1 1       NaN  NaN   NaN  NaN
2       value  1.0   NaN  NaN
3         NaN  NaN   NaN  NaN
2 1       NaN  NaN  text  2.0
2         NaN  NaN   NaN  NaN

A: Since your problem comes from using index_col with multiple values (and that's what creates a multiindex), let's simplify the problem by not using an index. (Also, we don't need to modify the excel structure for this to work).
>>> df = pd.read_excel(r"https://buy-and-hold-strategy.s3.eu-central-1.amazonaws.com/example.xls",
                   skiprows=2,
                   sheet_name='Sheet1',
                   # index_col=[0],  # No index over here
                   header=[0, 1])

Now, you can create the new index:
>>> df = df.set_index(df.columns[:2].tolist())
>>> df
                                      1          2
                                      0    1     0    1
(Unnamed: 0_level_0, q) (b, sub)
1                       1           NaN  NaN   NaN  NaN
                        2         value  1.0   NaN  NaN
                        3           NaN  NaN   NaN  NaN
2                       1           NaN  NaN  text  2.0
                        2           NaN  NaN   NaN  NaN


text:
Q: How to do a date format in Javascript? I need to understand how to do date formattting in javascript.
i have date as,
var date="12/02/1994";// dd/mm/yyy
var date1=new Date(date);
date1.getDate();// this gives me Month which is 02
date1.getMonth();// this gives me date which is 12.

How do i get the exact date i have in var date in get date and getmonth function? Please help

A: Javascript date() expects date in mm/dd/yy and not in dd/mm/yy. And months start from 0 and not 1.
var from = "12/02/1994".split("/");
var date1 = new Date(from[2], from[1] - 1, from[0]);
date1.getDate();
date1.getMonth();

A: The answer is pretty simple: JavaScript uses mm/dd/yyyy data format.
It doesn't support dd/mm/yyyy format, so, if you need to parse this format, then you will have to do this manually like this:
function parseDdmmyyyy(str)
{
    var spl = str.split('/');
    return new Date(spl[2], spl[1] - 1, spl[0]);
}

or you will have to use external libraries like Moment.js.

A: Use new Date('02/12/1994'), new Date('1994-02-12') or new Date(1994, 02-1, 12), because in js months start from 0 and american date format is used where month goes first

A: you can use the simple JS file DateFormat.js which has some very good example through the URL mattkruse (Date Funtion)
from this JS file you can validate the incoming date is a true format even you can add format date within a several ways.

A: Presumably you want to know how to format strings so they are consistently parsed by browsers. The short answer, is there is no guarantee that any particular string will be correctly parsed by all browsers in use (or perhaps even most).
So the bottom line is: don't parse strings with the Date constructor, ever. It's largely implementation dependent and even the one format specified in ES5 and ECMAScript 2015 is poorly and inconsistently supported.
How browsers treat a string like "12/02/1994" is entirely implementation dependent, however most will treat it as the peculiar US month/day/year format, i.e. 2 December and getMonth will return 11, since months are zero indexed.
So you should always manually parse strings (a library can help, but a simple parsing function is only 2 lines, 3 if validation is required), e.g.

// Parse a date string as d/m/y
// If s is not a valid date, return a Date object with its
// time value set to NaN.
function parseDMY(s) {
  var b = s.split(/\D/);
  var d = new Date(b[2], --b[1], b[0]);
  return d && b[1] == d.getMonth()? d : new Date(NaN);
}

document.write(parseDMY('12/02/1994'));


text:
Q: Zen Coding with ASP.NET MVC Is it possible to write your HTML with Zen Coding expressions into your CSHTML?  Say, something like
`foreeach(var str in list)

    {
          table>(tr>td[str])
    }

where you can use C# variables in your HTML coding while writing Zen code stuff?

A: If you install most popular extension for web development in visual studio
Web Essentials you will get Zen coding enabled.
You can install this via NuGet.
http://vswebessentials.com/

ZenCoding with #WebEssentials is a sweet productivity enhancement! CSS as a template language for expansion is awesome!


text:
Q: How to mock patch a django model field? I have these 2 models:
class Transaction(models.Model):
    gateway_reference = models.CharField(max_length=255, null=True, blank=True)
    ...

    @property
    def abc(self):
        ...

class Item(models.Model):
    txn = models.ForeignKey('Transaction')

    def refund(self):
       Gateway.refund(self.txn)

In my unittest:
def test_decline(self):
    item = Item.objects.get(...)
    with patch('app.models.Transaction.gateway_reference', new='invalid reference'):
        item.refund()

But it complains that Transaction class does not have the attribute 'gateway_reference'
NOTE:
I am using similar patch for an property of a model class and it worked fine, eg.
with patch('app.models.Transaction.abc', new='lalala')

A: When you instantiate the model with the line below

item = Item.objects.get(...)

You have already created a reference to the Transaction model through the txn attribute. So patching the class Transaction within that namespace after the instantiation is too late.
I would use patch object here on the item instance. See https://docs.python.org/dev/library/unittest.mock.html#unittest.mock.patch.object


text:
Q: Report on the top 20% of Customers Only I need to report only on Contacts who are contributing to the top 20% of revenue.  Payment is stored on Customer which is a Master-Detail to Contact, one Contact can be a Customer multiple times.  In practice this means that Customer is an instance of a sale/service, and multiple Customers who have the same Contact must be aggregated to determine if that Contact contributed to the top 20% of revenue.
I can group by Customer and order by the sum of payment in Salesforce Reporting, however, I cannot limit/filter the results by an aggregate formula (# of Contacts * 0.20).
As a workaround I have created a batch class that runs every night and "flags" a record as a top 20% contributor, then I filter results on my report by that flag == true.
The problem with this method is it creates extraneous data in the database and is very limited in scope.  The time period for reporting is fixed to the value I used in the batch class to flag records as top 20% contributors (in this case the last fiscal quarter).  Is there a better way to do this within Salesforce?


text:
Q: How create a table on DynamoDB with a GlobalSecondaryIndexes in local? I DynamoDB install locally on Windows 7.
My project is a Node.js(0.12.0) and I use aws-sdk.
Version DynamoDB : 2012-08-10
This work ->
dynamodb.createTable({
TableName: 'Users',
AttributeDefinitions: [{AttributeName: 'userId', AttributeType: 'S'}],
KeySchema: [{AttributeName: 'userId', KeyType: 'HASH'}],
ProvisionedThroughput: {
    'ReadCapacityUnits': 5,
    'WriteCapacityUnits': 5
}
}, function () {
    ...
});

This don't work ->
dynamodb.createTable({
TableName: 'Users',
AttributeDefinitions: [{AttributeName: 'userId', AttributeType: 'S'}],
KeySchema: [{AttributeName: 'userId', KeyType: 'HASH'}],
ProvisionedThroughput: {
    'ReadCapacityUnits': 5,
    'WriteCapacityUnits': 5
},
GlobalSecondaryIndexes: [
    {
        IndexName: 'longitudeUserIndex',
        KeySchema: [
            {
                AttributeName: 'userId',
                KeyType: 'HASH'
            },
            {
                AttributeName: 'longitude',
                KeyType: 'RANGE'
            }
        ],
        Projection: {
            NonKeyAttributes: [
            ],
            ProjectionType: 'KEYS_ONLY'
        },
        ProvisionedThroughput: {
            'ReadCapacityUnits': 5,
            'WriteCapacityUnits': 5
        }
    }
]
}, function () {
    ...
});

Doc DynamoDB Javascript : http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#createTable-property

A: I resolve my problem.
I added in AttributeDefinitions longitude.
AttributeDefinitions: [{AttributeName: 'userId', AttributeType: 'S'}, {AttributeName: 'longitude', AttributeType: 'N'}]


text:
Q: Custom authorizer data with Amazon.Lambda.AspNetCoreServer Having worked extensively with Node.js in the past, we are currently investigating ASP.NET Core as an alternative Lambda platform.
In the past, our API Gateway-fronted services relied on a custom authorizer, which authenticated the user and retrieved a list of resource-based permission policies from our company's IAM service. The authorizer attaches that list to the authContext key. Our services would integrate with API Gateway via Lambda Proxy and extract the principal object from the raw proxy request.
When using Amazon.Lambda.AspNetCoreServer to translate between API Gateway and ASP.NET, we are unable to arrive at a similar scenario.
Amazon.Lambda.AspNetCoreServer::ApiGatewayProxyFunction::FunctionHandlerAsync(Stream responseStream, ILambdaContext lambdaContext), or any equivalent Lambda handler signature for that matter, receives the complete, raw request in the first parameter. It is possible to serialize the stream (for example, into a JSON.NET JObject) and extract the principal object there.
However, what proves difficult is accessing that data within the ASP.NET application. I am not convinced that the authorizer response is passed to the HTTP context. When checking it, the ClaimsPrincipal context.User key contains no data.
Several solutions were thrown around:

*

*retrieving IAM information in the overriden FunctionHandlerAsync and storing them globally using environment variables or sessions

*creating an interface and a complementary implementation of an IAM provider service. It would expose a method to retrieve IAM information. The implementation would simply return a deserialized list of claims. The service would be configured in an overriden Init(IWebHostBuilder) method.

*gluing together a (Claims/General)Principal object and attempting to pass it to the HTTP context

Is there a way to achieve this cleanly?

A: We've in the exact same situation and I can by no means offer a nice and clean solution, but I have a workaround.
If you look at the request payload, the json is formatted like this:
{
    [...]
    "requestContext": {
        [...]
        "authorizer": {
            "claims": {
                "claim1": "value1",
                "claim2": "value2",
                "claim3": "value3",
            }
        },
        [...]

In APIGatewayProxyFunction.FunctionHandlerAsync they deserialize the requestStream into an APIGatewayProxyRequest. If you step into that class you'll find that the Authorizer part of the json gets deserialized into:
public class APIGatewayCustomAuthorizerContext
{
    public string PrincipalId { get; set; }
    public string StringKey { get; set; }
    public int? NumKey { get; set; }
    public bool? BoolKey { get; set; }
}

I.e all claims are lost in deserialization. I've posted this issue here: https://github.com/aws/aws-lambda-dotnet/issues/98
Now to the workaround, I've just put something that "works" together here (Code here):
Note that it's very untested. :-)
Usage:
public class LambdaEntryPoint : APIGatewayAuthorizerProxyFunction
{
    protected override void Init(IWebHostBuilder builder)
    {
        builder
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseStartup<Startup>()
            .UseApiGateway();
    }
}


text:
Q: PHP why is not "strtotime is not defined" // why does this not work PHP in XAMMP stack
// error: "strtotime is not defined"

$date2 = strtotime('2010-10-01');

A: According to http://us3.php.net/manual/en/calendar.installation.php,

To get these functions to work, you
  have to compile PHP with
  --enable-calendar.
The Windows version of PHP has
  built-in support for this extension.
  You do not need to load any additional
  extensions in order to use these
  functions.

or on OS X:

sudo port install php5-calendar

Failing that, try looking for php5-calendar in your system's package manager.


text:
Q: How to iterate over every second number Reading the docs, I noticed a sentence saying: "Rust doesn't have a C style for loop.". So, I wonder, how can I make a loop equivalent to for(i = 0; i < 10; i += 2) { }?
The ways I can think of are something like:
for i in 0..10 {
    if i % 2 == 0 {
        //Do stuff
    }
}

Or even:
let i = 0;
loop {
    if i < 10 {
        //Do stuff
        i += 2;
    } else {
        break;
    }
}

But I'm not sure this is the best way, especially since it's really verbose. Is there a better way? I'm guessing it would be with iterators, but I'm not sure how I'd do that.

A: There's std::iter::range_step right now, but it's marked as unstable with the message "likely to be replaced by range notation and adapters".
fn main() {
    for i in std::iter::range_step(0, 10, 2) {
        println!("{:?}", i);
    }
}

prints
0
2
4
6
8

A: the itertools crate offers what you want for abitrary iterators. The step function creates an iterator that skips n-1 elements after each iteration.
use itertools::Itertools;

let mut it = (0..10).step(2);
assert_eq!(it.next(), Some(0));
assert_eq!(it.next(), Some(2));
assert_eq!(it.next(), Some(4));
assert_eq!(it.next(), Some(6));
assert_eq!(it.next(), Some(8));
assert_eq!(it.next(), None);

A: This is now implemented in std with the step_by function
for i in (0..10).step_by(2) {
    // Do stuff
}


text:
Q: How to return 2 output from a list Probably a very stupid Q!  Too much office has damaged my brain today.
I am stuck at solving a basic problem from a site.
I have a function that has 3 values in tuple (name, age, gender). I have worked on getting just age & gender in a list & then iterating there to get average if the gender matches M or F and No match if anything apart from it.
Now I am stuck in the problem in BOLD  in the code where I am unable to return either one of the output i.e. if  gender = "m' or 'f' it works properly, but if it uses avergae_age(members,Z), it doesnt return ' No matches found' instead error, which is obvious.

*

*How do I make this code better?

b) How do I just get the output if anything apart form M/F is input without changing my existing code pls ?
Thanks in advance
def average_age(members,gender):
lst=[]
for x in zip(members):
     lst.append(x[0][1])
     lst.append(x[0][2])

lst_tuple = [x for x in zip(*[iter(lst)]*2)]

#return lst_tuple

**lst1=[]
for z in lst_tuple:
    if z[1]!=gender:
        lst1=[]
return ("No matches found.")

for z in lst_tuple:
    if z[1]==gender:
        lst1.append(z[0])
return (sum(lst1)/len(lst1))**

A: For input data:
members = [("Maria", 20, "F"), ("Dan", 21, "M"), ("Ana", 30, "F"), ("Max", 40, "M")]

You can compute average age like this:
def average_age(members: list, gender: str):

    # Collect ages for the given gender
    ages = [member[1] for member in members if member[2] == gender]

    try:
        return sum(ages) / len(ages)

    except ZeroDivisionError:
        print("Unable to compute average age")


text:
Q: Random sample of rows with "at least one from each" condition So I've got a dataset that looks something like this:
a   b   c
23  34  Falcons
14  9   Hawks
2   18  Eagles
3   21  Eagles
22  8   Falcons
11  4   Hawks

And I know I can do a random subset of rows with a nested conditional, but what I want to do is create a random subset that takes at least one of each available value in column 'c'.
So possible correct subsets would be
23  34  Falcons
14  9   Hawks
3   21  Eagles

or
11  4   Hawks
2   18  Eagles
22  8   Falcons

[in no particular order], but something like:
14  9   Hawks
2   18  Eagles
3   21  Eagles

would NOT work, because 'Falcons' is not represented.  Is there an easy way to do this in R?

A: Use group_by and sample_n functions in the dplyr package.
text1 <- "a   b   c
23  34  Falcons
14  9   Hawks
2   18  Eagles
3   21  Eagles
22  8   Falcons
11  4   Hawks"

dat <- read.table(text=text1, head=T, as.is=T)

library(dplyr)
dat %>% group_by(c) %>% sample_n(1)

# Source: local data frame [3 x 3]
# Groups: c [3]

#       a     b       c
#   (int) (int)   (chr)
# 1     3    21  Eagles
# 2    22     8 Falcons
# 3    11     4   Hawks

UPDATE: You can write a function to do the sampling.
sample_df <- function(df) {
  df.r <- sample(1:nrow(df), 1)
  return(sample_n(df, df.r))
}
dat %>% group_by(c) %>% do(sample_df(.))

A: You can specify the n for each group here (use 1s if you only want a data frame with nrows == number of groups
dd <- read.table(header = TRUE, text = 'a   b   c
23  34  Falcons
14  9   Hawks
2   18  Eagles
3   21  Eagles
22  8   Falcons
11  4   Hawks', stringsAsFactors = FALSE)

(n <- setNames(c(1,2,1), unique(dd$c)))
# Falcons   Hawks  Eagles
#       1       2       1

set.seed(1)
dd[as.logical(ave(dd$c, dd$c, FUN = function(x)
  sample(rep(c(FALSE, TRUE), c(length(x) - n[x[1]], n[x[1]]))))), ]

#    a  b       c
# 1 23 34 Falcons
# 2 14  9   Hawks
# 4  3 21  Eagles
# 6 11  4   Hawks

Putting this into a function to automate some other things for you
sample_each <- function(data, var, n = 1L) {
  lvl <- table(data[, var])
  n1 <- setNames(rep_len(n, length(lvl)), names(lvl))
  n0 <- lvl - n1
  idx <- ave(as.character(data[, var]), data[, var], FUN = function(x)
    sample(rep(0:1, c(n0[x[1]], n1[x[1]]))))
  data[!!(as.numeric(idx)), ]
}

sample_each(dd, 'c', n = c(1,2,1))
#    a  b       c
# 1 23 34 Falcons
# 3  2 18  Eagles
# 5 22  8 Falcons
# 6 11  4   Hawks

sample_each(mtcars, 'gear', 1)
#                mpg cyl  disp  hp drat   wt  qsec vs am gear carb
# Valiant       18.1   6 225.0 105 2.76 3.46 20.22  1  0    3    1
# Merc 280      19.2   6 167.6 123 3.92 3.44 18.30  1  0    4    4
# Maserati Bora 15.0   8 301.0 335 3.54 3.57 14.60  0  1    5    8

sample_each(mtcars, 'gear', c(2,2,5))
#                     mpg cyl  disp  hp drat    wt  qsec vs am gear carb
# Hornet Sportabout  18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
# Porsche 914-2      26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
# Lotus Europa       30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2
# Ford Pantera L     15.8   8 351.0 264 4.22 3.170 14.50  0  1    5    4
# Ferrari Dino       19.7   6 145.0 175 3.62 2.770 15.50  0  1    5    6
# Maserati Bora      15.0   8 301.0 335 3.54 3.570 14.60  0  1    5    8
# Mazda RX4 Wag1     21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
# Hornet Sportabout1 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
# Merc 2801          19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4


text:
Q: Rotating a 2D converted 1D array 90 degrees clockwise Been stuck on this a few days now, I'm going out my mind. Essentially I have converted a 2D array of values (an image, I know there are easier ways to achieve this but I have explicit requirements) into a 1D array. I can rotate the 2D array with ease. I'm having trouble with the rotating of the 1D version of the array, and I think it's down to a single line of algorithm being incorrect.
The code I'm using for rotating the array is:
cout << "\nTransfer from 2D to dynamic 1D array and print details\n\n";
myImage * p_myImage = new myImage[total];

    for (int y = 0; y < height; y++)
{
    for (int x = 0; x < width; x++)
    {
        int offset = width * y + x;
        p_myImage[offset].pixel = array2D[y][x];
        cout << p_myImage[offset].pixel << " ";
    }
  cout << "\n";
}

//new pointer to copy to
myImage * p_myImage2 = new myImage[total];
cout << "\nRotate Matrix through 1D array\n\n";

for (int x = 0; x < width; x++)
{
    for (int y = 0; y < height; y++)
    {
        int offset = height * x + y;
        //int offset = width * y + x ;
        p_myImage2[offset].pixel = p_myImage[height-1+x].pixel;
        cout << p_myImage2[offset].pixel << " ";
    }
  cout << "\n";
}

A: This should rotate it clockwise:
p_myImage2[offset].pixel = p_myImage[width * (height - 1 - y) + x].pixel;


text:
Q: Uncaught TypeError: Cannot read property 'style' of null in react if else statement Im trying to filter elements by their respective id via button click
first condition works fine when I click on it but when it has to check the else if conditions I get Uncaught TypeError: Cannot read property 'style' of null
HERES MY FUNCTION :
 filter(e){
        var filtertag = 'data-story-card';

        if (e.target.classList.contains(productive)) {
           filtertag = 'data-story-card-productive';
           document.getElementById('data-story-card-productive').style.display = "none"
           console.log(e.target.classList)

        }
        else if (e.target.classList.contains(inclusive)){
            filtertag = 'data-story-card-inclusive';
            document.getElementById('data-story-card-inclusive').style.display = "none"
            console.log(filtertag)
        }
        else if (e.target.classList.contains(well)) {
            filtertag = 'data-story-card-well-governed';
            document.getElementById('data-story-card-well-governed').style.display = "none"
            console.log(filtertag)
        }
        else if (e.target.classList.contains(sustainable)){
            filtertag = 'data-story-card-sustainable';
            document.getElementById('data-story-card-sustainable').style.display = "none"
            console.log(filtertag)
        }
        else if (e.target.classList.contains(built)){
            filtertag = 'data-story-card-built';
            document.getElementById('data-story-card-built').style.display = "none"
            console.log(filtertag)
        }
        else if (e.target.classList.contains(city)) {
            filtertag = 'data-story-card-city';
            document.getElementById('data-story-card-city').style.display = "none"
            console.log(filtertag)
        }

    }


text:
Q: Implement ball bouncing in free fall using scipy.ivp() I want to solve ordinary differential equations using scipy_ivp() of a ball falling with an inital velocity of 1 in the x-direction, and 0 in the y-direction. The gravitational acceleration is g = 9.82, and when the ball hits the ground, its velocity is suppossed to change sign and be multiplied by 0.9. However, using the events parameter, I find it doesn't work as it should. This is my code and the result:
from scipy.integrate import solve_ivp
def f_derivs_ivp(t, vars, g = 9.82):

    dxdt = vars[2]
    dydt = vars[3]

    dvxdt = 0
    dvydt = -g

    return dxdt, dydt, dvxdt, dvydt

def bounce(t, y, g = 9.82):
    if y[1] <= 0:
        y[3] = -0.9*y[3]
    #print(y[1])
    return y[1]

#bounce.terminal = True
#bounce.direction = -1

vars0 = np.array([0, 10, 1, 0])

sol = solve_ivp(f_derivs_ivp, [0, 7], vars0, max_step=0.01, events = bounce)

plt.plot(sol.y[0], sol.y[1], "ko")

print(sol.y_events)
print(sol.t_events)

Using another method than scipy.ivp(), the result should look like this:

What am I doing wrong, and how does the events parameter work? Note also that if I write return y[1] - 10 in the bounce function, nothing changes. It bounces up and down if I in the if statement of the bounce function write y[3] = 10 for example, but not as it should.

A: The scipy ODE solvers do not possess an event-action mechanism with user-definable actions. The event function is just a scalar-valued function on the trajectory whose zeros (with crossing-direction if set) are the events. This means that the event function is used to search for an event (first detecting sign changes, then refining using Brent's method). It will be called multiple times per time step independent on if the time step contains an event.
The built-in actions are "register" (default) and "terminate".
You will have to interrupt the integration at a bounce, and restart with the reflected state as initial condition. Plot the pieces separately or use concatenation to get one big solution array.


text:
Q: What is gzip(gfe)? I see gzip(gfe) in the User Agent in my logs. Here is an example:
05-18 06:44AM 00.897 /NTp9 405 17ms 0cpu_ms 0kb Twitterbot/0.1,gzip(gfe),gzip(gfe)
128.242.241.133 - - [18/May/2010:06:44:00 -0700] "HEAD /NTp9 HTTP/1.1" 405 124 - "Twitterbot/0.1,gzip(gfe),gzip(gfe)"

Does anyone know what this is?

A: I found this on a link (link defunct, no Wayback)

gzip is as software application for compression and uncompression. This token means, that the server request/response is compressed.
gfe means the Google Front End
You will see this token, if an user translate your website in another language with the Google Translator.

A: The twitter robot is looking for something on your site.  It should say in the GAE logs what resource it is failing on.  It may be looking for the robots.txt file or it may be following a link to your site that someone posted (which is likely a bad link).


text:
Q: Multiple File Upload VueJS I am new to VueJS and I was trying to upload multiple pictures. The form looks like this.

I am using Vue from CDN on a blade file. The problem is when I click delete, it is not the one clicked which is removed, but the last one. I have noticed that the one clicked is actually removed from the data, but the form doesn't update like that. Any help is appreciated. My code looks like this:
Vue.createApp({
    data() {
        return {
            images: []
        }
    },
    methods: {
        addField(images){
            images.push({});
        },
        removeField(index, images){
            images.splice(index, 1);
        }
    }
}).mount('#picture')

<input id="picture" type="file"
 class="form-control-file{{ $errors->has('picture') ? ' is-invalid' : '' }}"
 name="picture[]" accept="image/*" required>

 @if ($errors->has('picture'))

     {{ $errors->first('picture') }}

 @endif


text:
Q: Does a Fuzz Testing Tool use the TCP/IP Stack of the Operating System? Fuzz testing tools generate malformed packets of protocols. Do they use their own TCP/IP stack to generate these malformed packets? Does the operating system's TCP/IP stack play any role in Fuzz testing?
I am working on a MPLS Fuzz testing tool running on Windows 7 OS. The tool is testing a MPLS stack on a Linux machine. Does my test tool use the windows stack? I was told that windows does not support MPLS but the test tool works just fine.

A: Any tool that doesn't rely on kernel modifications will have to go through the OS's networking stack. This doesn't mean that they necessarily have to use the networking stack's TCP/IP support: many OSes support APIs like SOCK_RAW+IP_HDRINCL (Windows, BSD, OS X)/PF_PACKET (Linux) which lets you build your own packets (which do not have to be TCP, or even IP).
This means that userspace tools are free to bypass the TCP/IP handling in the OS and roll their own packets so long as the OS provides the necessary support (and most major ones do).


text:
Q: How to make a pretty biplot in R without using external packages? I'm a huge fan of the typical R plots. Today I have to make a biplot, but the typical biplot are ugly. There is a way to make it prettier, draw the ellipses, etc. without using others packages?
If is not possible, how can I draw it looking as the classical R plots?
DF <- iris
PCA <- prcomp(DF[,c(1:4)], scale. = T, center = T)
biplot(PCA)

The result:

A desired result (made in PAST3)

A: I notice that the points plotted in your PAST3 version do not seem to match up with those in the R biplot. It looks like the y-axis is flipped in the two versions.
The structure returned from prcomp has what you need to make one in the nicer style. The projected points are in PCA$x so you can get the desired plot from base R plotting with
plot(PCA$x[,1:2], pch=20, col=iris$Species)

For adding ellipses, I always use dataEllipse from the car package,  but that goes outside your request to not use other packages.
UPDATE
As requested in the comment, I am adding how to add ellipses using the car package.
library(car)
plot(PCA$x[,1:2], pch=20, col=iris$Species)
dataEllipse(PCA$x[,1], PCA$x[,2], iris$Species, lwd=1,
    group.labels = NULL, plot.points=FALSE, add=TRUE,
    fill=TRUE, fill.alpha=0.02)

I picked something that I thought looked nice, but dataEllipse allows you to make many kinds of adjustments. Just look at the help page so that you can tune it to your taste.


text:
Q: Err:5 http://in.archive.ubuntu.com/ubuntu bionic InRelease
lsb_release -a

No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 18.04.2 LTS
Release:    18.04
Codename:   bionic

I tried finding error what to remove and what not but couldn't figure out. Can any other help me with which ppa is causing this problem?
> sudo apt update
Hit:1 http://linux.teamviewer.com/deb stable InRelease
Ign:2 http://dl.google.com/linux/chrome/deb stable InRelease
Hit:3 http://archive.canonical.com/ubuntu bionic InRelease
Hit:4 http://security.ubuntu.com/ubuntu bionic-security InRelease
Err:5 http://in.archive.ubuntu.com/ubuntu bionic InRelease
  500  Internal Server Error [IP: 103.123.234.254 80]
Hit:6 http://dl.google.com/linux/chrome/deb stable Release
Hit:8 https://download.sublimetext.com apt/stable/ InRelease
Err:10 http://in.archive.ubuntu.com/ubuntu bionic-updates InRelease
  500  Internal Server Error [IP: 103.123.234.254 80]
Hit:9 https://packagecloud.io/slacktechnologies/slack/debian jessie InRelease
Hit:11 http://in.archive.ubuntu.com/ubuntu bionic-backports InRelease
Reading package lists... Done
W: Failed to fetch http://in.archive.ubuntu.com/ubuntu/dists/bionic/InRelease  500  Internal Server Error [IP: 103.123.234.254 80]
W: Failed to fetch http://in.archive.ubuntu.com/ubuntu/dists/bionic-updates/InRelease  500  Internal Server Error [IP: 103.123.234.254 80]
W: Some index files failed to download. They have been ignored, or old ones used instead.

A: changing servers from India to Main fixed the problem: How do I change mirrors in Ubuntu Server from regional to main?


text:
Q: What is the difference between %u & %g? What is the difference between %u & %g  (Log File Pattern Variables) in Java Logging API and when they are used?
Thanks

A: A pattern consists of a string that includes the following special components that will be replaced at runtime:
"/" the local pathname separator
"%t" the system temporary directory
"%h" the value of the "user.home" system property
"%g" the generation number to distinguish rotated logs
"%u" a unique number to resolve conflicts
"%%" translates to a single percent sign "%"

A: Found the solution from FileHandler API

If no "%g" field has been specified and the file count is greater than
  one, then the generation number will be added to the end of the
  generated filename, after a dot.
Thus for example a pattern of "%t/java%g.log" with a count of 2 would
  typically cause log files to be written on Solaris to
  /var/tmp/java0.log and /var/tmp/java1.log whereas on Windows 95 they
  would be typically written to to C:\TEMP\java0.log and
  C:\TEMP\java1.log
Generation numbers follow the sequence 0, 1, 2, etc.

while %u make the file name unique if multiple apps trying to log to the same app.


text:
Q: AngularJS filter search I have tried the filter logic from angular to one of the unordered list.
But, the search filter is working after typed 3 characters of the name, sometimes giving wrong search results.
 <input type='text' ng-model='searchString' placeholder="Search a name..." />

           {{item.name}}

JSON:
{
    "People":[
       {
          "name":"Andrew Amernante",
          "rating":3,
          "img":"http://www.fillmurray.com/200/200",
          "Description":"Glutenfree cray cardigan vegan. Lumbersexual pork belly blog, fanny pack put a bird on it selvage",
          "Likes":[
             "Dogs",
             "Long walks on the beach",
             "Chopin",
             "Tacos"
          ],
          "Dislikes":[
             "Birds",
             "Red things",
             "Danish food",
             "Dead Batteries"
          ]
       },
       {
          "name":"Frank Wang",
          "rating":5,
          "img":"http://www.fillmurray.com/200/201",
          "Description":"Before errors, mails were only pressures. This is not to discredit the idea that a magic is the prose of anelizabeth. This could be, or perhaps some posit the outmost coil to be less than dedal. Some assert that those treatments are nothing more than carp.",
          "Likes":[
             "Frank",
             "Manchester United",
             "Football",
             "Programming"
          ],
          "Dislikes":[
             "Dogs",
             "Long walks on the beach",
             "Chopin",
             "Tacos"
          ]
       },
       {
          "name":"Sissi Chen",
          "rating":5,
          "img":"http://www.fillmurray.com/200/202",
          "Description":"Aaah! Natural light! Get it off me! Get it off me! Oh, loneliness and cheeseburgers are a dangerous mix. D'oh. Here's to alcohol, the cause of all life's problems.",
          "Likes":[
             "Cats",
             "the beach",
             "Chopin",
             "Blue things"
          ],
          "Dislikes":[
             "Birds"
          ]
       },
       {
          "name":"Diego Garcia",
          "rating":2,
          "img":"http://www.fillmurray.com/200/204",
          "Description":"Facts are meaningless. You could use facts to prove anything that's even remotely true! I prefer a vehicle that doesn't hurt Mother Earth. It's a gocart, powered by my ownsense of selfsatisfaction. You don't win friends with salad.",
          "Likes":[
             "Talking Spanish",
             "Spanish food",
             "Spanish things",
             "Football"
          ],
          "Dislikes":[
             "Not talking spanish",
             "Chopin"
          ]
       },
       {
          "name":"Fuad Rashid",
          "rating":4,
          "img":"http://www.fillmurray.com/200/206",
          "Description":"Glutenfree cray cardigan vegan. Lumbersexual pork belly blog, fanny pack put a bird on it selvage",
          "Likes":[
             "Dogs",
             "Long walks on the beach",
             "Chopin",
             "Tacos"
          ],
          "Dislikes":[
             "Birds",
             "Red things",
             "Danish food",
             "Dead Batteries"
          ]
       }
    ]
 }

Here is the plnkr code.
Ex: Start typing 'si', you will end up with two results where first one(frank wang) is not correct.
And, this is the reference plnkr where I'm referring for.

A: You would need to specify which object property, in this case name for the filter to filter against:
<input type='text' ng-model='searchString' placeholder="Search a name..." />

    {{item.name}}

You would need to set the initial value of searchString to an empty string as well to match against all people when no text has been entered.
$scope.searchString = '';

Here is a Plunker demonstrating the functionality.
Hopefully that helps!

A: You can create your own customized filter to specify on which property you need to search:
$scope.searchTextByName = function(artist){
    if($scope.searchText !== undefined){
        if(artist.name.toLowerCase().indexOf($scope.searchText.toLowerCase()) > -1 ){
           return artist;
        }
    }
}

Otherwise, it will match on all JSON value of single people object with your searchText key.


text:
Q: Callbacks on Ajax.BeginForm don't work right why do I always have so much trouble...?  given that I didn't solve the problem in my other article, I decided to just code the javascript right into the values... so I have:
OnSuccess="alert('ok')",
OnFailure="alert('failed')",

so my problem is the submission works fine; a record gets inserted into the database and I get a callback... but I get the wrong callback!  I get a failure even though the record got inserted.  heeeeelp!

A: You should be able to read data from the response to figure out why it's considered a failure:
OnFailure="handleError",

...
function handleError(ajaxContext) {
    var response = ajaxContext.get_response();
    var statusCode = response.get_statusCode();
    alert("Sorry, the request failed with status code " + statusCode);
}

Alternatively, use Fiddler and look at the response. Make sure the status code, content type and content are all as expected.

A: ok, I figured out a few things:

*

*OnFailure="handleError" is the correct way to do this (see the other article I mentioned for resolution)

*ajaxContext didn't have a get_response() method because I was actually hooking up the function to the OnComplete event instead (my bad)!  once hooked up to the OnSuccess, I get my controller's method Json return value natively

*I was getting the OnSuccess handler called when the database entry was failing.  this is because my controller method was try{} catch{}ing and therefore never failed! me being dopey :(


text:
Q: The fastest way in Python to merge and remove duplicate ids I have two different querysets I need to merge together then remove any duplicate ids. There is over a over a million records.
list_a = Wharehouse.orders.all().values_list('id', flat=True)
list_b = Shops.orders.all().values_list('id', flat=True)

Is there a fast pythonic way of doing this?
I can think of using a list comprehension and looping each value. But, could this be done in numpy better/faster or maybe a set? The output only needs to be a list of ids.
I'm using Python 3.4 and Django with numpy 1.11.0 pip installed.

A: Assuming list_a, and list_b are lists of integers, you could use np.union1d(list_a, list_b). Using:
import numpy as np
N = 10**6
list_a = np.random.randint(2*10**6, size=N).tolist()
list_b = np.random.randint(2*10**6, size=N).tolist()

Here is a benchmark suggesting np.union1d may be faster when applied to lists with around a million elements:
In [32]: %timeit np.union1d(list_a, list_b)
1 loop, best of 3: 296 ms per loop

In [40]: %timeit set(list_a + list_b)
1 loop, best of 3: 308 ms per loop

In [31]: %timeit set(list_a).union(list_b)
1 loop, best of 3: 338 ms per loop

In [33]: %timeit list(set(list_a + list_b))
1 loop, best of 3: 382 ms per loop

Note, of course, that np.union1d returns a NumPy array, while set and list return Python objects of the eponymous type so the benchmark is to some extent an apples-to-orange comparison.

A: Try casting it to a set to remove the duplicates. You can then return it to a list. To concatenate the lists use the + operator. It will do just this (at least with normal lists)
merged = list(set(list_a + list_b))

A: One way is to use Sets.
We create 2 sets set_a and set_b. set_a contains all the ids of Wharehouse objects. set_b contains all the Shops ids. Now to get all unique ids combined, we use union operation on sets.  final_set contains all the desired unique ids.
set_a = set(Wharehouse.orders.all().values_list('id', flat=True))
set_b = set(Shops.orders.all().values_list('id', flat=True))

final_set = set_a.union(set_b) # contains all unique ids combined

A: shops_query=Shops.orders.all().values_list('id', flat=True)
result = Wharehouse.orders.all().exclude(id__in=shops_query).values_list('id', flat=True)

Let the DB do the work.


text:
Q: Inserting data in cassandra without puting in single quotes using cql java driver I am having trouble puting those single quotes for ASCII/Timestamp columns and not puting for other types like Int, Decimal, Boolean etc.
The data comes from another db/table, which is a sql.
I have all the column data as string. I don't want to format each column data to check null values and then decide to put quote or not.
Is it possible to pass in insert data value without giving single quotes, using prepared statement or whatever.

A: If you don't want to write a loader that uses prepared statements (via the CQL driver...which is a good idea), I can think of one other way.  To import without using single quotes, you should be able to accomplish this with the COPY FROM CQL3 command (setting the QUOTE parameter to an empty string).  If you can dump your RDBMS data to a csv file, you should be able to insert those values into Cassandra like this:
COPY myColumnFamily (colname1,colname2,colname3)
FROM '/home/myUser/rdbmsdata.csv' WITH QUOTE='';

Check out the documentation on the COPY command for more information.  Examples can be found here.
EDIT:
I also read the above question and assumed that you did not want a prepared statement-based answer.  Since that's obviously not the case, I thought I'd also provide one here (using DataStax's Java CQL driver).  Note that this answer is based on my column family and column names from my example above, and assumes that col1 is the (only) primary key.
PreparedStatement statement = session.prepare(
    "UPDATE myKeyspace.myColumnFamily " +
    "SET col2=?, col3=? " +
    "WHERE col1=?");

BoundStatement boundStatement = statement.bind(
    strCol2, strCol3, strCol1);
session.execute(boundStatement);

This solution does not require you to encapsulate your string data in single quotes, and has a few added benefits over your String.ReplaceAll:

*

*Allows you to insert values containing single quotes.

*Escapes your values, protecting you from CQL-Injection (the lesser-known relative of SQL-Injection).

*In CQL, both UPDATE and INSERT add a record if it does not exist and update it if it does (effectively known as an "UPSERT").  Using an UPDATE over an INSERT supports counter columns (if your schema ends up using them).

*Prepared statements are faster, because they allow Cassandra to only have to parse the query once, and then re-run that same query with different values.

For more information, check out DataStax's documentation on using prepared statements with the Java Driver.

A: Finally did it using String.format clubbed with replace
String.format("INSERT INTO xyz_zx(A,B,C,D) VALUES('%s','%s',%s,%s);",(Object[])Strings).replaceAll("'null'","null");


text:
Q: Serve React production App (local server) through Flask-Python I'm producing an application with these two technologies: React-app & Flask-Python. Its intended to run a react client to represent data received from Flask-server. The flask server and react client are on the same machine and communicate trough sockets (SocketIO).
In Dev mode, in order to run the application, I have to run the react server with npm start (node) and the flask server with python.
In production mode, after the react server is built, I have to serve the build folder with the serve option available on Node. Otherwise the app will not work properly (I think its because I use react-router, and when I go to another place of my react app, the browser cannot find the URL's specified. When serving the build folder with serve option of Node, no problem shows up).
So, my question is: Can I serve the build folder of my react application with flask instead of serve option of node? I want to do this, in order to eliminate the Node.js dependency so if I want to run my application on another machine, I will not have to install node.

A: So i got this working by doing this:
-Build my react app with
npm run build

my app structure right now is:
├── server-flask/
    ├── ...
    ├── static/
├── react-app/
      ├── ...
      ├── build/

-Copied the content of build folder to /server-flask/static.
-And my flask code looked like this:
from flask import Flask, send_from_directory
import os

app = Flask(__name__, static_folder="/static")

@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def serve(path):
    if path != "" and os.path.exists("/static/" + path):
        return send_from_directory('static', path)
    else:
        return send_from_directory('static', 'index.html')

if __name__ == "__main__":
    app.run()

A: Yes it's possible to do it in flask with static folder/files. You need to create a folder which is called static in your project. Imagine this folder structure:
├── server/
└── static/
    ├── css/
    ├── dist/
    ├── images/
    └── js/
        index.html

For your react app the only thing you need do is to build npm run build.
In flask you should set this static folder in order to be used. You need in a simplified version this:
# server.py
from flask import Flask, render_template

app = Flask(__name__, static_folder="../static/dist", template_folder="../static")

@app.route("/")
def index():
    return render_template("index.html")

@app.route("/hello")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    app.run()

So the root path / will show react. The /hello path will show the response from flask.


text:
Q: Apigee Api proxy - how to make asynchronous call I have api that I would like to return to user as soon as the message is received by apigee. Do not wait for response from my service. Do you know how to do that using apigee api proxy?

A: The node.js method mentioned above is probably the most straight forward solution.  Information on using node.js with Apigee can be found at http://apigee.com/docs/api-services/content/developing-nodejs-applications-apigee-edge

A: I believe you tried the initial right approach Kaszaq using httpClient get method. As it's been documented in Apigee Docs.
http://apigee.com/docs/api-services/content/javascript-object-model
https://github.com/apigee/api-platform-samples/blob/master/sample-proxies/async-callout/apiproxy/resources/jsc/callout.js
And yes, if you want a more robust solution try Node.js.
//
//  Make 5 HTTP callouts to Yahoo weather to get the weather for 5 cities
//  The calls are all asynchronous and execute in parallel
//  httpClient returns an exchange object that will contain the HTTP response. . . when it arrives
//

var paloAlto = httpClient.get('http://weather.yahooapis.com/forecastrss?w=2467861');
context.session['paloAlto'] = paloAlto;

var anchorage = httpClient.get('http://weather.yahooapis.com/forecastrss?w=2354490');
context.session['anchorage'] = anchorage;

var honolulu = httpClient.get('http://weather.yahooapis.com/forecastrss?w=2423945');
context.session['honolulu'] = honolulu;

var newyork = httpClient.get('http://weather.yahooapis.com/forecastrss?w=2459115');
context.session['newyork'] = newyork;

var dublin = httpClient.get('http://weather.yahooapis.com/forecastrss?w=560743');
context.session['dublin'] = dublin;

A: As you have the liberty of customising API's using Node.js. You can use that to implement async behaviour in you api proxy.
For more info on customising api's using Node.js visit the following link-
http://apigee.com/docs/api-services/content/developing-nodejs-applications-apigee-edge


text:
Q: How to create Array and ArrayList in Java I need to make an array and add and delete from the end of the array.
The problem is I'v been asked to build Arraylist constructor to intialize the Array "list" but I got error on that
What Should I Do ??!!!
01. Creating an instance of ArrayList(‐1). The list size will become 10
02. Adding 15 items. Only 10 will be added
03. Here is the list
A C E G I K M O Q S
04. Calling delete three times
05. Here is the list
A C E G I K M
06. Calling expandByTen
07. Here is the list
A C E G I K M
08. Adding 15 items.
09. Here is the list
A C E G I K M B D F H J L N P R T V X Z
import java.util.ArrayList;

public class Main{

    /**
     * @param args
     */

     // create an array list

        char []list;
  int length;

  ArrayList(int maxSize)
   {
       if (maxSize<=0)
          length=10;
       else
           length=maxSize;

   }

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        ArrayList arrayList;
        System.out.println("01. Creating an instance of ArrayList(‐1). The list size will become 10");
        arrayList = new ArrayList(‐1);
        System.out.println("02. Adding 15 items. Only 10 will be added");
        for (int i = 65; i < 96; i += 2) {
           arrayList.insertEnd((char) i);
        }
        System.out.println("03. Here is the list");
        arrayList.print();
        System.out.println("04. Calling delete three times");
        arrayList.deleteEnd();
        arrayList.deleteEnd();
        arrayList.deleteEnd();
        System.out.println("05. Here is the list");
        arrayList.print();
        System.out.println("06. Calling expandByTen");
        arrayList.expandByTen();
        System.out.println("07. Here is the list");
        arrayList.print();
        System.out.println("08. Adding 15 items.");
        for (int i = 66; i `enter code here`< 97; i += 2) {
           arrayList.insertEnd((char) i);
        }
        System.out.println("09. Here is the list");
        arrayList.print();
      }
    }

A: The class ArrayList already exists... You don't need to write such constructor: ArrayList(int maxSize).
Instantiate your ArrayList as you just did in the main method:
List myList = new ArrayList(); //don't add a -1 parameter

Then, cleverly use the ArrayList methods that you will find in the Java API.
myList.add(...);
myList.remove(...);
myList.size();

A: Arraylist allocate size dynamically,  increases the size while you adding the element to it.
. So you can create arraylist like below.
 ArrayList arrayList= new ArrayList(10);

or
 ArrayList arrayList= new ArrayList();

You cant create  ArrayList with size -1.  replace new ArrayList(-1); to new ArrayList();
Remove the following useless code from your program. It wont work at all
 ArrayList(int maxSize)
   {
       if (maxSize<=0)
          length=10;
       else
           length=maxSize;

   }

There  is no method print(); ,deleteEnd(); , insertEnd((char) i); in Arraylist

A: *

*I don't see where you create a new instance of the char array.  Any reference to it will generate a NullPointerException

*I don't see the declaration or implementation of ArrayList.insertEnd(..) which would generate a compilation error, so I'm assuming you have not included it here (same goes for deleteEnd and expandByTen etc).

*Assuming you are creating the char[] instance somewhere with the length defined in the constructor, you set the size equal to 10 if the constructor argument is less than or equal to zero.  In the main method, you instantiate an instance of ArrayList with a size of -1, which should (based on what little you have provided) create (somewhere) an instance of the list field with a size of 10.  However, your first loop attempts to make 15 iterations, which will generate an IndexOutOfBounds exception at runtime if you aren't doing appropriate bounds checking in the insertEnd method.

I'm going out on a limb and guessing you are doing this as an assignment for school?  If not, be aware that Java has a whole plethora of containers, including java.util.ArrayList, in the java.util package.