text:
Q: Android action bar home button I've set my action bar like so but nothing happens when I click the home up button.
The two options below are enabled so shouldn't it go to the home activity automatically?
ab.setHomeButtonEnabled(true);
ab.setDisplayHomeAsUpEnabled(true);

Action Bar
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu, menu);

    final String[] activities;
    Resources res = getResources();
    activities =  res.getStringArray(R.array.activities);

    ActionBar ab = getActionBar();
    ab.setHomeButtonEnabled(true);
    ab.setDisplayHomeAsUpEnabled(true);
    ab.setTitle(R.string.app_name);
    ab.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
    ab.show();

    /** Create an array adapter to populate dropdownlist */
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_spinner_dropdown_item, activities);

    /** Setting dropdown items and item navigation listener for the actionbar */
    getActionBar().setListNavigationCallbacks(adapter, navigationListener);

    /** Enabling dropdown list navigation for the action bar */
    getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
    return true;
}

A: As other people have said, the behaviour doesn't happen automatically - you need to tell it where to go.
However, I need to add another answer, as the current answers are all breaking Android design guidelines - Back != Home. See the documentation
What you really want to be doing is something along the lines of this:
@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
    switch (menuItem.getItemId()) {
        case android.R.id.home:
            Intent homeIntent = new Intent(this, HomeActivity.class);
            homeIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(homeIntent);
    }
    return (super.onOptionsItemSelected(menuItem));
}

Which will take you to the parent activity, rather than just go through the back stack. I've also added the Intent.Flag to clear the back stack, it's a useful one to have when going to a home activity and can stop the back stack getting in a muddle when your users are using the 'Up' button

A: We have to define meta data into our child activity in AndroidManifast.xml file as per given in official document:
<application ... >
...
<!-- The main/home activity (it has no parent activity) -->
<activity
    android:name="com.example.myfirstapp.MainActivity" ...>
    ...
</activity>
<!-- A child of the main activity -->
<activity
    android:name="com.example.myfirstapp.DisplayMessageActivity"
    android:label="@string/title_activity_display_message"
    android:parentActivityName="com.example.myfirstapp.MainActivity" >
    <!-- The meta-data element is needed for versions lower than 4.1 -->
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value="com.example.myfirstapp.MainActivity" />
</activity>

There is no need to define meta data if version is 4.1 or above and you have to enable your action bar home button as you have done in your code. No need to use back button code and it is working fine with my android app: Helper+

A: You need to define what happens here:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        onBackPressed();
    }
    return true;
}

A: You can achieve this using below one method although there are lots of ways to do so.
put this line inside your onCreate
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

override method onSupportNavigateUp in your activity
@Override
public boolean onSupportNavigateUp() {
    finish();
    return super.onSupportNavigateUp();
}

A: Add these lines in your code:
@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {

    case android.R.id.home:
        System.out.println("Pressed Back Button");
        break;

    default:
        return super.onOptionsItemSelected(item);
    }
    return false;
}

A: You also need to make sure your App knows what to do when it is pressed:
@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
    switch (menuItem.getItemId()) {
    case android.R.id.home:
      // ProjectsActivity is my 'home' activity
      super. onBackPressed();
      return true;
    }
  return (super.onOptionsItemSelected(menuItem));
}


text:
Q: How to produce a PKCS8 private key encrypted by a symmetric key? If I try to produce a 3TDES encrypted PKCS 8 key using the OpenSSL command line:
openssl genrsa 512 | openssl pkcs8 -topk8 -v2 des-ede3-cbc

I get:
Enter Encryption Password:

What if I wanted to encrypt it using an actual key, not a key derived from a passphrase?
The PKCS8 RFC does not say which algorithm must be used to create the keyblock. It does give PKCS5 algorithms as example. Is there a way to use OpenSSL to create a PKCS8 key encrypted by a DES key? If not, is it just unsupported by OpenSSL or is it a very nonstandard thing to do?
Here is an example created using password based encryption through the OpenSSL command line (password "test"):
 0:d=0  hl=4 l= 422 cons: SEQUENCE
 4:d=1  hl=2 l=  64 cons:  SEQUENCE
 6:d=2  hl=2 l=   9 prim:   OBJECT            :PBES2
17:d=2  hl=2 l=  51 cons:   SEQUENCE
19:d=3  hl=2 l=  27 cons:    SEQUENCE
21:d=4  hl=2 l=   9 prim:     OBJECT            :PBKDF2
32:d=4  hl=2 l=  14 cons:     SEQUENCE
34:d=5  hl=2 l=   8 prim:      OCTET STRING
   0000 - 34 28 48 ce 80 65 2e 49-                          4(H..e.I
44:d=5  hl=2 l=   2 prim:      INTEGER           :0800
48:d=3  hl=2 l=  20 cons:    SEQUENCE
50:d=4  hl=2 l=   8 prim:     OBJECT            :des-ede3-cbc
60:d=4  hl=2 l=   8 prim:     OCTET STRING
   0000 - 87 9a 4b b1 4a 9a 5d 2a-                          ..K.J.]*
70:d=1  hl=4 l= 352 prim:  OCTET STRING
   0000 - 1a 93 74 14 57 96 80 ca-68 2f 06 82 a4 3c c5 bb   ..t.W...h/...<..
   0010 - 2e 32 81 28 89 d9 71 8c-f3 20 4c 3d d4 7a 8c 17   .2.(..q.. L=.z..
   0020 - 13 fd 8e bd 59 54 dd 17-4d 72 12 dd 24 71 af 39   ....YT..Mr..$q.9
   0030 - 16 64 3f 11 63 4b 36 b4-cf 5d 42 a7 4a 7e be 26   .d?.cK6..]B.J~.&
   0040 - b1 8e 60 2a 28 b8 21 f8-a6 0e 54 93 28 bb 46 e9   ..`*(.!...T.(.F.
   0050 - c9 45 1f 5a 91 17 d8 a0-06 b0 c4 1b c0 2f ee e1   .E.Z........./..
   0060 - fd d0 3b 44 23 2c 98 ab-ea e9 3e 2e f3 ce 14 04   ..;D#,....>.....
   0070 - f7 ab 4e 1a f2 f7 70 b0-02 51 aa cd 86 ae 97 f1   ..N...p..Q......
   0080 - 66 9f 75 72 06 2e a3 90-38 50 44 88 b0 8a c1 26   f.ur....8PD....&
   0090 - 57 1b 21 95 7b f9 af 66-c4 ac 4e 68 c4 32 cb 16   W.!.{..f..Nh.2..
   00a0 - 78 1c 55 d1 c1 b6 93 1c-15 ab 92 32 2c 6c 8d 2f   x.U........2,l./
   00b0 - 34 ba 09 a1 ac 4b 7a d0-86 cd 68 0d b8 67 2f 20   4....Kz...h..g/
   00c0 - 91 c7 79 64 0a cd f7 68-5f c3 08 ea 1a 4f d1 b8   ..yd...h_....O..
   00d0 - c6 ac ff ff a1 c0 38 e1-32 22 f4 76 60 60 6f 9d   ......8.2".v``o.
   00e0 - c0 07 32 ec 35 31 7a c5-d4 f3 0d cc 76 f4 f1 d2   ..2.51z.....v...
   00f0 - 77 79 11 4d 60 62 9b 23-56 23 a3 7d 9d 64 96 b0   wy.M`b.#V#.}.d..
   0100 - c4 c5 12 7f d4 87 07 fa-c4 8a 0a 03 9e 21 70 d8   .............!p.
   0110 - eb 8a 6b 24 ee 58 bc 23-82 23 ac 90 36 9a ab a0   ..k$.X.#.#..6...
   0120 - 9f c9 8d f5 07 f4 c6 53-6d 00 fd b3 9d 5b e9 cd   .......Sm....[..
   0130 - c4 f6 27 89 55 98 f0 bc-05 31 75 6a 2d d5 12 b1   ..'.U....1uj-...
   0140 - 41 9f e5 6b 45 6c 12 7d-02 ab b6 e6 78 6c 62 f3   A..kEl.}....xlb.
   0150 - d2 9d c1 29 de 98 22 ba-98 b5 47 7d 38 ff 82 50   ...).."...G}8..P

Here is a PKCS8 key I made manually, by using TDES CBC with a triple length key of all 0s (IV 5F218F117C86CEE1) to encrypt the "PrivateKeyInfo" ASN1 structure and then put that payload into an "EncryptedPrivateKeyInfo" ASN1 structure:
 0:d=0  hl=4 l= 378 cons: SEQUENCE
 4:d=1  hl=2 l=  20 cons:  SEQUENCE
 6:d=2  hl=2 l=   8 prim:   OBJECT            :des-ede3-cbc
16:d=2  hl=2 l=   8 prim:   OCTET STRING
   0000 - 5f 21 8f 11 7c 86 ce e1-                          _!..|...
26:d=1  hl=4 l= 352 prim:  OCTET STRING
   0000 - c1 dc 29 07 0d 4b 48 73-8a 6f 98 04 12 69 e0 ca   ..)..KHs.o...i..
   0010 - a6 d2 f3 94 01 ba aa c8-72 da d4 cb 99 92 96 cd   ........r.......
   0020 - f0 7f 92 b0 c9 4b 81 02-c6 28 a9 3a 26 68 44 e3   .....K...(.:&hD.
   0030 - 6a 52 4b a6 02 0d ef 72-07 d2 23 a4 0e c3 ab 2c   jRK....r..#....,
   0040 - 9c d7 8c 92 3c df 01 41-a5 b9 90 fc 91 f6 c3 6a   ....<..A.......j
   0050 - 83 02 2a e9 71 59 a4 70-36 16 45 be a6 2a c8 e7   ..*.qY.p6.E..*..
   0060 - 84 cc ce a9 fa 1f a0 60-e9 26 a2 d7 41 bb 3c 1a   .......`.&..A.<.
   0070 - 1b a4 47 21 dc 51 4d f7-ed dd 2a 8c 5f e6 68 9e   ..G!.QM...*._.h.
   0080 - f2 60 c1 79 bc d4 e7 0d-4b 90 4b 80 30 5b 30 f8   .`.y....K.K.0[0.
   0090 - 49 8f 7f 82 05 f7 d3 4d-51 f7 5d ff e8 7c c4 ff   I......MQ.]..|..
   00a0 - d9 ad a3 f9 33 08 22 29-9e da d5 ee 67 6a 68 a4   ....3.")....gjh.
   00b0 - 80 29 8f 6a d9 2b ef d5-50 87 69 9a 66 da 3e 78   .).j.+..P.i.f.>x
   00c0 - 0a 5d 9d 40 58 ea a3 88-92 62 d5 7c 72 05 f4 4d   .].@X....b.|r..M
   00d0 - 01 ca 8d fb 0b af 71 25-d8 1b a6 03 4d 74 f8 ac   ......q%....Mt..
   00e0 - 7d 77 44 08 e5 84 0d fb-15 c3 f7 d4 4c e7 50 b3   }wD.........L.P.
   00f0 - 08 96 9a 33 3c 74 05 ec-3d 8b 19 01 ba 04 d0 ab   ...3<t..=.......
   0100 - 47 32 6a d8 09 9b 0e 0e-58 f5 34 5f 8f 63 18 12   G2j.....X.4_.c..
   0110 - 22 a5 f7 e0 af 09 ed 16-22 2c 35 4a 8f 55 f3 22   ".......",5J.U."
   0120 - aa b1 e0 f4 27 df 45 ef-3b 04 08 19 89 67 dd 17   ....'.E.;....g..
   0130 - 47 13 55 3f 9d 0a a3 80-4d 6a 49 90 e9 83 90 ad   G.U?....MjI.....
   0140 - 1b 49 2f c1 1f c5 8b db-03 38 a4 13 03 ad fe 99   .I/......8......
   0150 - 1d 75 e7 b1 2f 83 ad e4-42 74 44 06 38 cb bd c4   .u../...BtD.8...

As far as I can tell, my keyblock conforms to the RFC. However since OpenSSL doesn't have the ability to produce something like this, and I can't find any test vectors for a similar type of PKCS8 encryption, I am concerned that this format is somehow nonstandard.
Does anyone know if it is correct to build a PKCS8 key this way (using a non-passphrase based encryption scheme)?
PKCS8 RFC https://www.rfc-editor.org/rfc/rfc5208
Unencrypted PKCS8 Private Key:
PrivateKeyInfo ::= SEQUENCE {
    version Version,
    privateKeyAlgorithm AlgorithmIdentifier {{PrivateKeyAlgorithms}},
    privateKey PrivateKey,
    attributes [0] Attributes OPTIONAL }

Is enciphered and placed into encrypted PKCS8 structure:
EncryptedPrivateKeyInfo ::= SEQUENCE {
    encryptionAlgorithm AlgorithmIdentifier {{KeyEncryptionAlgorithms}},
    encryptedData EncryptedData }

I'm not sure what these empty algorithm identifier definitions are for
PrivateKeyAlgorithms ALGORITHM-IDENTIFIER ::= {
     ... -- For local profiles
}

KeyEncryptionAlgorithms ALGORITHM-IDENTIFIER ::= {
     ... -- For local profiles
}

X509 RFC https://www.rfc-editor.org/rfc/rfc5280
This defines the algorithm identifier field
AlgorithmIdentifier  ::=  SEQUENCE  {
    algorithm               OBJECT IDENTIFIER,
    parameters              ANY DEFINED BY algorithm OPTIONAL  }

Cryptographic Message Syntax for TDES CBC AlgorithmIdentifier: http://www.ietf.org/rfc/rfc3370.txt
The AlgorithmIdentifier parameters field MUST be present, and the
parameters field must contain a CBCParameter:

CBCParameter ::= IV

IV ::= OCTET STRING  -- exactly 8 octets

A: Here is a response to the same-ish question on the OpenSSL mailing list:
http://marc.info/?l=openssl-users&m=137106970116394&w=2
It appears to be valid to create a PKCS8 keyblock using any cipher's AlgorithmIdentifier for the encryptionAlgorithm field.

"[T]he standard does not restrict the possible values, it may very
  well be possible that someone somewhere has a PKCS#8 implementation
  which accepts a value which does not refer to a password based
  encryption scheme."

redpajama_set_name: RedPajamaStackExchange


text:
Q: get code value in Alamofire jsonSerializationFailed Error :
responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Something looked like a 'true' but wasn't around character 0." UserInfo={NSDebugDescription=Something looked like a 'true' but wasn't around character 0.}))

I need to handle with code .I measn :
case .failure(let error):

if code  == 3840 {
}

I need to handle this with code. If i get this code then i need to show some message. So from the above error message with my above code how can I handle that failure case with the code value?
Thanks in advance ~~

A: You can get it from the response like this
result.response?.statusCode

read more about here:
https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#response-handling


text:
Q: joomla 3.5 creates multiple duplicates of articles I have a joomla 3.5 website that at some point started to show strange behaviors. In the back-panel, all the articles have been duplicated around 20 times and each set of suplicated articles share the same ID (I checked the DB and it correctly contains only one entry for each article). This problem happens also when I create a new article, since the system creates also a lot of copy of it. I am also not able to delete the duplicated copies, because any action (publishing, unpublishing, trashing, ...) that I apply to one of the copy, affects also all the other ones (which makes sense since they share the same ID).
Any ideas?

A: It seems that you have touched the query that presents the list, namely the join because if this is not set correctly it has several occurring repeated times, so with the same id.
Activate joomla debugging and so see the query that generates the list so try it out to find the error.


text:
Q: Using a string stored in a variable as a name for another variable I want to concatenate a string passed as argument with another word and then use it as a variable name for an array. Is this allowed?
function getFromSomewhere(arg1) {

string newName = arg1 + "sampleWord";

var (use NewName here) = [];

}

A: Not allowed, unfortunately. Variable names, such as newName, that we see are rid of at compilation time for optimization. Your machine will have no use for it's name newName during runtime, which is when you're trying to assign the name to it.

A: You could use an object with the wanted fruits as key for the array, like in the example.
The object is easy to access and to maintain.

var array = ["apple", "banana", "grapes"],
    prices = {};

array.forEach(function (k) {
    prices[k] = [];
});

prices.apple.push(1, 10, 3);

console.log(prices.apple[2]);
console.log(prices);

A: You can use newName as the name of a property
function getFromSomewhere(arg1) {

    var myVariableNamedAtRuntime = [];

    string newName = arg1 + "sampleWord";

    myVariableNamedAtRuntime[newName] = [];

}

and then access the array as ...
myVariableNamedAtRuntime[newName]

A: There is no way you can add new variables to the function definition after the function is defined.. However you can always add new properties to the function object defined or it's prototype and you can access them as follows;

function getFromSomewhere(arg1) {

  var newName = arg1 + "_sampleWord_";
  this.getFromSomewhere.varName = newName + "test";
  this.getFromSomewhere.prototype.varName = newName + "best";
  console.log(this.getFromSomewhere.varName);
  console.log(this.getFromSomewhere.prototype.varName);
}

getFromSomewhere("test");

A: You can add the variable to the window object:
function getFromSomewhere(arg1) {
  var newName = arg1 + "sampleWord";
  window[newName] = [];
}

getFromSomewhere("blip");
console.log(blipsampleWord); // You'd get []

A: Yes it is possible. But no, you dont want to do that. Dynamic variable names are always a sign, that you should use an object instead. In this case i think you could simply map your array of strings to an array of objects:
 function namesToObj(arr){
   return arr.map( name => ({
    name,
    price:10
   }));
}

 namesToObj(["banana","tomato"])
 /*results in
 [{name:"banana",price:10},{name:"tomato",price:10}]
 */


text:
Q: Shortcut with holding more keys and one char with click in c# selenium automation I have a shortcut with holding keys CRTL + ALT + E + CLICK on button.
In selenium I'm trying to do this with like below
var actions = new Actions(Driver)
then
actions.KeyDown(Keys.Control + Keys.Alt).SendKeys("E").Click(Button).Perform();
Method SendKeys("E") is doing KeyDown and then KeyUp and that's why, I can not create correct shortcut with click because I'm not holding "E".
Any tips how to perform KeyDown("E") ?
EDIT:
actions.ClickAndHold(ActionButtons.Edit.Init());
 actions.SendKeys(Keys.Control + Keys.Alt + "e" + Keys.Clear);
 actions.Build().Perform();
Also I find other way with ClickAndHold(). The principle is click and send sequence of keys and in the same time release click.
Any suggestions, how to do that ?

A: Try below code
 actions.SendKeys(Keys.Control + Keys.Alt + "e").Click(Button).Perform();


text:
Q: Выбрать все элементы после определенного Есть список, мне нужно что бы при наведении мышкой на перый елемент списка подчеркивались все остальные, пытаюсь сделать так:

$('.title_content').hover(function() {
  $(this).nextAll('a').css({
    'text-decoration': 'underline'
  });
})
ul {
  list-style: none;
}

a {
  text-decoration: none;
  color: black;
}

USER INTERFACE DESIGN

Wirefarming

Prototyping

Usability testing

Но ничего не получается, подскажите в чем проблема?
Вот как это должно быть:

A: $().nextAll - выбирает элементы в том же родителе.

$('.title_content').hover(function() {
  $(this).closest('li').nextAll('li').find('a').css({
    'text-decoration': 'underline'
  });
})
ul {
  list-style: none;
}

a {
  text-decoration: none;
  color: black;
}

USER INTERFACE DESIGN

Wirefarming

Prototyping

Usability testing


text:
Q: How to write if-else in shell and echo the ouput to a variable Checking whether the reddis is working using this command
redis-cli ping if output is PONG redis is working.
How to re-write this in shell script like this

#!/bin/bash
redis_metrics=$(redis-cli ping)

if [$redis_metrics == PONG]
then
        echo "100"
else
        echo "0"
fi

Need to assign the echo output value to a variable - redis_status

A: You can try this one :
#!/bin/bash
redis_metrics=$(redis-cli ping)

if [ $redis_metrics == PONG ]
then
        redis_status=100
        echo "100"
else
        redis_status=0
        echo "0"
fi


text:
Q: visualforce: select option for custom setting field Hi I have difficulties with regards to custom settings, I have this field Type__c which has the data type 'text' and uses it in my visualforce. My field Type__c has 3 selections to choose inside the dropdown. Since the custom settings don't have the datatype Picklist, how can I create picklist selection on visualforce with a controller? i hope you'll help me.
<apex:outputLabel > Tyoe :</apex:outputLabel>
<apex:selectList size="1" >
    <apex:selectOption itemLabel="--None--" itemvalue=""></apex:selectOption>
    <apex:selectOption itemLabel="Sandbox" itemvalue=""></apex:selectOption>
    <apex:selectOption itemLabel="Production" itemvalue=""></apex:selectOption>
    <apex:selectOption itemLabel="Developer" itemvalue=""></apex:selectOption>
</apex:selectList>

this is my save method
public PageReference save(){
        try{
            upsert orgInfo;
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM,'Created successfully'));
            ScheduledOrgInfoFetch.ScheduledOrgInfoFetch();
        }
        catch(System.DMLException e){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Invalid Credentials'));
        }
            orgInfo = null;
            return null;
    }
    enter code here

A: If you want to leverage picklist fields in your configuration records, you can use Custom metadata types. Its an alternative and better version of Custom Settings and support picklist fields.
If your uuse case doesnt allow you to use CMT, you can do the following to render a dropdown in the UI and save its value in apex class.
<apex:outputLabel > Tyoe :</apex:outputLabel>
<apex:selectList size="1" value="{!selectedType}">
    <apex:selectOption itemLabel="--None--" itemvalue=""></apex:selectOption>
    <apex:selectOption itemLabel="Sandbox" itemvalue=""></apex:selectOption>
    <apex:selectOption itemLabel="Production" itemvalue=""></apex:selectOption>
    <apex:selectOption itemLabel="Developer" itemvalue=""></apex:selectOption>
</apex:selectList>

In your apex class:
public String selectedType{get;set;}

public void MethodOfSave()
{
   CustomSettings__c cd = new CustomSettings__C();
   cd.Type__c = selectedType;
...
}

This should allow you to save the selected picklist value into Type__c field.


text:
Q: Insert data from a dataset to an Excel table in a worksheet using powershell I have an Excel file with 3 worksheets, the third is called "DataArea". This worksheet has a empty table called "Table1" with 2 columns "Column1" and "Column2". I already retrieve the data from my SQL server database, so i have 2 columns in a dataset. My scope is to insert the information contained in my dataset to that table in excel, in need to do this because because the table is the source of a graphic in the second sheet.
Is there a way to do that?
Thanks in advance.

A: Take this one, see comments:
Add-Type -AssemblyName Microsoft.Office.Interop.Excel

# create dummy datatable with 2 colums
$dt = New-Object System.Data.DataTable
[void]$dt.Columns.Add('Column1',[string]::empty.GetType() )
[void]$dt.Columns.Add('Column2',[string]::empty.GetType() )

#fill datatable
for( $i = 0; $i -lt 10; $i++ ) {

    $row          = $dt.NewRow()
    $row.Column1  = 'Hello' + $i.ToString()
    $row.Column2  = 'World' + $i.ToString()
    [void]$dt.Rows.Add( $row )
}

# to move a datatable to excel, it must be an n-dimensional array of objects
# move datatable to object-array:

$excelArray = New-Object 'object[,]' $dt.Rows.Count, $dt.Columns.Count

for( $i = 0; $i -lt $dt.Rows.Count; $i++ ) {
    $excelArray[$i, 0] = $dt.Rows[$i].Column1
    $excelArray[$i, 1] = $dt.Rows[$i].Column2
}

# open excel file
$excelFile = 'D:\test\emptySheet.xlsx'

$excel                = New-Object -ComObject Excel.Application
$excel.Visible        = $true
$excel.ScreenUpdating = $true

$workbook  = $excel.Workbooks.Open( $excelFile ,$null, $false )

$ws        = $workbook.WorkSheets.item(1)

[void]$ws.Activate()

# select range
$range = $ws.Range('A1', ([char](64 + $dt.Columns.Count)).ToString() + ($dt.Rows.Count).ToString() )

# copy aray to excel range
$range.Value2 = $excelArray

# save and cleanup
[void]$workbook.Save()
[void]$workbook.Close()
[void]$excel.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel) | Out-Null


text:
Q: A question regarding a paragraph.
There's this paragraph here, and the question reads:
"The first people who invented a system of drains and plumbing are the..."
I'm convinced that the answer is People of The Secret Cities whilst people tell me it's the Romans,
If it is the Romans, can I have an explanation to why?

A: You are right, it isn't the Romans, according to this passage.
The point the passage is making is that while the Romans are generally thought to be the inventors of this level of plumbing technology, the people of the Secret Cities actually had them 2,500 years earlier than the Romans did.
The quotes around "first invented" are scare quotes implying irony, in the same way that they'd be used in a sentence reading, "When Columbus 'discovered' America, he ...", the point there being that he can't have discovered America when it was already inhabited by people who'd arrived there before he did, and had been visited by the Vikings 400 or 500 years before his arrival.
One might suggest that "discovered" and "invented" can mean "from the point of view of a particular population that didn't know about them before". If the Romans figured out plumbing without having had any idea that it had existed somewhere else in the world centuries earlier, and the technology as the Romans developed it is what spread throughout the rest of the world, leading directly to the technology of plumbing as we know it today, then the Romans "invented" it in that sense of the word. Likewise, if the pre-Columbian residents of the New World never returned to the Old World and spread news about the New World (and possibly didn't even realize it had never been known to humankind before), and if word from the Vikings didn't really get around, so that, as far as most of the world knew at the time, Columbus's expeditions were the source of this knowledge that then spread widely, then Columbus was the "discoverer" in that sense.
But in the sense of "first people ever to create", the Romans weren't the inventors.


text:
Q: BIGINT mysql performance compared to INT I'm trying to find out if my table will get less performant if I change the primary key to BIGINT(20). At the moment, I'm using INT(7) and have about 300.000 entries already with large IDs (7 or 8 digits).
I searched a lot already but only found out that it uses more disk-space (which is obvious).
All of my IDs have 7 digits right now, but my customer wants to change to 8 digits. I won't be able to easily change the software in the future, so I thought about using BIGINT(20) now just in case. Would it be less performant if I use BIGINT even though I don't need to yet?
Does anyone with experience doing this have suggestions regarding speed and performance?

A: Not wishing to resurrect a zombie, but 'modern' mysql uses the column type serial, which is a bigint(20) unsigned NOT NULL AUTO_INCREMENT - and certainly suggests that mysql will be (or is) going to be optimised for using bigint as a primary key.
Also, rather than using serial, varbinary(16) primary allows for one (we do this) to use uuid_short() for the primary key (not uuid – which is very slow to use as a primary, because it's a string) - which has the feature of ensuring that every record has a key which is unique across the entire database (indeed - network).
But be aware - some coercion's will degrade bigint to int with bad results. If, for instance, you are comparing a string representation with a big int - you may find that you get false positives. So one must compare using binary... eg
where id = binary id_str

Personally I would call this an unfixed bug...

A: To answer your question: yes it'll get less performant. Obviously, the bigger the type, the bigger the table, the slower the queries (more I/O, bigger indexes, longer access time, result less likely to fit in the various caches, and so on). So as a rule of thumb: always use the smallest type that fits you need.
That being said, performance doesn't matter. Why? Because when you reach a point where you overflow an INT, then BIGINT is the only solution and you'll have to live with it. Also at that point (considering you're using an auto increment PK, you'll be over 4 billions rows), you'll have bigger performance issues, and the overhead of a BIGINT compared to a INT will be the least of your concerns.
So, consider the following points:

*

*Use UNSIGNED if you don't need negative values, that'll double the limit.

*UNSIGNED INT max value is 4.294.967.295. If you're using an auto increment PK, and you only have 300.000 entries, you really don't need to worry. You could even use a MEDIUMINT at the moment, unless you're planning for really really fast growth. (see http://dev.mysql.com/doc/refman/5.1/en/integer-types.html)

*The number in parenthesis after the type doesn't impact the max value of the type. INT(7) is the same as INT(8) or INT(32). It's used to indicate the display width if you specify ZEROFILL (see http://dev.mysql.com/doc/refman/5.1/en/numeric-type-overview.html)


text:
Q: how to print Original request body JSON without any modification in java? Normally to print out request body i using ObjectMapper, but this way removing space and printing object to string in one line, example :
if i send request body like this :
{
   "Header" : "value"
}

and i using objectMapper to print that object
ObjectMapper mapper = new ObjectMapper();
mapper.writeValueAsString(requestBody)

the out put is like this :
{"Header":"value"}

how to print Original request body without any modification ?

A: I'm not sure if you can print it in it's original form but you can pretty print it.
With Jackson's Object Mapper, you can do something like:
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(body);
System.out.println(json);

or
ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
String json = mapper.writeValueAsString(body);
System.out.println(json);

A: I don't think you can do this without using any framework.
But you can use the gson for this if you enable the prettyPrinting option. Example:
Gson gson = new GsonBuilder()
            .setPrettyPrinting()
            .create();

prettyPrintedString = gson.toJson(requestBody, Object.class);


text:
Q: JSON parse image came out blank android Hi I've look through all the stackoverflow and tried a few solutions,and I still cant solve my problem. I'm still fairly new to json parsing and android, any help would be greatly appreciated.
this is my json url-http://vina.harvestcamasu.com/vina/xml/image.json
and this is the code that I tried
    json = jParser.getJSONFromUrl(url);

                    JSONObject json = jParser.getJSONFromUrl(url);

                    System.out.println("json is "+json);
                    System.out.println("Length"+TAG_IMAGE
                            .length());

                    for (int i = 0; i < json.length(); i++) {
                        try {
                            String atObj = Integer.toString(i);
                            System.out.println(atObj);
                            JSONObject jObj = json.getJSONObject(atObj);
                            System.out.println(jObj.getString("Name"));
                            System.out.println(jObj.getString("PicURL"));
                            System.out.println(jObj.getString("Caption"));
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    JSONArray iArray;
                    try {
                        iArray = json.getJSONArray(TAG_IMAGE);
                        for (int i = 0; i < iArray.length(); i++) {
                            JSONObject m = iArray.getJSONObject(i);

                            String Id       = m.getString(TAG_ID);
                            String Name     = m.getString(TAG_NAME);
                            String PicURL   = m.getString(TAG_PICURL);
                            String Date     = m.getString(TAG_DATE);
                            String Caption  = m.getString(TAG_CAPTION);

                            //create a new hashmap
                            HashMap<String, String> map = new HashMap<String, String>();

                            //adding nodes into hashmap
                            map.put(TAG_ID, Id);
                            map.put(TAG_NAME, Name);
                            map.put(TAG_PICURL, PicURL);
                            map.put(TAG_DATE, Date);
                            map.put(TAG_CAPTION, Caption);

                            //adding hashlist into arraylist
                            imagelist.add(map);
                            images[i] = m.getString(TAG_PICURL);

                        }
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    InputStream is1 = (InputStream) new URL(images[0]).getContent();
                    d1 = Drawable.createFromStream(is1, "src name");
                    InputStream is2 = (InputStream) new URL(images[1]).getContent();
                    d2 = Drawable.createFromStream(is2, "src name");
                    InputStream is3 = (InputStream) new URL(images[2]).getContent();
                    d3 = Drawable.createFromStream(is3, "src name");
                    InputStream is4 = (InputStream) new URL(images[3]).getContent();
                    d4 = Drawable.createFromStream(is4, "src name");
                    InputStream is5 = (InputStream) new URL(images[4]).getContent();
                    d5 = Drawable.createFromStream(is5, "srcname");

                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return json;

            }

and the log keeps returning the error of
    12-04 10:12:02.892: W/System.err(28210): org.json.JSONException: No value for 0
    12-04 10:12:02.892: W/System.err(28210):    at
    org.json.JSONObject.get(JSONObject.java:354)
    12-04 10:12:02.892: W/System.err(28210):    at
    org.json.JSONObject.getJSONObject(JSONObject.java:569)
    12-04 10:12:02.892: W/System.err(28210):    at
    vinajson.img.MainActivity$1.doInBackground(MainActivity.java:82)
    12-04 10:12:02.892: W/System.err(28210):    at
    vinajson.img.MainActivity$1.doInBackground(MainActivity.java:1)
    12-04 10:12:02.892: W/System.err(28210):    at
    android.os.AsyncTask$2.call(AsyncTask.java:264)
    12-04 10:12:02.892: W/System.err(28210):    at
    java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
    12-04 10:12:02.892: W/System.err(28210):    at
    java.util.concurrent.FutureTask.run(FutureTask.java:137)
    12-04 10:12:02.900: W/System.err(28210):    at
    android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
    12-04 10:12:02.900: W/System.err(28210):    at
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
    12-04 10:12:02.900: W/System.err(28210):    at
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
    12-04 10:12:02.900: W/System.err(28210):    at
    java.lang.Thread.run(Thread.java:856)
    12-04 10:12:02.900: W/System.err(28210): org.json.JSONException: No value for Image
    12-04 10:12:02.900: W/System.err(28210):    at
    org.json.JSONObject.get(JSONObject.java:354)
    12-04 10:12:02.900: W/System.err(28210):    at
    org.json.JSONObject.getJSONArray(JSONObject.java:544)
    12-04 10:12:02.900: W/System.err(28210):    at
    vinajson.img.MainActivity$1.doInBackground(MainActivity.java:93)
    12-04 10:12:02.900: W/System.err(28210):    at
    vinajson.img.MainActivity$1.doInBackground(MainActivity.java:1)
    12-04 10:12:02.900: W/System.err(28210):    at
    android.os.AsyncTask$2.call(AsyncTask.java:264)
    12-04 10:12:02.900: W/System.err(28210):    at
    java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
    12-04 10:12:02.900: W/System.err(28210):    at
    java.util.concurrent.FutureTask.run(FutureTask.java:137)
    12-04 10:12:02.900: W/System.err(28210):    at
    android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
    12-04 10:12:02.900: W/System.err(28210):    at
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
    12-04 10:12:02.900: W/System.err(28210):    at
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
    12-04 10:12:02.900: W/System.err(28210):    at
    java.lang.Thread.run(Thread.java:856)
    12-04 10:12:02.900: W/System.err(28210): java.net.MalformedURLException

A: Because Image JSONArray is inside Artist JSONObject and Artist inside Gallery JSONObject so you should follow same hierarchy to extract JSONObject from Image JSONArray to retrieve all values as:
JSONObject json = jParser.getJSONFromUrl(url);

// get Gallery JSONObject
JSONObject json_gallery=json.getJSONObject("Gallery");
// get Artist JSONObject
JSONObject json_artist=json_gallery.getJSONObject("Artist");

// now get Image JSONArray of JSONObject from json_artist

 iArray = json_artist.getJSONArray(TAG_IMAGE);
 for (int i = 0; i < iArray.length(); i++) {
     // your code here for retrieving values
  }


text:
Q: Cannot debug over VPN - Visual Studio 2010 I have no trouble debugging from Visual Studio 2010 when I go to work and wire into the LAN.
However, when I telecommute over the corporate VPN, I cannot debug, because when I try to debug, the monitor correctly shows a status of <datetime>  CONNECTED, but Visual Studio 2010 comes back with the "Unable to connect ...The remote computer cannot connect back to this computer" message.
There is no change in procedure between debugging from home or debugging from work; it simply won't work over the VPN...
The remote machine is my VM running on corporate servers someplace. I can ping my developer machine from the remote virtual machine, and I'm using Windows authentication mode. Both machines are Windows 7 64-bit.
The application I wrote is deployed using the full-trust mode of ClickOnce.
Why?

A: Here's what was wrong:
Our corporate firewall allows remote clients to come in via SSLVPN and see everything at the corporation. What our firewall does not have is the reverse rule which allows computers already within the firewall to see remote clients as soon as they log in.
Therefore, the machine being debugged, which was running MSVSMON.EXE, could not see the machine running the Visual Studio 2010 debugger.


text:
Q: Regex not working / taking effect I have some values fetched from a TextField, stored to a Array and I'm going to filter it through a for loop. I want to keep out symbols like []{}; and so on, while also allowing whitespaces and the - for some words. So, I constructed this:
$Regex = '/^[a-zA-ZÀ-ÖØ-öø-ÿ0-9 \-]*$/';
$FieldRegex = (preg_match($Regex, $Field[$counter]));

for ($counter = 0; $counter <= 6; $counter++){

if(!$FieldRegex) {

                echo '<script language="javascript">';
                echo 'alert("Only numbers, letters and - are allowed!")';
                echo '</script>';

                header("Location:{$_SERVER['HTTP_REFERER']}");
                break;
                exit;

} else {
                if($counter == 6){
                $Proceed1 = true;
}

The problem that persists through each try is that anything that I try to submit, it won't give me any message and doesn't save to the DB, even if it fits within the regex parameters.
I've been wrapping my head around it but can't seem to find the answer.
What am I doing wrong?

A: You should use a u modifier with a pattern containing Unicode characters for it work correctly in all cases, and you also need to place the $counter setting code line inside the loop for the variable to get assigned a value correctly:
$Regex = '/^[a-zA-ZÀ-ÖØ-öø-ÿ0-9 -]*$/u';
for ($counter = 0; $counter <= 6; $counter++){
    if(!preg_match($Regex, $Field[$counter])) {
                echo '<script language="javascript">';
                echo 'alert("Only numbers, letters and - are allowed!")';
                echo "</script>\n";
                header("Location:{$_SERVER['HTTP_REFERER']}");
                break;
                exit;

    } else {
                if($counter == 6){
                    $Proceed1 = true;
                }
    }
}

See the PHP demo.
Note that in case you need to match any letters, you may change the '/^[a-zA-ZÀ-ÖØ-öø-ÿ0-9 -]*$/u'; regex to '/^[\p{L}0-9 -]*$/u'; where \p{L} matches any Unicode letter.


text:
Q: std::shared_ptr constructed from this I want to add all objects of a class to a std::map. Since I don't want to copy objects, I try to get a workaround using smart pointers like this:
Class.h
class A : public std::enable_shared_from_this<A> {
public:
    A();
    ~A();
    static std::map<uint32_t, std::shared_ptr<A>> getObjects();
private:
    static uint32_t counter;
    uint32_t id;
    static std::map<uint32_t, std::shared_ptr<A>> objects;
};

Class.cpp
A::A()
{
    id = counter++;
    std::shared_ptr<A> ptr = std::make_shared<A>();
    objects[id] = ptr->shared_from_this();
}

A::~A()
{
    objects.erase(id);
}

std::map<uint32_t, std::shared_ptr<A>> A::getObjects()
{
    return objects;
}

uint32_t A::counter=0;

std::map<uint32_t, std::shared_ptr<A>> A::objects;

This compiles fine but when trying to use it like this
int main(){
    A a;
    A b;
    auto objects = A::getObjects();
}

i get

Segmentation fault: 11`

If I try to change the constructor to
A::A()
{
    id = counter++;
    std::shared_ptr<A> ptr(this);
    objects[id] = ptr->shared_from_this();
}

i get

pointer being freed was not allocated

I basically need to get a std::shared_ptr<A> constructed from this but can't manage to get it work.

A: You cannot get an owning shared pointer to an object not managed by a shared pointer.
Automatic storage objects lifetime may not have their lifetime managed by a shared pointer.
In general, your design cannot be done, as objects and object lifetime is controlled by the code creating the object, not the object itself.
Smart pImpl wrappers can make the guts of an object have a separate smart pointer determined lifetime.  But even there that shared pointer solution is illegal, as destroying the map can kill the last shared pointer, which then attempts to reenter the map code and erase it.  This is undefined behaviour.
A mixture of weak pointer map contents, pImpl based wrappers, smart deleters that deregister instances, and other work might work.  That is beyond the scope of a SO answer.
You have to learn about how to manage object lifetime, how weak ptrs work, alternative deleters, pImpl based value-types, and a myriad of other subjects to pull this off.   Good luck.

A: Your original code has a stack-overflow:

A::A()
{
    id = counter++;
    std::shared_ptr<A> ptr = std::make_shared<A>();
    objects[id] = ptr->shared_from_this();
}

You unconditionally construct A within A's constructor.
What you then tried also doesn't work:

A::A()
{
    id = counter++;
    std::shared_ptr<A> ptr(this);
    objects[id] = ptr->shared_from_this();
}

shared_from_this() only works if this object's lifetime is being managed by a std::shared_ptr.

There are a couple options for what you could do. You could use a static factory function and not expose the constructor, but that's an unexpected design for your class.
What seems a clearer design to me is to do something similar to the Pimpl pattern. You can have std::shared_ptrs to the actual implementation of A, and wrap the functionality in an object that simply contains the shared_ptr.

A: If you need all instances of a class stored in a global map, you can try this: 1) hide all constructors; 2) only create new objects via a static ('factory') method. In your case, this method can return a shared_ptr (or, say, it can return a reference, the shared_ptr itself private to the global map; in this case you can even use unique_ptr).


text:
Q: GetSchemaTable returns weird/incorrect columnames I have MS-SQL Database and want to read the data of a table in a DataTable.
When I use GetSchemaTable to load in DataTable, I can't get de correct column names.
The code to get the schema:
SqlCommand nCmd = new SqlCommand("SELECT * FROM import", con);
SqlDataReader reader = nCmd.ExecuteReader();

DataTable schemaTable = reader.GetSchemaTable();

while (reader.Read())
{
   returnData += reader["NAME"];
}

reader.Close();

The reader["NAME"] is filled with expected data. (Just to be sure I can get it by it's columname.)
I try to read the columnnames from schema:
DataColumnCollection columns = schemaTable.Columns;

foreach (DataColumn column in columns)
{
    returnData += column.ColumnName;
}

It returns:
ColumnOrdinal
ColumnSize
NumericPrecision
NumericScale
IsUnique
IsKey
BaseServerName
BaseCatalogName
...etc instead of the read column names.

I seached for it. And there seems to be a bug about it. I was directed to use OleDbConnection, but it makes no difference in this case.
What am I doing wrong?


text:
Q: A form $F$ is simple if and only if $F\wedge F=0$? Gravitation by Charles W. Misner, Kip Throne and John Wheeler page 93 Box 4.1 point 5 b. Applications: a.
"In four dimensions, all 0 forms, 1- forms, 3-forms, and 4-forms are simple. A 2-form $F$ is generally a sum of two simple forms, e.g., $F=-edt\wedge dx+hdy\wedge dz$; it is simple if and only if $F\wedge F=0$" where simple form is defined to be the "one that can be written as a wedge product of $p$ 1-forms: $\sigma_p=\alpha \wedge...(p~factors)\wedge \gamma$."
Question:

*

*Does the conclusion here $F\wedge F=0$ specifically applied to $F=-edt\wedge dx+hdy\wedge dz$? or does it apply to any 2 form in 4 dimension? or does it apply to any 2 form in any dimesion?

*The statement "A form $F$ is simple if and only if $F\wedge F=0$": I have a hard time to prove if $F\wedge F=0$ then $F$ is simple for general cases. Could you demonstrate a general proof, please?

A: Let $F\in \Omega^p(\mathbb{R}^d)$ be an arbitrary $p$-form in $d$ dimensions, where $1\leq p\leq d$.

*

*Clearly any form $F$ squares to zero: $F\wedge F=0$ if $p$ is odd or if $2p>d$.

*Clearly any simple/decomposable $F$ squares to zero: $F\wedge F=0$.

*
Proposition 1: The opposite implication
  $$\forall F\in \Omega^p(\mathbb{R}^d):~~F\wedge F=0~\Rightarrow~ F\text{ decomposable}\tag{1}$$
  holds if and only if $p=2$ and $d\geq 4$.

*Tomas Brauner's answer shows the "if" part of Proposition 1 by using the fact that any 2-form/antisymmetrix matrix can be brought on 2-block diagonal form.

*The "only if" part of Proposition 1 can be seen by finding suitable counterexamples. E.g. in the case $p=4$ and $d\geq 8$, one may check that
$$ F~=~(\mathrm{d}x^1 \wedge \mathrm{d}x^2+ \mathrm{d}x^3 \wedge \mathrm{d}x^4)\wedge \mathrm{d}x^5 \wedge \mathrm{d}x^6 \tag{2}$$
squares to zero but is not$^{\dagger}$ decomposable.
--
$^{\dagger}$ Sketched indirect proof of non-decomposability of (2):  Assume that the 4-form (2)
$$F~=~A_1\wedge A_2 \wedge A_3 \wedge A_4\tag{3}$$
is decomposable with four 1-forms
$$A_k~=~\sum_{j=1}^d a_{kj} \mathrm{d}x^j, \qquad k~\in~\{1,2,3,4\}.\tag{4}$$
Next explore that various contractions yield
$$\forall j\geq 7:~~ i_j F~=~0,\tag{5}$$
and
$$i_1i_3F~=~0,\quad i_1i_4F~=~0,\quad i_2i_3F~=~0, \quad i_2i_4F~=~0,\tag{6} $$
to derive that
$$\forall k\in\{1,2,3,4\}~\forall j\geq 7:~~ a_{kj}~=~0,\tag{7}$$
and that $\forall k,\ell\in\{1,2,3,4\}:$
$$
a_{k1}a_{\ell 3}~=~a_{k3}a_{\ell 1}~\wedge~
a_{k1}a_{\ell 4}~=~a_{k4}a_{\ell 1}~\wedge~
a_{k2}a_{\ell 3}~=~a_{k3}a_{\ell 2}~\wedge~
a_{k2}a_{\ell 4}~=~a_{k4}a_{\ell 2}, \tag{8} $$
and therefore
$$\forall k,\ell\in\{1,2,3,4\}:~~ (a_{k 1}, a_{k 2}, a_{k 3}, a_{k 4}) ~~\parallel~~(a_{\ell 1}, a_{\ell 2}, a_{\ell 3}, a_{\ell 4}).\tag{9} $$
Deduce that the four 1-forms (4) are spanned by $\mathrm{d}x^5$, $\mathrm{d}x^6$ and only one more 1-form, and hence the four 1-forms (4) are not linearly independent. Contradiction. $\Box$

A: Let me add an argument that is much less general than the answer by Mike Stone, but somewhat more elementary. It is valid for 2-forms regardless of the dimension of the base space the forms act on.
So, a general 2-form $F$ can be written in an arbitrarily chosen basis of 1-forms $e^i$ as $F=\frac12f_{ij}e^i\wedge e^j$. The matrix of coefficients $f_{ij}$ is antisymmetric, and thus can be made block-diagonal by a suitable change of basis. In other words, the form $F$ can always be expanded as
$$
F=f_{12}e^1\wedge e^2+f_{34}e^3\wedge e^4+\dotsb.
$$
It follows immediately that $F\wedge F=0$ if and only if the above expansion contains at most one term (that is, exactly one term as long as the form $F$ is nonzero). This answers your questions.

A: The general condition for an $n$-form with components $T^{\mu_1,\mu_2,\ldots \mu_n}$ to be writable  as a single wedge product
$$
T=U_1\wedge U_2,\wedge\ldots \wedge U_n
$$
is
$$
T^{\mu_1\mu_2\ldots\mu_{n-1}[ \nu_1}T^{\nu_2\nu_3\ldots \nu_{n+1}]}=0
$$
for all possible choices of the indices.
where $[\ldots]$ means antisymmetrize.  Thus a three index antisymmetric tensor is decomposable if
$$
T^{i_1i_2j_1}T^{j_2j_3j_4}-T^{i_1i_2 j_2}T^{j_1j_3j_4}+T^{i_1i_2j_3}T^{j_1j_2j_4}-T^{i_1i_2 j_4}T^{j_1j_2j_3}=0
$$
These are the Plücker conditions. It is fairly easy to show that they are necessary, but I do not know an  easy way to show that they are sufficient.


text:
Q: I'm trying to find an algorithm for merging m sorted lists (of total n elements) in n log2 m runtme Above says it all. I cannot really think of a way to do this, and how to prove it. Any ideas?

A: Put the input lists in a heap (aka a priority queue) where each list's priority is its first element.  To get the next element of the output list, pull the top list off the heap, append its first element to the output list, remove that element from the input list, and (if the input list is not empty) put the input list back in the heap.  Repeat until the heap is empty.
See this question and answer on Computer Science stackexchange for more details.


text:
Q: Image of $(\Bbb Z/p\Bbb Z)^\times$ under a polynomial map. Consider the following result:

Proposition. For an odd prime $p$ such that $\left(\frac{-1}{p}\right)=-1$, every square in $(\Bbb Z/p\Bbb Z)^\times$ is of the form $x^3+x$.

I am trying to give a general formulation for such phenomenon, namely

*

*Given an odd prime $p$, characterize the polynomials $f\in\Bbb Z[x]$ such that the image of $h_f: (\Bbb Z/p\Bbb Z)^\times\to (\Bbb Z/p\Bbb Z)^\times, h_f(x)=f(x)$ contains the group of quadratic residues mod $p$.

*Given a polynomial $f\in\Bbb Z[x]$, characterize the odd primes $p$ such that the image of $h_f: (\Bbb Z/p\Bbb Z)^\times\to (\Bbb Z/p\Bbb Z)^\times, h_f(x)=f(x)$ contains the group of quadratic residues mod $p$.

Note: The proposition on the top is equivalent to the following statement related to the number of solutions a polynomial congruence:

There are exactly $p-1$ solutions to the equation $x^3+x=y^2$ in $(\Bbb Z/p\Bbb Z)^\times$ for odd prime $p = 3 \bmod 4$.


text:
Q: I wonder what these fibre-optic cables are used for One cord. Two identical ends. Looks like female end would be similar to a phone style connection but it is not for phone.

Black cord, two ends identical

A: Looks like and optical SPDIF or Toslink cable.
Like this one (just as an example, not necessarily recommending this product):

A: It's a digital audio cable that uses an optical link: a plastic fiberoptic cable. You can shine a light at one end and see it at the other.
This optical cable system commonly goes by the name of TOSLink (Toshiba Optical Link). TOSLink jacks are found on TVs, audio/video gear, players and some set-top boxes.
The alternative digital audio connection is called SP-DIF (for Sony-Philips Digital Interface), and uses ordinary coax video cable to carry it.
SP-DIF (coax) and TOSLink (optical) work exactly the same, and often appear side-by-side on A/V gear. This is owing to the fact that SP-DIF and TOSLink use the same channel encoding, called AES/EBU or AES3. AES3 defines a digital payload format that is flexible enough to carry a wide range of audio standards, including uncompressed stereo and popular compressed multichannel movie audio formats like Dolby AC3 and DTS.
Note: both formats are considered 'SP-DIF' by some. Industry usage has settled on TOSLink for optical and SP-DIF for the coax version. Conversion between TOSLink optical and SP-DIF coax is only a matter of converting the signal to or from optical. There is no difference in the underlying waveforms or the data payload.
For DVD/Blu-Ray players and set-top boxes, TOSLink and SP-DIF have been largely supplanted by HDMI, which merges audio with video in a multiplexed format so a separate digital path isn't needed for audio.
TVs still provide TOSLink or SP-DIF to connect to home theater systems. This comes up when the TV is the source of the audio, such as from an over-the-air tuner or an app running on the set, but has multichannel audio that needs to be sent to a sound bar or home theater amplifier.
HDMI provides an alternative, called Audio Return Channel or ARC, that does the same thing as TOSLink/SP-DIF. However, ARC isn't universally supported.

A: It's a Toslink cable here's another one.
It connects an SPDIF optical output (the cable conducts light, not an electrical signal!) to an SPDIF input.
It could be used to feed the optical output signal (containing audio) from a CD/DVD/BD player to an audio receiver or TV.


text:
Q: Git pull, fatal: loose object My colleague tried to do a git pull from our master.  He got this error:
$ git pull
fatal: loose object f7630cc30248df1e19bcb40c9de1b60b71cdfce1 (stored in ./objects/f7/630cc30248df1e19bcb40c9de1b60b71cdfce1) is corrupt
fatal: The remote end hung up unexpectedly

Luckily, my repo seems not to be corrupt, and I do have a copy of f7630cc30248df1e19bcb40c9de1b60b71cdfce1.  But I can't figure out what he needs to do with it.  We tried just taking my copy & putting it in his .git/objects/f7/ directory, but the error message stays the same.
Is it supposed to be as simple as just shuffling files around, or do we need to do something else?

A: Does that file exist loose on the master? If so, is it valid or corrupt there? Yes, it should be sufficient just to copy a good version of the file into the objects directory.

A: Check the .git/objects directory for files not readable by you.  I had this problem and that was the issue.  A coworker had cloned my repo while the central server was down, and (I think) a push ended up putting files owned by him but not readable by me.


text:
Q: How to export firebase firestore for my next.js project I'm having trouble understanding how to export firebase's firestore to use on the clientside of my next.js app. I have the following way of instantiating the firebase from my app.
import firebase from 'firebase/app'
import 'firebase/auth' // If you need it
import 'firebase/firestore' // If you need it
import 'firebase/storage' // If you need it
import 'firebase/analytics' // If you need it

const clientCredentials = {
  apiKey: process.env.NEXT_PUBLIC_FIREBASE_PUBLIC_API_KEY,
  authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
  databaseURL: process.env.NEXT_PUBLIC_FIREBASE_DATABASE_URL,
  projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
  storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
  appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
}

// Check that `window` is in scope for the analytics module!
if (typeof window !== 'undefined' && !firebase.apps.length) {
  firebase.initializeApp(clientCredentials)
  // To enable analytics. https://firebase.google.com/docs/analytics/get-started
  if ('measurementId' in clientCredentials) firebase.analytics()
}

export default firebase

My problem is that I thought I could instantiate firestore within the codeblock above and export it to use across my app by importing that instantiated object:
export const db = firebase.firestore();

But when I try to use that in other files I get this error:
{ FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app).
But I have instantiated inside the if (window ...) block. I'm not sure what I'm doing wrong, I can infer that the instantiation within the if block is taking place after export const db... is ran so how do I wait for that?
TIA

A: Try this.
import app from "firebase/app";
import "firebase/auth";

const config = {
    apiKey: process.env.NEXT_PUBLIC_FIREBASE_PUBLIC_API_KEY,
  authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
  databaseURL: process.env.NEXT_PUBLIC_FIREBASE_DATABASE_URL,
  projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
  storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
  appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
};

class Firebase {
    constructor() {
        app.initializeApp(config);
        this.auth = app.auth();

        this.fs = app.firestore(); // example of setting firestore equal to this.fs for later access
    }
}

export default Firebase;

The key parts are import app from "firebase/app"; and the contents of the constructor.
Try it, see if it works. My app uses some of the context API in React but yea that's how it starts. If not leave a comment with what error you get and I'll try to stop back to see how you're doing


text:
Q: Botão JavaScript em Animate CC Boa tarde pessoal,
Estou desenvolvendo uma tela no Animate CC, a tela são 12 botões e quando o usuário "clica" em todos e no final do contador executa a a função de destravar a tela.
Oque esta acontecendo, é que se ele clicara em apenas 1 botão 12 vezes libera a função, estou precisando de fazer com que o botão só soma uma vez quando "clicado".
Obrigado!!
Código:
var contador = 0;

function verificaAvanco() {

  contador = contador + 1;
  if (contador == 12)
    window.parent.postMessage('destravaSlide', '*');
}

this.b1.addEventListener("click", fl_MouseClickHandler.bind(this));

function fl_MouseClickHandler() {
  this.gotoAndStop('f1');
  verificaAvanco();
}

this.b2.addEventListener("click", fl_MouseClickHandler_2.bind(this));

function fl_MouseClickHandler_2() {
  this.gotoAndStop('f2');
  verificaAvanco();
}

this.b3.addEventListener("click", fl_MouseClickHandler_3.bind(this));

function fl_MouseClickHandler_3() {
  this.gotoAndStop('f3');
  verificaAvanco();
}

this.b4.addEventListener("click", fl_MouseClickHandler_4.bind(this));

function fl_MouseClickHandler_4() {
  this.gotoAndStop('f4');
  verificaAvanco();
}

this.b5.addEventListener("click", fl_MouseClickHandler_5.bind(this));

function fl_MouseClickHandler_5() {
  this.gotoAndStop('f5');
  verificaAvanco();
}

this.b6.addEventListener("click", fl_MouseClickHandler_6.bind(this));

function fl_MouseClickHandler_6() {
  this.gotoAndStop('f6');
  verificaAvanco();
}

this.b7.addEventListener("click", fl_MouseClickHandler_7.bind(this));

function fl_MouseClickHandler_7() {
  this.gotoAndStop('f7');
  verificaAvanco();
}

this.b8.addEventListener("click", fl_MouseClickHandler_8.bind(this));

function fl_MouseClickHandler_8() {
  this.gotoAndStop('f8');
  verificaAvanco();
}

this.b9.addEventListener("click", fl_MouseClickHandler_9.bind(this));

function fl_MouseClickHandler_9() {
  this.gotoAndStop('f9');
  verificaAvanco();
}

this.b10.addEventListener("click", fl_MouseClickHandler_10.bind(this));

function fl_MouseClickHandler_10() {
  this.gotoAndStop('f10');
  verificaAvanco();
}

this.b11.addEventListener("click", fl_MouseClickHandler_11.bind(this));

function fl_MouseClickHandler_11() {
  this.gotoAndStop('f11');
  verificaAvanco();
}

this.b12.addEventListener("click", fl_MouseClickHandler_12.bind(this));

function fl_MouseClickHandler_12() {
  this.gotoAndStop('f12');
  verificaAvanco();
}

A: Fala Amigo,
Acredito que pode fazer a validação de forma diferente.
Atualmente sua validação está sendo feita através do contator, com isso você não tem controle do botão clicado, certo?
O que você pode fazer, é criar uma VAR do tipo Array com 12 posições e a cada botão clicado você adiciona o valor na posição respectiva.
var nome_Array = new Array(12);

function verificaAvanco() {

  if (nome_Array.toString() == '1,1,1,1,1,1,1,1,1,1,1,1'){

    window.parent.postMessage('destravaSlide', '*');
}

this.b1.addEventListener("click", fl_MouseClickHandler.bind(this));

function fl_MouseClickHandler() {

  btn = Number(this.name.slice(1,this.name.length));
  nome_Array[btn-1]= '1';

  this.gotoAndStop('f1');

  verificaAvanco();

}

Vai ficar um pouco Manual, mas supre o que você precisa.
A outras formas de se fazer, mas com base no seu código , creio que lhe ajude.


text:
Q: DynamoDB input broken item if putting items too fast? I'm facing a weird phenomenal when putting items to DynamoDB.
It seems like if putting items too fast, DynamoDB can't put the whole data to the table(kinda like a broken data, it has partial attributes but with some weird values)?
I'm using the AWS JavaScript SDK to putting items, no errors shown up, everything seemed to work fine, but once I checked the data from web console, some of the inserted data was broken. Is this is related to write capacity units? (but no errors tell me it's caused by the write capacity units..) I could confirm the spike of my write capacity units was about 60/min, the setting is "on-demand".
I tried to slow down the putting speed with one second interval and with the exactly same data, the data could be inserted correctly...
Anyone knows why and how to fix this..?

A: The answer is no: If DynamoDB decides to throttle your requests because you exceeded your provisioned capacity or exceed their own hardware's capacity or whatever - it will refuse to do whole requests, or in the case of BatchWriteItems do some of the writes and not do others (and it will tell you which it did and which it didn't). DynamoDB will never write part of a request or corrupt parts of one attribute.
If you are seeing that, the most likely culprit is a bug in your own code that does the write. Maybe your own code is not thread-safe, so if your code is trying to prepare two items for writing concurrently, the code doing this preperation has a data race and results in a corrupt item to be written. Obviously, it is also possible that DynamoDB has a bug causing this, but it can't be as simple a bug as "writing more than 60 items a minute causes corruption" - if this were the case, everyone would have encountered this bug...


text:
Q: function Prototype in jQuery I have two files - prototype.js and jquery.js
In prototype.js have:
function check(www) {
//....
}

in jquery.js have:
jQuery('#aaa').click(function() {
    var bbb = $this.val();
        //-----
         check(www);
        //--------

    });

How can I correctly use check?

A: If it were really declared as shown, you could just call it as you've shown. It doesn't matter that it's defined in one file and then used in another; once the files are loaded, they all exist in the same execution environment. But I don't recall Prototype having a check function at global scope.
Note that if you're using Prototype and jQuery on the same page, you have to tell jQuery to not use the $ symbol:
jQuery.noConflict();

Then you can just intersperse use of Prototype and jQuery all you want. Example:
<script src='prototype.js'></script>
<script src='jquery.js'></script>
<script>
jQuery.noConflict();
jQuery(function() {
    // Get a jQuery instance containing elements with class "foo"
    var foo = jQuery(".foo");

    // Retrieve the first matching element, use Prototype's `$()` to extend it
    // (automatic on some browsers, not on IE), then call Prototype's `update` function.
    $(foo[0]).update("Hi there");
});
</script>

As you can see, you can intersperse the two if you like. I'm not saying it's a good idea, but sometimes it's necessary, particularly when you're incrementally transitioning a page or site from one library to another.
If you're used to writing jQuery code with the $ symbol, you can still do that for entire sections of the code if you like. Here's a fairly common idiom:
(function($) {
    // Within this function, $ = jQuery
    ....
})(jQuery);

That shadows the $ symbol within that function (by making it an argument), and passes jQuery in for that argument. Or you can be more explicit:
(function() {
    var $ = jQuery; // Within this function, $ = jQuery
    ....
})();

That does much the same thing, but more obviously.


text:
Q: Why is zipped faster than zip in Scala? I have written some Scala code to perform an element-wise operation on a collection. Here I defined two methods that perform the same task. One method uses zip and the other uses zipped.
def ES (arr :Array[Double], arr1 :Array[Double]) :Array[Double] = arr.zip(arr1).map(x => x._1 + x._2)

def ES1(arr :Array[Double], arr1 :Array[Double]) :Array[Double] = (arr,arr1).zipped.map((x,y) => x + y)

To compare these two methods in terms of speed, I wrote the following code:
def fun (arr : Array[Double] , arr1 : Array[Double] , f :(Array[Double],Array[Double]) => Array[Double] , itr : Int) ={
  val t0 = System.nanoTime()
  for (i <- 1 to itr) {
       f(arr,arr1)
       }
  val t1 = System.nanoTime()
  println("Total Time Consumed:" + ((t1 - t0).toDouble / 1000000000).toDouble + "Seconds")
}

I call the fun method and pass ES and ES1 as below:
fun(Array.fill(10000)(math.random), Array.fill(10000)(math.random), ES , 100000)
fun(Array.fill(10000)(math.random), Array.fill(10000)(math.random), ES1, 100000)

The results show that the method named ES1 that uses zipped is faster than method ES that uses zip.
Based on these observations, I have two questions.
Why is zipped faster than zip?
Is there any even faster way to do element-wise operations on a collection in Scala?

A: Consider lazyZip
(as lazyZip bs) map { case (a, b) => a + b }

instead of zip
(as zip bs) map { case (a, b) => a + b }

Scala 2.13 added lazyZip in favour of .zipped

Together with .zip on views, this replaces .zipped (now
  deprecated). (scala/collection-strawman#223)

zipped (and hence lazyZip) is faster than zip because, as explained by Tim and Mike Allen, zip followed by map will result in two separate transformations due to strictness, whilst zipped followed by map will result in a single transformation executed in one go due to laziness.
zipped gives Tuple2Zipped, and analysing Tuple2Zipped.map,
class Tuple2Zipped[...](val colls: (It1, It2)) extends ... {
  private def coll1 = colls._1
  private def coll2 = colls._2

  def map[...](f: (El1, El2) => B)(...) = {
    val b = bf.newBuilder(coll1)
    ...
    val elems1 = coll1.iterator
    val elems2 = coll2.iterator

    while (elems1.hasNext && elems2.hasNext) {
      b += f(elems1.next(), elems2.next())
    }

    b.result()
  }

we see the two collections coll1 and coll2 are iterated over and on each iteration the function f passed to map is applied along the way
b += f(elems1.next(), elems2.next())

without having to allocate and transform intermediary structures.

Applying Travis' benchmarking method, here is a comparison between new lazyZip and deprecated zipped where
@State(Scope.Benchmark)
@BenchmarkMode(Array(Mode.Throughput))
class ZippedBench {
  import scala.collection.mutable._
  val as = ArraySeq.fill(10000)(math.random)
  val bs = ArraySeq.fill(10000)(math.random)

  def lazyZip(as: ArraySeq[Double], bs: ArraySeq[Double]): ArraySeq[Double] =
    as.lazyZip(bs).map{ case (a, b) => a + b }

  def zipped(as: ArraySeq[Double], bs: ArraySeq[Double]): ArraySeq[Double] =
    (as, bs).zipped.map { case (a, b) => a + b }

  def lazyZipJavaArray(as: Array[Double], bs: Array[Double]): Array[Double] =
    as.lazyZip(bs).map{ case (a, b) => a + b }

  @Benchmark def withZipped: ArraySeq[Double] = zipped(as, bs)
  @Benchmark def withLazyZip: ArraySeq[Double] = lazyZip(as, bs)
  @Benchmark def withLazyZipJavaArray: ArraySeq[Double] = lazyZipJavaArray(as.toArray, bs.toArray)
}

gives
[info] Benchmark                          Mode  Cnt      Score      Error  Units
[info] ZippedBench.withZipped            thrpt   20  20197.344 ± 1282.414  ops/s
[info] ZippedBench.withLazyZip           thrpt   20  25468.458 ± 2720.860  ops/s
[info] ZippedBench.withLazyZipJavaArray  thrpt   20   5215.621 ±  233.270  ops/s

lazyZip seems to perform a bit better than zipped on ArraySeq. Interestingly, notice significantly degraded performance when using lazyZip on Array.

A: None of the other answers mention the primary reason for the difference in speed, which is that the zipped version avoids 10,000 tuple allocations. As a couple of the other answers do note, the zip version involves an intermediate array, while the zipped version doesn't, but allocating an array for 10,000 elements isn't what makes the zip version so much worse—it's the 10,000 short-lived tuples that are being put into that array. These are represented by objects on the JVM, so you're doing a bunch of object allocations for things that you're immediately going to throw away.
The rest of this answer just goes into a little more detail about how you can confirm this.
Better benchmarking
You really want to be using a framework like jmh to do any kind of benchmarking responsibly on the JVM, and even then the responsibly part is hard, although setting up jmh itself isn't too bad. If you have a project/plugins.sbt like this:
addSbtPlugin("pl.project13.scala" % "sbt-jmh" % "0.3.7")

And a build.sbt like this (I'm using 2.11.8 since you mention that's what you're using):
scalaVersion := "2.11.8"

enablePlugins(JmhPlugin)

Then you can write your benchmark like this:
package zipped_bench

import org.openjdk.jmh.annotations._

@State(Scope.Benchmark)
@BenchmarkMode(Array(Mode.Throughput))
class ZippedBench {
  val arr1 = Array.fill(10000)(math.random)
  val arr2 = Array.fill(10000)(math.random)

  def ES(arr: Array[Double], arr1: Array[Double]): Array[Double] =
    arr.zip(arr1).map(x => x._1 + x._2)

  def ES1(arr: Array[Double], arr1: Array[Double]): Array[Double] =
    (arr, arr1).zipped.map((x, y) => x + y)

  @Benchmark def withZip: Array[Double] = ES(arr1, arr2)
  @Benchmark def withZipped: Array[Double] = ES1(arr1, arr2)
}

And run it with sbt "jmh:run -i 10 -wi 10 -f 2 -t 1 zipped_bench.ZippedBench":
Benchmark                Mode  Cnt     Score    Error  Units
ZippedBench.withZip     thrpt   20  4902.519 ± 41.733  ops/s
ZippedBench.withZipped  thrpt   20  8736.251 ± 36.730  ops/s

Which shows that the zipped version gets about 80% more throughput, which is probably more or less the same as your measurements.
Measuring allocations
You can also ask jmh to measure allocations with -prof gc:
Benchmark                                                 Mode  Cnt        Score       Error   Units
ZippedBench.withZip                                      thrpt    5     4894.197 ±   119.519   ops/s
ZippedBench.withZip:·gc.alloc.rate                       thrpt    5     4801.158 ±   117.157  MB/sec
ZippedBench.withZip:·gc.alloc.rate.norm                  thrpt    5  1080120.009 ±     0.001    B/op
ZippedBench.withZip:·gc.churn.PS_Eden_Space              thrpt    5     4808.028 ±    87.804  MB/sec
ZippedBench.withZip:·gc.churn.PS_Eden_Space.norm         thrpt    5  1081677.156 ± 12639.416    B/op
ZippedBench.withZip:·gc.churn.PS_Survivor_Space          thrpt    5        2.129 ±     0.794  MB/sec
ZippedBench.withZip:·gc.churn.PS_Survivor_Space.norm     thrpt    5      479.009 ±   179.575    B/op
ZippedBench.withZip:·gc.count                            thrpt    5      714.000              counts
ZippedBench.withZip:·gc.time                             thrpt    5      476.000                  ms
ZippedBench.withZipped                                   thrpt    5    11248.964 ±    43.728   ops/s
ZippedBench.withZipped:·gc.alloc.rate                    thrpt    5     3270.856 ±    12.729  MB/sec
ZippedBench.withZipped:·gc.alloc.rate.norm               thrpt    5   320152.004 ±     0.001    B/op
ZippedBench.withZipped:·gc.churn.PS_Eden_Space           thrpt    5     3277.158 ±    32.327  MB/sec
ZippedBench.withZipped:·gc.churn.PS_Eden_Space.norm      thrpt    5   320769.044 ±  3216.092    B/op
ZippedBench.withZipped:·gc.churn.PS_Survivor_Space       thrpt    5        0.360 ±     0.166  MB/sec
ZippedBench.withZipped:·gc.churn.PS_Survivor_Space.norm  thrpt    5       35.245 ±    16.365    B/op
ZippedBench.withZipped:·gc.count                         thrpt    5      863.000              counts
ZippedBench.withZipped:·gc.time                          thrpt    5      447.000                  ms

…where gc.alloc.rate.norm is probably the most interesting part, showing that the zip version is allocating over three times as much as zipped.
Imperative implementations
If I knew that this method was going to be called in extremely performance-sensitive contexts, I'd probably implement it like this:
  def ES3(arr: Array[Double], arr1: Array[Double]): Array[Double] = {
    val minSize = math.min(arr.length, arr1.length)
    val newArr = new Array[Double](minSize)
    var i = 0
    while (i < minSize) {
      newArr(i) = arr(i) + arr1(i)
      i += 1
    }
    newArr
  }

Note that unlike the optimized version in one of the other answers, this uses while instead of a for since the for will still desugar into Scala collections operations. We can compare this implementation (withWhile), the other answer's optimized (but not in-place) implementation (withFor), and the two original implementations:
Benchmark                Mode  Cnt       Score      Error  Units
ZippedBench.withFor     thrpt   20  118426.044 ± 2173.310  ops/s
ZippedBench.withWhile   thrpt   20  119834.409 ±  527.589  ops/s
ZippedBench.withZip     thrpt   20    4886.624 ±   75.567  ops/s
ZippedBench.withZipped  thrpt   20    9961.668 ± 1104.937  ops/s

That's a really huge difference between the imperative and functional versions, and all of these method signatures are exactly identical and the implementations have the same semantics. It's not like the imperative implementations are using global state, etc. While the zip and zipped versions are more readable, I personally don't think there's any sense in which the imperative versions are against the "spirit of Scala", and I wouldn't hesitate to use them myself.
With tabulate
Update: I added a tabulate implementation to the benchmark based on a comment in another answer:
def ES4(arr: Array[Double], arr1: Array[Double]): Array[Double] = {
  val minSize = math.min(arr.length, arr1.length)
  Array.tabulate(minSize)(i => arr(i) + arr1(i))
}

It's much faster than the zip versions, although still much slower than the imperative ones:
Benchmark                  Mode  Cnt      Score     Error  Units
ZippedBench.withTabulate  thrpt   20  32326.051 ± 535.677  ops/s
ZippedBench.withZip       thrpt   20   4902.027 ±  47.931  ops/s

This is what I'd expect, since there's nothing inherently expensive about calling a function, and because accessing array elements by index is very cheap.

A: You should always be cautious with performance measurement because of JIT compilation, but a likely reason is that zipped is lazy and extracts elements from the original Array vaules during the map call, whereas zip creates a new Array object and then calls map on the new object.

A: To answer your second question:

Is there any more faster way to do element wise operation on a collection in Scala?

The sad truth is that despite it's conciseness, improved productivity, and resilience to bugs, is that functional languages aren't necessarily the most performant. In the OP's example, using higher order functions to define a projection to be executed against collections has overhead, and the tight loop amplifies this. As others have pointed out, additional storage allocation for intermediate and final results will also have overhead.
If performance is critical, although by no means universal, in cases like yours you can unwind concise functional code back into imperative equivalents in order to regain more direct control over memory usage and eliminating function call overheads.
In your specific example, the zipped sums can be performed imperatively by pre-allocating a fixed, mutable array of correct size (since zip stops when one of the collections runs out of elements), and then adding elements at the appropriate index together (since accessing array elements by ordinal index is a very fast operation).
By example, adding a third function, ES3 to your test suite:
def ES3(arr :Array[Double], arr1 :Array[Double]) :Array[Double] = {
   val minSize = math.min(arr.length, arr1.length)
   val array = Array.ofDim[Double](minSize)
   for (i <- 0 to minSize - 1) {
     array(i) = arr(i) + arr1(i)
   }
  array
}

On my i7 I get the following response times:
OP ES Total Time Consumed:23.3747857Seconds
OP ES1 Total Time Consumed:11.7506995Seconds
--
ES3 Total Time Consumed:1.0255231Seconds

Even more heineous would be to do direct in-place mutation of the shorter of the two arrays, which would obviously corrupt the contents of this shorter array, so should only be implemented if the original arrays wouldn't be needed for further work by the caller:
def ES4(arr :Array[Double], arr1 :Array[Double]) :Array[Double] = {
   val minSize = math.min(arr.length, arr1.length)
   val array = if (arr.length < arr1.length) arr else arr1
   for (i <- 0 to minSize - 1) {
      array(i) = arr(i) + arr1(i)
   }
  array
}

Total Time Consumed:0.3542098Seconds

But obviously, direct mutation of arrays elements passed as parameters isn't in the spirit of Scala - this code smells of side effects.
To be honest, if you require this level of performance optimization in tight loops, you're likely better off writing these kinds of algorithms in Rust, Go or C.


text:
Q: ofy() appengine Date search query I want to search a list of employee between two dates ie. 1 jan 2014 to 31 Dec 2014 using GAE ofy(objectify) for a branch.How do I do that?
ulist=ofy().load().type(Employee.class).filter("branch", branch).filter("date >=", fromdate).filter("date <=", toDate).list();

There are 2 fields
-Branch is auto generated field.
-For date I have taken 2 Datebox, fromDate and toDate and using those 2 date I have to query on date field.
Above query written is not working & not giving results when searched between date. However if same date is entered in both from date & todate then its working.
Is there any isssue with my logic or is there any other method which I can use to find out employees of branch joined between two dates?

A: You will need to specify a custom index to support this query as it combines multiple filters on different properties.
As per the documentation:

Other forms of query require their indexes to be specified in the index configuration file, including:
...
Queries with one or more inequality filters on a property and one or more equality filters on other properties
...

Your query has an equality filter (on branch) with two inequality (on date) filters.
The documentation tells you all you need to know about configuring your custom indexes.


text:
Q: Metric tensor and einstein's notations .
Here , $\Omega \subset \mathbb R^n$.
Can someone explain it to me what $F$ is ?
I also don't understand how we can get the unit outer normal in the second para .
Please kindly help me to understand as the text i am referring doesn't say anything regarding what $F$ is .
Thanks

A: I cannot see your whole paragraph, so I hope what I write here is correct.
$\Omega$ is an open set in $\mathbb R^n$ with $C^{2, \alpha}$ boundary, that is, $\partial \Omega $ is a $C^{2, \alpha}$ submanifolds of $\mathbb R^n$. So for any point $p \in \partial \Omega$, there is an open set $U_p \subset \mathbb R^n$ so that
$$\Omega \cap U_p = \{(x_1, \cdots, x_{n-1}, F(x_1, \cdots, x_{n-1}) \in \mathbb R^n: (x_1, \cdots, x_{n-1}) \in V_p \}$$
for some open set $V_p \subset \mathbb R^{n-1}$, and $F$ is in $C^{2, \alpha}(V_p)$. In your case, this $\mathbb R^{n-1}$ is identified with the tangent plane of $\partial \Omega$ at $p$. (That is, $F$ is a local defining function of $\partial \Omega$).
To pick an example, let $\Omega = \{||x|| <1\}$. Then $\partial \Omega = \{||x||=1\}$ is the unit sphere in $\mathbb R^n$ (Obviously a $C^{2, \alpha}$ submanifold). Let $p = (0,\cdots, 0, 1) \in \partial \Omega$. Then choosing
$$U_p = \{ (x_1, \cdots, x_n): |x_1|^2 + \cdots + |x_{n-1}|^2 < 1/2, 0< x_n< 2\}$$
(A cylindraicl open set) and
$$V_p = \{ (x_1, \cdots, x_{n-1}): |x_1|^2 + \cdots + |x_{n-1}|^2 < 1/2\} \subset \mathbb R^{n-1}.$$
Then in this case
$$\partial \Omega \cap U_p = \{(x_1, \cdots, x_{n-1}, F(x_1, \cdots, x_{n-1}) \in \mathbb R^n: (x_1, \cdots, x_{n-1}) \in V_p \},$$
where $F(x_1, \cdots, x_{n-1}) = \sqrt{1- |x_1|^2 - \cdots - |x_{n-1}|^2}$.
For the normal vector, as $\partial \Omega$ is locally parametrized by $F$, then for any $i = 1, \cdots n-1$,
$$(0, \cdots, 0, 1, 0, \cdots , 0, \frac{\partial F}{\partial x_i})$$
is in the tangent space of $\partial \Omega$ at $p$ (The "1" is at the $i$-th component). So one can check directly that $\tilde\nu$ given in your question are perpendicular to all the above tangent vectors and have norm one.


text:
Q: Ubuntu download and install on VirtualBox Downloaded ubuntu  16.04.2-desktop-amd64 on a Windows 10 64 bit intel i7.
Why does iso filename say amd ?
Tried running this iso on virtualBox and got message as Kernel version is not correct. Which version do i need to download?

A: amd64 is all 64-bit XX86 class processors regerdless of manufacturer.
vitrualbox is 32 bit. get the 32bit version. i386 will be at then end of the image name


text:
Q: Sensor.TYPE_LINEAR_ACCELERATION not recognized I'm creating an Android project with Eclipse and I'm getting that error.
I'm using Gingerbread 2.3.3 (Google API Level 10).
What could be missing?
Thanks in advance. Guillermo.

A: Did you import android.hardware.Sensor ?

A: The problem was an import. I was using the

import org.openintents.sensorsimulator.hardware.Sensor;
  import org.openintents.sensorsimulator.hardware.SensorEvent;
  import org.openintents.sensorsimulator.hardware.SensorEventListener;
  import org.openintents.sensorsimulator.hardware.SensorManagerSimulator;

from the openintents project which needed an import that was conflicting to use the Sensor class and then I couldn't use the new Sensors.
Thanks. Guillermo.


text:
Q: Mostrar consulta de 2 tablas diferentes en un dataTable de Primefaces Trabajo en una aplicación con JSF , Primefaces , MySQL y la persistencia con MyBatis.
Necesito recuperar la información de 2 tablas de una BD(Toda la información de una y toda o parte de la otra) y mostrarlas en un mismo p:dataTable.

Nota: Para cada tabla ya está  funcionando mostrar los datos en su propio dataTable.
Consultando encontré que puedo hacerlo con la etiqueta "association"(MyBatis) manejando join en un resulmap como lo muestro más adelante, pero no encuentro como pasar estos datos a un dataTable de primefaces en JSF.

La pregunta es: ¿que debo agregar a la pagina xhtml donde tengo el p: dataTable  o a la clase pojo, y/o  a la clase del bean, para visualizar los datos de las 2 tablas?.
Esto es lo que tengo en la BD :

- Estudiantes (Tiene PRIMARY KEY (idEstudiante)
-Matriculas  (Tiene  PRIMARY KEY (idMatricula)
         FOREIGN KEY (idEstudiante)
-Así es como en un DataTable recupero los datos de la tabla matriculas(algo similar funciona para  la tabla Estudiantes y deberá ser con algunos cambios pienso yo, para  la asociación de las 2 tablas)
<p:dataTable value="#{matriculasbean.matricula}" var="aux"
paginator="true" paginatorPosition="top" editable="true"
style="margin-bottom:20px" scrollable="true" scrollWidth="100%"
rows="5" rowsPerPageTemplate="5,10,15">

<p:column headerText="Id Estudiante">
    <h:outputText value="#{aux.idEstudiante}" />
</p:column>
<p:column headerText="Grado">
    <h:outputText value="#{aux.grado}" />
</p:column>
<p:column headerText="Curso">
    <h:outputText value="#{aux.nombreCurso}" />
</p:column>

-Pojo para Matriculas:
   public class Matriculas {
        private int idMatricula;
        private int idEstudiante;
        private String grado;
        private String nombreCurso;
        private Date fechaMatricula;
        private Double costoMatricula;

        public Matriculas() {

        }

    // Getters y Setters

-Pojo para Estudiantes:
 public class Estudiantes {

        private int idEstudiante;
        private String nombreEstudiante;
        private String primerApellidoE;
        private String segundoApellidoE;
        private String tipoDocumento;

    public Estudiantes() {

    }
    // Getters y Setters

-La clase java beans desde donde llamo el mapper para la consulta de las 2 tablas:
@ManagedBean
@SessionScoped
public class Matriculasbean {

    private Matriculas matriculas;

  public Matriculasbean() {

        matriculas= new Matriculas();
    }

  public List<Matriculas> getMatriEstuNombre(){
    System.out.println("está en getMatriEstuNombre");
    List<Matriculas> lista = null;

    SqlSession session = new MyUtil().getSession();

    if (session != null) {
        try { lista = session.selectList("Coleg.selectMatriculasestu");

    } finally {
        session.close();                }

    }else {
        System.out.println("ERROR");
        }
        return lista;
    }
}

Esto es lo que tengo de acuerdo a lo que he investigado, utilizando Mapper y resulmap con MyBatis en una relación uno a uno en el fichero xml de mapeo  para hacer el join entre las 2 tablas:
-El Select para la consulta:
  <select id="selectMatriculasestu" parameterType="int"
    resultMap="ResulMatricula">
           select
                    M.idEstudiante as idEstudiante,
                    M.idMatricula as idMatricula,
                    M.grado as grado,
                    M.nombreCurso as nombreCurso,
                    M.fechaMatricula as fechaMatricula,
                    M.costoMatricula as costoMatricula,
                    E.nombreEstudiante as nombreEstudiante,
                    E.primerApellidoE as  primerApellidoE,
                    E.segundoApellidoE as segundoApellidoE
                    E.tipoDocumento as tipoDocumento
    from Matriculas M left outer join Estudiantes E on M.idEstudiante =
    E.idEstudiante where M.idEstudiante = #{idEstudiante}
    </select>

-Mapeo:
<resultMap  id="ResulMatricula" type="Matriculas">
   <id column="idEstudiante" property="idEstudiante" javaType="int"/>
   <result column="idMatricula" property="idMatricula" javaType="int"/>
   <result column="grado" property="grado" javaType="string"/>
   <result column="nombreCurso" property="nombreCurso" javaType="string"/>
   <result column="fechaMatricula" property="fechaMatricula" javaType="date"/>
   <result column="costoMatricula" property="costoMatricula" javaType="double"/>

   <association property="Estudiantes" javaType="Estudiantes" resultMap="ResulEstudiantes" />
</resultMap>

<resultMap  id="ResulEstudiantes" type="Estudiantes">
   <id column="idEstudiante" property="idEstudiante" javaType="int"/>
     <result column="nombreEstudiante" property="nombreEstudiante" javaType="string"/>
     <result column="primerApellidoE" property="primerApellidoE" javaType="string"/>
     <result column="segundoApellidoE" property="segundoApellidoE" javaType="string"/>
     <result column="tipoDocumento" property="tipoDocumento" javaType="int"/>

    </resultMap>

A: Arenas:
Nota que estás trabajando con un ORM, por lo que deberías ser capaz de pedirle a cada entity el objeto que represena la clase referenciada o la lista de objetos que lo referencian a él. Algo como esto
    Matriculas matricula = findMatricula('1') // asumiendo que tienes un método que
    te devuelve una matríclula según su id.
    Estudiante estudiante = matricula.getEstudianteFK();

    // También es válido el caso contrario
    List<Matricula> list = estudiante.getMatriculas(); //esto debería devolver  la
    lista de matrículas del estudiante

Luego en un datatable podrías tener algo como esto, aprobechando que matrícula tiene el id del estudiante:
<p:dataTable value="#{matriculasbean.matricula}" var="aux"
paginator="true" paginatorPosition="top" editable="true"
style="margin-bottom:20px" scrollable="true" scrollWidth="100%"
rows="5" rowsPerPageTemplate="5,10,15">

<p:column headerText="Id Estudiante">
<h:outputText value="#{aux.idEstudiante}" />
</p:column>
<p:column headerText="Grado">
<h:outputText value="#{aux.grado}" />
</p:column>
<p:column headerText="Curso">
<h:outputText value="#{aux.nombreCurso}" />
</p:column>

<p:column headerText="Un dato del estudiante asociado a la matrícula aux">
<h:outputText value="#{aux.estudianteFK.atributoDelEstudiante}" />
</p:column>

<p:column headerText="Otro dato del estudiante asociado a la matrícula aux">
<h:outputText value="#{aux.estudianteFK.otroAtributoDelEstudiante}" />
</p:column>


text:
Q: Windows 8 - WOL works from power off but not from hibernation I followed the advice here to shut off fast boot in order to wake-on-LAN my Windows 8 machine when powered down. This worked for me which shows that the packet is being forwarded properly from my router and the network card of the computer is receiving that packet. However, I am not able to power on the computer if it is set to hibernate. This leads me to believe it is an issue with Windows. What could be going on here?

A: Quoting this page:

*

*On the target computer in Device Manager or in the network settings
select the network card.

*Click on: Properties

*Click on the configure button of the network card.

*Select the tab: Power management

*Set a check mark at: Allow this device to bring the computer out of
standby

*Click on: OK

*Continue to close all property pages.

It seems that when Windows hibernates, the power management settings for Windows prevent it from completely turning loose of the NIC and letting BIOS manage the device for WOL purposes. Hope this helps.


text:
Q: Printing a Password Generator So,  I am trying to make a password generator that I can use for furure Applications etc.
So far i have gotten what characters I want to use and have made a SecureRandom to put them in a certain order.
How exactly should I lay this out. Any suggestions on how I should make it print the characters out, and how should I go about printing the 10 character password?
here is the code so far :
import java.security.SecureRandom;
import java.util.Random;

public class Generator {

public static void main(String [] args){

    String[] symbols = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
    int length = 10;
    Random random = new SecureRandom();
    StringBuilder sb = new StringBuilder(length);
    for (int i = 0; i < length; i++) {
        int indexRandom = random.nextInt( symbols.length );
        sb.append( symbols[indexRandom] );
    }
    String password = sb.toString();

}

}

basically what I am asking is how would I get this to print out the 10 character password that is randomly generated.

A: Just add  System.out.println(password); to the code. It worked for me.
Btw, not sure why its not working in your console. It worked for me with Eclipse.

A: You can make simple UI on Swing with label and button "Generate". Also it will let you make your generation mechanism configurable. Also use
new Random(Calendar.getInstance().getTimeInMillis())

instead. Otherwise you will loose the availability to control the seed of randomness.


text:
Q: Proving whether or not a function is regulated Let $\phi : [0,1] \rightarrow \mathbb R $ be a step function and $f: [0,1] \rightarrow \mathbb R $ be defined $f(0)=0$, $f(x)=sin(1/x)$, $x \in (0,1]$. We want to prove that f is not regulated.
To start I know to choose $\epsilon$ = $1$ but I'm not sure where to go from here without picking a specific step function to start from but that is obviously the wrong way to go about it.
Any help would be much appreciated.

A: The idea of this proof is to note that, since $\phi$ is a step function, in particular it is constant on an interval $[0,a]$ for some $a<1$.
However, the function $f$ will reach both $-1$ and $1$ in $(0,a]$ so there is $x\in[0,a]\subseteq[0,1]$ s.t. $\vert f(x)-\phi(x)\vert\geq 1$. This shows that, for any sequence of step functions $\phi_n$, $\Vert \phi_n-f\Vert_\infty\geq1$, which implies $f$ is not regulated


text:
Q: How can I read a Google Spreadsheets using jquery and php I have some information in Google Spreadsheets as a single sheet. Is there any way by which I can read this information from html by jquery and php. my sheet link and my username suresh@rangde.org password Pattu&1991

A: You need to use Google Spreadsheet API for PHP
OR
See Simple example of retrieving JSON feeds from Spreadsheets Data API


text:
Q: Spring AOP Exception Handling I'm trying to check if some database hosts are alive. ConfigReader class parses a xml file and gets the list of some database hosts.
I want to see logs like this if some hosts are not available:
running check for host:dbhost1
Some Exception is ...
running check for host:dbhost2
host is alive

and so on.
But I see this exception if the host is not alive. The application exits instead of logging and throwing the exception.
#### running check for host:dbhost1
Exception in thread "main" java.sql.SQLException: Cannot create PoolableConnectionFactory (I/O-Fehler: The Network Adapter could not establish the connection)
    at org.apache.commons.dbcp2.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:2291)
    at org.apache.commons.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:2038)
    at org.apache.commons.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:1533)
    at com.csinfra.jdbmon.app.CheckDatabase.runCheckGroup(CheckDatabase.java:108)

Here are the classes:
@Component
public class ScheduleCheck {
    public ConfigReader configReader;
    public CheckDatabase checkDatabase;

    public void runHostCheck() throws Exception {
        configReader.readConfig();
        checkDatabase.setConfigReader(configReader);
        for(Host host:configReader.getHostMap().values()){
                System.out.println("#### running check for host:"+host.getId());
                checkDatabase.runCheckGroup(host, getCheckFromCheckGroup(host));
        }
    }
}

@Component
public class CheckDatabase {
    public void runCheckGroup(Host host) throws Exception{
            createConnections(host.getJdbcurl(), host.getJdbcuser(), host.getJdbcpassword(), host.getDriverclassname());
            Connection connection_single = jdbcPool.getConnection();
            if(connection_single!=null){
                System.out.println("host is alive");
            }
    }

    public void createConnections(String url, String username, String password, String driverClassname) throws Exception{
            jdbcPool = new BasicDataSource();
            jdbcPool.setDriverClassName(driverClassname);
            jdbcPool.setUsername(username);
            jdbcPool.setUrl(url);
            jdbcPool.setPassword(password);
            jdbcPool.setInitialSize(2);
            jdbcPool.setCacheState(false);
            jdbcPool.setMaxTotal(2);
            jdbcPool.setMaxWaitMillis(6000);
            jdbcPool.setMaxIdle(2);
            jdbcPool.setDefaultReadOnly(true);
    }
}

@Configurable
@Aspect
@Component
public class AopMethodLogger {

    private static final Logger LOGGER = RootLogger.getLogger(AopMethodLogger.class);

    @AfterThrowing(pointcut = "execution(* com.csinfra.app..*.*(..))", throwing = "exception")
    public void logAfterThrowing(JoinPoint joinPoint, Throwable exception)  throws Throwable {
        LOGGER.debug("Some Exception is "+exception.getLocalizedMessage());
        throw exception;
    }
}

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">

    <aop:aspectj-autoproxy proxy-target-class="true" />
    <context:component-scan base-package="com.csinfra.app />

    <bean id="aopMethod" class="com.csinfra.app.log.AopMethodLogger" />

    <bean id="scheduleCheck" class="com.csinfra.app.ScheduleCheck">
        <property name="configReader" ref="configReader" />
        <property name="checkDatabase" ref="checkDatabase" />
    </bean>

    <bean id="checkDatabase" class="com.csinfra.app.CheckDatabase">
    </bean>

</beans>

A: CheckDatabase.runCheckGroup throws an exception and it is not handled, thats why the application exits.
Surround your call to runCheckGroup with try/catch and log the exception :
try{
  checkDatabase.runCheckGroup(host, getCheckFromCheckGroup(host));
 } catch(Exception e){
  System.out.println("Exception occured :"+e);
}

The number of connections to the database is limited, so creating a new connection, just to check the database is alive seems rather expensive.
It may be better to let spring inject all available datasources :
@Autowire
List<DataSource>dataSources;

This has also the advantage to automatically check all configured datasources, without additional configuration.
And than iterate over those, for each doing something like
new JdbcTemplate(dataSource).queryForInt("SELECT 1")

to check its alive.


text:
Q: npm run scripts runs infinite amounts of time I have scss files which I want to convert to css then run autoprefixer, then minify the whole thing.
I came to this code:
"devDependencies": {
    "autoprefixer": "^9.7.2",
    "cssnano": "^4.1.10",
    "node-sass": "^4.13.0",
    "npm-run-all": "^4.1.5",
    "postcss": "^7.0.23",
    "postcss-cli": "^6.1.3",
    "watch": "^1.0.2"
  },
  "scripts": {
    "scss": "node-sass -o www/css src/scss",
    "prefix": "postcss --use autoprefixer -b 'last 2 versions' < www/css/websiteStyles.css | postcss --use cssnano > www/css/websiteStyles.min.css",
    "dev": "npm-run-all scss prefix",
    "watch" : "watch 'npm run dev'"
  },

When I run npm run watch the script runs infinitely. I don't change anything but the script runs and runs and then runs ageain. What did I do wrong?


text:
Q: R replace all instances of a pattern from a list A with instances from list C by matching A with list B I have three lists of country names.
orig_list <- c("MURICA","uSa","Ger","Gerrmany",...) #[LONG, about 15000 entries]
unique_spellings <- c("MURICA","uSa","Ger","Gerrmany") #[600 entries]
norm_spellings <- c("USA","USA","Germany","Germany") #[600 entries]

So the idea is that I want the entries in the original list be replaced by the corresponding normed spellings. Each unique spelling from orig_list is represented in unique_list and the normed spellings can be found at the same index in norm_spellings.
In a related thread (which I cannot find again for the life of me, suggested using setNames for a similar task, like
map = setNames(norm_spellings, unique_spellings)
orig_list  = map[orig_list]

works almost, but produces a lot of NAs for some reason. Is there a clever way to do it without multiple for loops?