text:
Q: Python нарисовать GUI для крестиков-ноликов Как сделать поле для крестиков-ноликов и при клике на определенную ячейку нужно, что бы изменялось значение в моем словаре (который будет "базой" для крестиков-ноликов) и изменялся символ на крестик. При следующем клике так же изменится значение в моем словаре и символ на поле на нолик и так по кругу.
Просто прошу советов, которые помогут мне решить это задание, спасибо.

A: Набросал простенький пример рисования доски и обработке клика на ее ячейках с изменением матрицы доски:
try:
    from PyQt5.QtWidgets import *
    from PyQt5.QtGui import *
    from PyQt5.QtCore import *

except:
    from PyQt4.QtGui import *
    from PyQt4.QtCore import *

class Window(QWidget):
    def __init__(self):
        super().__init__()

        # Матрица 3 на 3
        self._board_tic_tac_toe = [[None for _ in range(3)] for _ in range(3)]

        self._size_cell = 80

        # If True -- X else -- O
        self._current_figure_flag = True

    def mouseReleaseEvent(self, e):
        # Определяем позицию клика
        i = e.pos().y() // self._size_cell
        j = e.pos().x() // self._size_cell

        # Выход за пределы массива
        if i >= 3 or j >= 3:
            return

        self._board_tic_tac_toe[i][j] = 'X' if self._current_figure_flag else 'O'
        self._current_figure_flag = not self._current_figure_flag

        # Перерисовка, вызов paintEvent
        self.update()

    def paintEvent(self, e):
        painter = QPainter(self)

        painter.setPen(Qt.black)
        painter.setBrush(Qt.white)

        for i in range(len(self._board_tic_tac_toe)):
            row = self._board_tic_tac_toe[i]

            for j in range(len(row)):
                x = j * self._size_cell
                y = i * self._size_cell
                w = self._size_cell
                h = self._size_cell

                painter.drawRect(x, y, w, h)

                painter.save()
                painter.setFont(QFont('Arial', 16))

                value = self._board_tic_tac_toe[i][j]
                painter.setPen(Qt.blue if value == 'X' else Qt.red)

                painter.drawText(x, y, w, h, Qt.AlignCenter, value)

                painter.restore()

if __name__ == '__main__':
    app = QApplication([])

    w = Window()
    w.show()

    app.exec()

Скриншот:


text:
Q: Issue with Reddit API and cURL creating an account I'm working on an app that allows users to create an account on reddit (and more). I use cURL and PHP to interface with the Reddit API, this is my code:
    function create_account($username, $password, $captcha_iden, $captcha_answer){

    $url = "http://reddit.com/api/register";

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_POST, true);

    $data = "user=$username&passwd=$password&passwd2=$password&rem=false&reason=redirect&api_type=json&iden=$captcha_iden&captcha=$captcha_answer";

    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

    $curl_scraped_page = curl_exec($ch);

    die($curl_scraped_page);
    curl_close($ch);

}

However, all I receive from the Reddit servers is this:
HTTP/1.1 302 Moved Temporarily
Server: AkamaiGHost
Content-Length: 0
Location: http://www.reddit.com/api/register
Date: Wed, 31 Jul 2013 20:02:03 GMT
Connection: keep-alive

HTTP/1.1 404 Not Found
Content-Length: 0
Content-Type: text/html; charset=UTF-8
Server: '; DROP TABLE servertypes; --
Vary: Accept-Encoding
Date: Wed, 31 Jul 2013 20:02:04 GMT
Connection: keep-alive

I'm not entirely sure what that HTTP response means and I'm really confused on how to fix this. cURL runs perfectly fine on my server (I have tested it).
Any ideas?

A: The first part of the response is switching you over from reddit.com to www.reddit.com. I'm assuming the second request is making a GET, which is not accepted for that endpoint (only POST according to the docs) and so it returns the 404. Try updating the original URL to include the www. and see if that works.

redpajama_set_name: RedPajamaStackExchange


text:
Q: WCF URI only works on localhost After creating a service host, I am not able to open page "http://myuri:8000/ServiceModelSamples/Service" when I use internet explorer.
  Uri baseAddress = new Uri("http://myuri:8000/ServiceModelSamples/Service");

  // Step 2 of the hosting procedure: Create ServiceHost
  ServiceHost selfHost = new ServiceHost(typeof(CalculatorService), baseAddress);
  // rest of the below code is from calculator MSDN sample

It only works if I use localhost instead of "myuri". Can someone please tell what else is required?
EDIT: myri is actually my PC name. I tried using IP adress for my PC also. Internet explorer is able to open up the URL from my box, but it fails when I open the URL from other box (eg., the URL I am trying to open is http://111.251.164.20:8000/ServiceModelSamples/Service )

A: Eh... myuri is just an example, a placeholder. Not something you should use literally.

A: If you really want to use myuri you need to add a record to your hosts.ini file.
Like: 127.0.0.1 myuri localhost


text:
Q: What is the meaning of "the same - than"? I'm working as a Software Engineer in US, and I'm a non-native speaker. I am familiar with the phrase "same as".
When I read the following wiki page, I encountered a phrase consisting of "same" and "than". I am copying and pasting that sentence at the bottom of this question.
I do not clearly understand what it means. Could anyone please tell me whether the following sentence makes sense? If so, could you explain to me what it means?
From https://en.wikipedia.org/wiki/Friend_function:

In object-oriented programming, a friend function, that is a "friend" of a given class, is a function that is given the same access than methods to private and protected data.

A: It's a mistake.

The same is followed by as. It is not followed by that or than:

http://dictionary.cambridge.org/grammar/british-grammar/same-similar-identical

A: There is a good explanation for this on the forum:
http://forum.wordreference.com/threads/same-than-same-as-same-that.400069/
In comparatives, when one is 'more' than the other you use 'than': bigger than, smaller than, colder than, warmer than, more interesting than, less interesting than.
When they are the same you always use 'as'. This is the same as this.
If you use another adjective you put the adjective between two 'as':
My house is as big as yours.
John is as tall as Pete, but Nick is taller than them.
So the sentence should be:

In object-oriented programming, a friend function, that is a
  "friend" of a given class, is a function that is given the same
  access as methods to private and protected data.


text:
Q: Assembly recompilation and assembly load issue I have an executable (Foo.exe) and a library Bar.dll. Both binaries are NOT strong name signed. The Bar.dll library depends on the executable file and has it specified in its manifest in such manner:
<dependency>
    <dependentAssembly dependencyType="install" allowDelayedBinding="true" codebase="Foo.exe" size="334336">
      <assemblyIdentity name="Foo" version="1.2.3.4" language="neutral" processorArchitecture="msil" />
    </dependentAssembly>
</dependency>

I do a roundtrip from Foo.exe -> msil -> Foo.exe with ildasm and ilasm. Decompilation with ildasm generates a single .il file, .res file and multiple .resources files. I recompile the application in such manner:
ilasm Foo.il /resource=Foo.res

After recompilation the application works and can be launched. The problem now is that the library Bar.dll that depends on the executable fails to load it (the Foo.exe executable) after recompilation. This is what fusion log gives me:
   *** Assembly Binder Log Entry  (11/12/2012 @ 5:00:38 PM) ***

The operation failed.
Bind result: hr = 0x8013101b. No description available.

Assembly manager loaded from:  C:\Windows\Microsoft.NET\Framework\v2.0.50727\mscorwks.dll
Running under executable  C:\Program Files (x86)\SomeApplication\Something.EXE
--- A detailed error log follows.

=== Pre-bind state information ===
LOG: User = Bartek-W7\Bartek
LOG: DisplayName = Bar, Version=1.2.3.4, Culture=neutral, PublicKeyToken=null
 (Fully-specified)
LOG: Appbase = file:///C:/Program Files (x86)/FooBar
LOG: Initial PrivatePath = NULL
LOG: Dynamic Base = NULL
LOG: Cache Base = NULL
LOG: AppName = NULL
Calling assembly : Bar, Version=1.2.3.4, Culture=neutral, PublicKeyToken=null.
===
LOG: This bind starts in default load context.
LOG: Application configurtion file not found.
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v2.0.50727\config\machine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: Attempting download of new URL file:///C:/Program Files (x86)/FooBar/Foo.dll
LOG: Attempting download of new URL file:///C:/Program Files (x86)/FooBar/Foo/Foo.dll
LOG: Attempting download of new URL file:///C:/Program Files (x86)/FooBar/Foo.exe
LOG: Assembly download was successful. Attempting setup of file: C:/Program Files (x86)/FooBar/Foo.exe
LOG: Entering download cache setup phase.
ERR: Error extracting manifest import from file (hr = 0x8013101b).
ERR: Setup failed with hr = 0x8013101b.
ERR: Failed to complete setup of assembly (hr = 0x8013101b). Probing terminated.

Now before the recompilation the file loads successfully and the only difference in the fusion log are last 4 lines:
LOG: set name: Foo, Version=1.2.3.4, Culture=neutral, PublicKeyToken=null
WARNING: found a duplicate set during cache setup
LOG: Bind successful.
LOG: Bind is in default load context.

A:
ERR: Error extracting manifest import from file (hr = 0x8013101b)

Error code 8013101b is COR_E_NEWER_RUNTIME.  In other words, the assembly needs a newer version of the CLR than the one that is actually loaded.  There's a pretty simple explanation for that, you are probably using the wrong version of ilasm.exe.  Version 4 instead of version 2.
Be sure to use C:\Windows\Microsoft.NET\Framework\v2.0.50727\ilasm.exe, not the one in v4.0.30319


text:
Q: How to send this SOAP request with PHP I'm trying to integrate with a third party API and their API accpets only SOAP requests. They have this sample in their documentation. All I need is to replace the agentcode and mpin. Pls I need some one to help me write a PHP code to send the below format to this link http://202.140.50.116/EstelServices/services/EstelServices?wsdl using SOAP request
<soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:ser="http://services.estel.com"
xmlns:bal="http://balance.support.services.estel.com">
   <soapenv:Header/>
   <soapenv:Body>
      <ser:getBalance>
         <ser:balanceRequest>
            <bal:agentCode>TPR_CM</bal:agentCode>
            <bal:mpin>EE17F932B3C311E8877F999DD7865E11</bal:mpin>
         </ser:balanceRequest>
      </ser:getBalance>
   </soapenv:Body>
</soapenv:Envelope>

Heres what I have tried so far
        $xml = '<?xml version="1.0" encoding="utf-8"?>'.
            '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://services.estel.com" xmlns:bal="http://balance.support.services.estel.com">'.
            '<soapenv:Header/>'.
            '<soapenv:Body>'.
            '<ser:getBalance>'.
                '<ser:balanceRequest>'.
                    '<bal:agentCode>TPR_CM</bal:agentCode>'.
                    '<bal:mpin>EE17F932B3C311E8877F999DD7865E11</bal:mpin>'.
                '</ser:balanceRequest>'.
            '</ser:getBalance>'.
            '</soapenv:Body>'.
        '</soapenv:Envelope>';

    $url = "http://balance.support.services.estel.com";

    $soap_do = curl_init();
    curl_setopt($soap_do, CURLOPT_URL,            $url );
    curl_setopt($soap_do, CURLOPT_RETURNTRANSFER, true );
    curl_setopt($soap_do, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($soap_do, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($soap_do, CURLOPT_POST,           true );
    curl_setopt($soap_do, CURLOPT_POSTFIELDS,    $xml);

    $result = curl_exec($soap_do);
    $err = curl_error($soap_do);
    var_dump($result);

A: Use this simple script, which gives you enough information. Function and type lists will help you to make correct SOAP call:
<?php
// SOAP
$soap = new SoapClient("http://202.140.50.116/EstelServices/services/EstelServices?wsdl");

// List functions
echo 'Functions: '.'
';
$functions = $soap->__getFunctions();
foreach($functions as $item) {
    echo $item.'
';
}
echo '
';

// List types
echo 'Types: '.'
';
$types = $soap->__getTypes();
foreach($types as $item) {
    echo $item.'
';
}
echo '
';

// Consume SOAP
$params = array(
    "balanceRequest" => array(
        "agentCode" => "TPR_CM",
        "mpin" => "EE17F932B3C311E8877F999DD7865E11"
    )
);

// Consume SOAP
$responce = $soap->getBalance($params);
foreach($responce->getBalanceReturn as $name => $value) {
   echo $name.': '.$value.'
';
}
?>

A: Use the PHP native SoapClient along with the service WSDL:
$atservices_wsdl = "http://202.140.50.116/EstelServices/services/EstelServices?wsdl";
$atservices_client = new SoapClient($atservices_wsdl);

$balance = $atservices_client->getBalance("TPR_CM","EE17F932B3C311E8877F999DD7865E11");

print_r($balance); // review the returned object converted from SOAP response.


text:
Q: How do I search Microsoft's "Legal Stuff" displayed during PC setup? I purchased a laptop with Windows 10 for testing some libraries I contribute to. I'm at the Windows 10 "Here's the Legal Stuff" screen where Microsoft forces users into accepting their obscene terms by only providing an Accept button.
There are pages upon pages of stuff in this form, and I don't understand most of it. I want to search for some keywords in the agreement that I usually do [somewhat] understand, but I don't see how to search the form.
How do I search the "Legal Stuff" displayed during PC setup?

A: Here is a link to Windows 10 license terms.  You can search it through the browser.


text:
Q: Do two II$_1$-factors with trivial intersection generate $B(H)$? Let $H$ be an infinite dim. separable Hilbert space and $B(H)$ the algebra of bounded operators.
Let $A$, $B \subset B(H)$ be II$_1$-factors such that $A \cap B = \mathbb{C}I$.
Examples:
(1) Take $B = A'$ then $A \cap B = \mathbb{C}I$ by definition of a factor.
(2) Take $(A' \subset B)$ an irreducible subfactor, then $A \cap B = \mathbb{C}I$ by definition of irreducibility.
Obviously $\langle A' , B' \rangle = (\mathbb{C}I)' = B(H)$.
Question: Is it also true that $\langle A , B \rangle = B(H)$ ?
Else, what are counterexamples?
Remark: It's true for the examples (1) and (2).
Notation: $\langle S \rangle= (S \cup S^* \cup \mathbb{C}I)  ''$

A: You can phrase the question as whether $A\cap B=\mathbb C$  implies $A'\cap B'=\mathbb C$.
Let $M$  be some II$_1$-factor in $B(H) $,  and let $A=M\otimes1$, $B=1\otimes M$ in $B(H\otimes H) $. Then
$$
A'=M'\otimes B(H),\ \ \ B'=B(H)\otimes M',
$$
so $A'\cap B'
=M'\otimes M'$.


text:
Q: unexpected "map" result (Javascript) Can someone explain why this has the unexpected result:
["1", "2", "3"].map(parseInt);

which returns [1, NaN, NaN] instead of [1, 2, 3]?
I can make it work by forcing a single-argument function:
["1", "2", "3"].map(function(s) {return parseInt(s);});

but I don't know what exactly went wrong in the first way.

A: As others mentioned, the problem is due to the 2nd argument.
Comments from MDN:
// parseInt is often used with one argument, but takes two. The second being the radix
// To the callback function, Array.prototype.map passes 3 arguments: the element, the index, the array
// The third argument is ignored by parseInt, but not the second one, hence the possible confusion.
// See the blog post for more details

But, with the use of bind, you can achieve the desired result:
var _parseInt = function(radix, number) {
  return parseInt(number, radix);
}
["1", "2", "3"].map(_parseInt.bind(this, 10));

A: this article describes your issue in its last sample, exactly the same what you are trying to do. However the blog article they refer to doesn't exist anymore.
array.map() and parseInt callback
A better answer cited from Stackoverflow:

So if you call a function which actually expects two arguments, the
  second argument will be the index of the element.
In this case, you ended up calling parseInt with radix 0, 1 and 2 in
  turn. The first is the same as not supplying the parameter, so it
  defaulted to base 10. Base 1 is an impossible number base, and 3 is
  not a valid number in base 2:

parseInt('1', 0); // OK - gives 1
parseInt('2', 1); // FAIL - 1 isn't a legal radix
parseInt('3', 2); // FAIL - 3 isn't legal in base 2

A: parseInt takes two arguments (the second being the radix), that's why this doesn't work. See the bottom of this MDN page for more information. Cited:

parseInt is often used with one argument, but takes two. The second
  being the radix To the callback function, Array.prototype.map passes 3
  arguments: the element, the index, the array. The third argument is
  ignored by parseInt, but not the second one, hence the possible
  confusion.


text:
Q: Task :app:mergeDebugAssets FAILED when I try to run npx react-native run-android I'm working on an android app on react-native using vscode and a physical android device and it keeps showing the error below while trying to build using npx react-native run-android.
Task :app:mergeDebugAssets FAILED

Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.7/userguide/command_line_interface.html#sec:command_line_warnings
38 actionable tasks: 38 executed
Warning: Mapping new ns http://schemas.android.com/repository/android/common/02 to old ns http://schemas.android.com/repository/android/common/01
Warning: Mapping new ns http://schemas.android.com/repository/android/generic/02 to old ns http://schemas.android.com/repository/android/generic/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/addon2/02 to old ns http://schemas.android.com/sdk/android/repo/addon2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/repository2/02 to old ns http://schemas.android.com/sdk/android/repo/repository2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/sys-img2/02 to old ns http://schemas.android.com/sdk/android/repo/sys-img2/01
Warning: Mapping new ns http://schemas.android.com/repository/android/common/02 to old ns http://schemas.android.com/repository/android/common/01
Warning: Mapping new ns http://schemas.android.com/repository/android/generic/02 to old ns http://schemas.android.com/repository/android/generic/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/addon2/02 to old ns http://schemas.android.com/sdk/android/repo/addon2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/repository2/02 to old ns http://schemas.android.com/sdk/android/repo/repository2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/sys-img2/02 to old ns http://schemas.android.com/sdk/android/repo/sys-img2/01

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:mergeDebugAssets'.
> Could not resolve all files for configuration ':app:debugRuntimeClasspath'.
   > Could not resolve org.webkit:android-jsc:+.
     Required by:
         project :app
      > Failed to list versions for org.webkit:android-jsc.
         > Unable to load Maven meta-data from https://jcenter.bintray.com/org/webkit/android-jsc/maven-metadata.xml.
            > Could not HEAD 'https://jcenter.bintray.com/org/webkit/android-jsc/maven-metadata.xml'. Received status code 502 from server: Bad Gateway

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 1m 1s

error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup.
Error: Command failed: ./gradlew app:installDebug -PreactNativeDevServerPort=8081
Warning: Mapping new ns http://schemas.android.com/repository/android/common/02 to old ns http://schemas.android.com/repository/android/common/01
Warning: Mapping new ns http://schemas.android.com/repository/android/generic/02 to old ns http://schemas.android.com/repository/android/generic/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/addon2/02 to old ns http://schemas.android.com/sdk/android/repo/addon2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/repository2/02 to old ns http://schemas.android.com/sdk/android/repo/repository2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/sys-img2/02 to old ns http://schemas.android.com/sdk/android/repo/sys-img2/01
Warning: Mapping new ns http://schemas.android.com/repository/android/common/02 to old ns http://schemas.android.com/repository/android/common/01
Warning: Mapping new ns http://schemas.android.com/repository/android/generic/02 to old ns http://schemas.android.com/repository/android/generic/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/addon2/02 to old ns http://schemas.android.com/sdk/android/repo/addon2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/repository2/02 to old ns http://schemas.android.com/sdk/android/repo/repository2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/sys-img2/02 to old ns http://schemas.android.com/sdk/android/repo/sys-img2/01

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:mergeDebugAssets'.
> Could not resolve all files for configuration ':app:debugRuntimeClasspath'.
   > Could not resolve org.webkit:android-jsc:+.
     Required by:
         project :app
      > Failed to list versions for org.webkit:android-jsc.
         > Unable to load Maven meta-data from https://jcenter.bintray.com/org/webkit/android-jsc/maven-metadata.xml.
            > Could not HEAD 'https://jcenter.bintray.com/org/webkit/android-jsc/maven-metadata.xml'. Received status code 502 from server: Bad Gateway

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 1m 1s

    at makeError (/home/akaranath/Desktop/krop_delivery_cs/node_modules/@react-native-community/cli-platform-android/node_modules/execa/index.js:174:9)
    at /home/akaranath/Desktop/krop_delivery_cs/node_modules/@react-native-community/cli-platform-android/node_modules/execa/index.js:278:16
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async runOnAllDevices (/home/akaranath/Desktop/krop_delivery_cs/node_modules/@react-native-community/cli-platform-android/build/commands/runAndroid/runOnAllDevices.js:94:5)
    at async Command.handleAction (/home/akaranath/Desktop/krop_delivery_cs/node_modules/react-native/node_modules/@react-native-community/cli/build/index.js:186:9)

This keeps happening usually when I start off a new project and usually have to start a new project altogether for this error to resolve.
These are few of the things I tried to resolve the error.

*

*Tried ./gradlew clean and tried building app again.

*Enabled multiDexEnabled in app/build.gradle

*I'm using a physical android device to run the app. I tried uninstalling the app and tried to build the app again.

*Removed node_modules, cleared npm cache and tried installing all node_modules again.

Does anyone know how to fix this?
Below are few details about the project
package.json dependencies
"dependencies": {
    "react": "17.0.1",
    "react-native": "0.64.2",
    "@react-native-async-storage/async-storage": "^1.15.5",
    "@react-native-firebase/app": "^13.0.1",
    "@react-native-firebase/auth": "^13.0.1",
    "@react-native-firebase/firestore": "^13.0.1",
    "@react-navigation/bottom-tabs": "^6.0.4",
    "@react-navigation/native": "^6.0.4",
    "@react-navigation/stack": "^6.0.4",
    "moment": "^2.29.1",
    "react-native-bootsplash": "^3.2.6",
    "react-native-geolocation-service": "^5.3.0-beta.3",
    "react-native-gesture-handler": "^1.10.3",
    "react-native-paper": "^4.9.2",
    "react-native-push-notification": "^8.1.1",
    "react-native-safe-area-context": "^3.3.0",
    "react-native-screens": "^3.5.0",
    "react-native-vector-icons": "^8.1.0"
  },
  "devDependencies": {
    "@babel/core": "^7.12.9",
    "@babel/runtime": "^7.12.5",
    "@react-native-community/eslint-config": "^2.0.0",
    "babel-jest": "^26.6.3",
    "eslint": "7.14.0",
    "jest": "^26.6.3",
    "metro-react-native-babel-preset": "^0.64.0",
    "react-test-renderer": "17.0.1"
  },

android/build.gradle info
buildscript {
    ext {
        buildToolsVersion = "29.0.3"
        minSdkVersion = 21
        compileSdkVersion = 29
        targetSdkVersion = 29
        ndkVersion = "20.1.5948944"
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath("com.android.tools.build:gradle:4.1.0")
        classpath 'com.google.gms:google-services:4.3.8'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

Output of ./gradlew build --warning-mode all
> Configure project :react-native-firebase_app
:react-native-firebase_app package.json found at /home/akaranath/Desktop/krop_delivery_cs/node_modules/@react-native-firebase/app/package.json
:react-native-firebase_app:firebase.bom using default value: 29.0.2
:react-native-firebase_app:play.play-services-auth using default value: 20.0.0
:react-native-firebase_app package.json found at /home/akaranath/Desktop/krop_delivery_cs/node_modules/@react-native-firebase/app/package.json
:react-native-firebase_app:version set from package.json: 13.1.1 (13,1,1 - 13001001)
:react-native-firebase_app:android.compileSdk using custom value: 29
:react-native-firebase_app:android.targetSdk using custom value: 29
:react-native-firebase_app:android.minSdk using custom value: 21
:react-native-firebase_app:reactNativeAndroidDir /home/akaranath/Desktop/krop_delivery_cs/node_modules/react-native/android

> Configure project :react-native-firebase_auth
:react-native-firebase_auth package.json found at /home/akaranath/Desktop/krop_delivery_cs/node_modules/@react-native-firebase/auth/package.json
:react-native-firebase_app package.json found at /home/akaranath/Desktop/krop_delivery_cs/node_modules/@react-native-firebase/app/package.json
:react-native-firebase_auth:firebase.bom using default value: 29.0.2
:react-native-firebase_auth package.json found at /home/akaranath/Desktop/krop_delivery_cs/node_modules/@react-native-firebase/auth/package.json
:react-native-firebase_auth:version set from package.json: 13.1.1 (13,1,1 - 13001001)
:react-native-firebase_auth:android.compileSdk using custom value: 29
:react-native-firebase_auth:android.targetSdk using custom value: 29
:react-native-firebase_auth:android.minSdk using custom value: 21
:react-native-firebase_auth:reactNativeAndroidDir /home/akaranath/Desktop/krop_delivery_cs/node_modules/react-native/android

> Configure project :react-native-firebase_firestore
:react-native-firebase_firestore package.json found at /home/akaranath/Desktop/krop_delivery_cs/node_modules/@react-native-firebase/firestore/package.json
:react-native-firebase_app package.json found at /home/akaranath/Desktop/krop_delivery_cs/node_modules/@react-native-firebase/app/package.json
:react-native-firebase_firestore:firebase.bom using default value: 29.0.2
:react-native-firebase_firestore package.json found at /home/akaranath/Desktop/krop_delivery_cs/node_modules/@react-native-firebase/firestore/package.json
:react-native-firebase_firestore:version set from package.json: 13.1.1 (13,1,1 - 13001001)
:react-native-firebase_firestore:android.compileSdk using custom value: 29
:react-native-firebase_firestore:android.targetSdk using custom value: 29
:react-native-firebase_firestore:android.minSdk using custom value: 21
:react-native-firebase_firestore:reactNativeAndroidDir /home/akaranath/Desktop/krop_delivery_cs/node_modules/react-native/android

> Configure project :react-native-screens
Adding a Configuration as a dependency is a confusing behavior which isn't recommended. This behaviour has been deprecated and is scheduled to be removed in Gradle 8.0. If you're interested in inheriting the dependencies from the Configuration you are adding, you should use Configuration#extendsFrom instead. See https://docs.gradle.org/6.7/dsl/org.gradle.api.artifacts.Configuration.html#org.gradle.api.artifacts.Configuration:extendsFrom(org.gradle.api.artifacts.Configuration[]) for more details.
Warning: Mapping new ns http://schemas.android.com/repository/android/common/02 to old ns http://schemas.android.com/repository/android/common/01
Warning: Mapping new ns http://schemas.android.com/repository/android/generic/02 to old ns http://schemas.android.com/repository/android/generic/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/addon2/02 to old ns http://schemas.android.com/sdk/android/repo/addon2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/repository2/02 to old ns http://schemas.android.com/sdk/android/repo/repository2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/sys-img2/02 to old ns http://schemas.android.com/sdk/android/repo/sys-img2/01
Warning: Mapping new ns http://schemas.android.com/repository/android/common/02 to old ns http://schemas.android.com/repository/android/common/01
Warning: Mapping new ns http://schemas.android.com/repository/android/generic/02 to old ns http://schemas.android.com/repository/android/generic/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/addon2/02 to old ns http://schemas.android.com/sdk/android/repo/addon2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/repository2/02 to old ns http://schemas.android.com/sdk/android/repo/repository2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/sys-img2/02 to old ns http://schemas.android.com/sdk/android/repo/sys-img2/01

FAILURE: Build failed with an exception.

* What went wrong:
Could not determine the dependencies of task ':app:lintVitalRelease'.
> Could not resolve all artifacts for configuration ':app:debugRuntimeClasspath'.
   > Could not resolve org.webkit:android-jsc:+.
     Required by:
         project :app
      > Failed to list versions for org.webkit:android-jsc.
         > Unable to load Maven meta-data from https://jcenter.bintray.com/org/webkit/android-jsc/maven-metadata.xml.
            > Could not HEAD 'https://jcenter.bintray.com/org/webkit/android-jsc/maven-metadata.xml'. Received status code 502 from server: Bad Gateway

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 7s

A: Replace the now obsolete jcenter() repository with mavenCentral().
In case of missing packages, not still could provide them with mavenLocal() or a flatDir repo.
The output has a more suspicious lines, which hint for a insane build environment.

A: I change android\build.gradle
...
    repositories {
        ...
        mavenCentral() //jcenter()
    }
...
allprojects {

    repositories {
        ...
        mavenCentral()
        jcenter() {
            content {
                includeModule("com.facebook.yoga", "proguard-annotations")
                includeModule("com.facebook.fbjni", "fbjni-java-only")
                includeModule("com.yqritc", "android-scalablevideoview")
            }
        }

I change android\gradle.properties
FLIPPER_VERSION=0.99.0


text:
Q: PGP Encryption/Decryption issue & Integrity methods We had a process that ran for almost 3 years with no problems until last week.
We tried to generate an encrypted file and it successfully made it, but on decryption, it gave us this error:

It's not possible to decrypt this message because your keyring does not contain usable private key(s) corresponding to any of the above public key(s).

How can I fix this problem?
Also, After this error, we're trying now to add some Integrity Check for the encrypted files, so, is there any thing that I can do with pgp's .exe file(s) to do so? Or what else should I do with my code to make this thing work?

A: OpenPGP uses Public-Key-Encryption. This means you're handing out your public key (thus it's named public) for others to encrypt information targeted to you and only the holder of the private key (here: you) can decrypt it.
The error message is quite clear: You encrypted the file using a public key for which you haven't got the private key in your keyring. You will need to import it; if you haven't got it (any more), you cannot decrypt the file.
If you're using Symantec PGP, you can do it using
pgp --import <keyname.asc>

For GnuPG, just replace the pgp by gpg.
Your encrypted file will be probably allright, PGP could read it, otherwise it would have echoed another error message.


text:
Q: PHP redirect website with only domain change I am asking the same question that has already been asked several times but none of them has answered so far.
I want to redirect the website to the clone folder on the web server.
Following URL was previously in use.
http://www.websiteurl.com/vshop/index.php?page=shop.product_details&product_id=440
Now i've a new setup on the same URL but different folder.
http://www.websiteurl.com/payonline/index.php?page=shop.product_details&product_id=440
The first folder name is "vshop" and 2nd one is "payonline".
Can somebody please tell me how can i keep the complete url, but change the folder name, I don't want to use "search or replace" feature. I might need to change the complete domain.
Please do also tell me if .htaccess is better of php script will work fine.
Thanks

A: This Htaccess RewriteRule should do it for you.
RewriteEngine On
RewriteRule ^vshop/(.*) payonline/$1 [QSA]


text:
Q: Problems with routing in a small JavaScript App without using frameworks , just a library - page.js I am trying to learn how a small routing library for javascript apps works - page.js
So I made one very tiny app for my own learning purposes but for some reason i can't make it work properly.
The app is really as simple as it gets - one folder named test-routing with one file and one folder
in it - index.html and src; the src folder has also one file - app.js and another folder-
views, with 3 files in it - home.js, page1.js and page2.js
The html file has empty body tag and in the head tag I wrote this:
<script src="./src/app.js" type="module"></script>
In the app.js there is this:
import page from '../node_modules/page/page.mjs';
import { home } from './views/home.js';
import { page1 } from './views/page1.js';
import { page2 } from './views/page2.js';
page('/',home);
page('/first',page1);
page('/second/:id',page2);
page.start();

Each of the  three files in the views folder has one line of code:
home.js
export function home(){ console.log('HOME PAGE'); }
page1.js
export function page1(){ console.log('PAGE ONE'); }
page2.js
export function page2(context, next){ console.log('PAGE TWO', context.params.id); }
Together with page.js I also installed locally live-server. I ran it and it started
working properly on port 8080.
My expectations were that when I go to http://localhost:8080 I would find
'HOME PAGE' in the console and that was indeed the case.
But when I tried with http://localhost:8080/first and http://localhost:8080/second/2,
I received in both cases 404 (Not Found) in the console instead of 'PAGE ONE' and 'PAGE TWO 2'
and it was also printed in the web page itself 'Cannot GET /first' and 'Cannot GET /second/2'
respectively.
Can anyone tell me where I went wrong, please?
Thank you very much in advance!

A: You may need to think about push state technique
pushState


text:
Q: Averaging data leads to smaller standard deviation. Where is this visible in the formulas? I need to compare two series of accidents counts from two cities. The comparison should establish whether the two series change at a similar rate.
My way to answer this would be to calculate for every two consecutive years the rate of change for each series. Then I will create a new series of the ratio of their rate of change.
The closer the mean of that series would be to 1, (and the smaller the variance), the stronger will be the conclusion that the two series A and B change at a similar rate.
I can decide to compare on a monthly basis ("resolution"), or to sum the monthes, and to take a year as the unit of time.
Now I come to the main quandry :
Comparison that uses a year (rather than a month) as a unit of time, makes the rate of change of the two series to seem to be more similar. It seems that always when I average/sum a series of data, the standard deviation becomes smaller.
However, obviously information is lost if summing\averaging across a year. My question is where does this loss of information appear in the mathematical formulas? Usually loss of information is expressed in the formulas...


text:
Q: Date command is not working in remote server when running using a script I am running below command from a script from a remote server, but getting error No such file or directory
ssh -t -t user@xx.xx.xx.xx \"sudo mysql nss_mysql < /home/user/scripts/Db_nss_mysql-`date +%Y-%m-%d`.sql && /bin/bash /home/user/scripts/jenkin-soft.sh\"

I run like bash jenkin-soft.sh and the complete error is:
jenkin-soft.sh: line 36: /home/user/scripts/Db_nss_mysql-`date +%Y-%m-%d`.sql: No such file or directory.

I tried below commands and they are working properly::
givinv@ser1:~/scripts$ ssh -t -t user@xx.xx.xx.xx "sudo mysql"
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 66

mysql> Bye
Connection to xx.xx.xx.xx closed.
givinv@ser1:~/scripts$ ssh -t -t  user@xx.xx.xx.xx "sudo ls /home/user/scripts/Db_nss_mysql-`date +%Y-%m-%d`.sql"
/home/user/scripts/Db_nss_mysql-2017-04-07.sql
Connection to xx.xx.xx.xx closed.
givinv@ser1:~/scripts$

What wrong I am doing?

A: Your quoting is at fault here or rather the lack of it. Coz when you write:  \"sudo ....\" does not quote your string, rather it quotes that one quote char "
ssh -t -t user@xx.xx.xx.xx 'sudo mysql nss_mysql < /home/user/scripts/Db_nss_mysql-`date +%Y-%m-%d`.sql && /bin/bash /home/user/scripts/jenkin-soft.sh'


text:
Q: How to insert data without auto incrementing ID using SQLite I need to insert one value into a table based on an auto incremented ID, for example the ID = 7 and I want to insert "this" into a column based on the ID "7".
I basically want to do this, but am not sure how to do it without auto incrementing the ID.
INSERT INTO table (tableData) VALUES (12345)
FROM table
WHERE ID = 7

I tried this:
INSERT INTO table (tableData)
SELECT ID FROM table
WHERE ID  7

But that just inserts the number 7 into the column and auto increments the table. Is there a way to insert a value based on the ID without auto-incrementing another row?
Thanks in advance
(SOLVED)
I figured out the problem. All I need to do was use UPDATE instead of INSERT so I used
UPDATE tablename
SET columnname ="something"
WHERE ID = "7"

A: Assuming your column can be nullable:
INSERT INTO tableData (id)
VALUES (7)

A: I figured out the problem. All I need to do was use UPDATE instead of INSERT so I used
 UPDATE tablename
 SET column="something"
 WHERE ID = "7"


text:
Q: How can I make this feature faster in Javascript? I have created a highlight feature that will highlight anything contained in a
 red using a user specified keyword. When the submit button is clicked Javascript/jQuery pull the keyword from the input field and compare it to any lines that conain it and then highlight those lines red. It works great... but its slow. Is there another way to do this that is faster when working with over 1000 lines of
?
HTML
Keyword: <input type="text" id="highlight_box" class="text_box" value="--Text--" />
<input type="button" id="highlight" value="Highlight" />

Some Content

Some more content

JavaScript
//add highlight and tag
$("#highlight").click(
function(){
    var id = $("#highlight_box").val();
    if(id == "--Text--" || id == ""){
        alert("Please enter text before highlighting.");
    }else{
        $("#access-keywords-row").append("
 " + id + "
");
$("#access_log_print p:containsi(" + id + ")").css("color","red");        }
});

//remove highlight and tag
$(".keywords-row").on("click", ".delete_filter",
    function() {
        var val = $(this).val();

        //remove element from HTML
        $(this).parent().remove();
        $("#access_log_print p:containsi(" + val + ")").css("color","black");

    });

A: Adding color, red means adding the style attribute to each p, I think this can be improved adding a class:
p.highlight {
   color:red;
}

And replacing
$("#access_log_print p:contains(" + id + ")").css("color","red");

by
$("#access_log_print p:contains(" + id + ")").addClass('highlight');

This probably speeds a little bit the process

A: Try defining a css class, e.g.:
.red{background-color:#f00;}

and then instead of adding to each "style=background-color:#f00;" you will just .addClass("red");
just less code to put, but still jQuery will have to go thru all lines and if it is a lot then I guess it depends on your machine speed ;)

A: I've written a small solution using jQuery's contains() method. Obviously you can throw in some string validation.
http://jsfiddle.net/W2CZB/

A: The following solution will probably increase performance at the cost of space. It works by building a word mapping of the lines and accessing directly to add or remove the highlight class. This solution also keeps a count of the number of times a filter hit that line so it stays highlighted until the last filter is removed. I have tested with a few lines, I am not sure how will it perform with 1000s. You tell us :)
$(function(){

buildIndex();

$("#highlight").click(
function(){
    var id = $("#highlight_box").val();
    if(id == "--Text--" || id == ""){
        alert("Please enter text before highlighting.");
    }else{
        var filter = $("
 " + id + "
");
        filter.click(function(){
            $(this).remove();
            removeHighlight(id)
        });
        $("#access-keywords-row").append(filter);
        $.each(index[id], function(i,line){
            if (line.highlightCount)
              line.highlightCount++;
            else {
              line.addClass('highlight')
              line.highlightCount=1;
            }
        });
    }
});

function removeHighlight(id) {
    $.each(index[id], function(i,line){
        line.highlightCount--;
        if (line.highlightCount<1)
            line.removeClass('highlight')
    });
};
});

var index={};
function buildIndex(){
    $("#access_log_print p").each(function(i) {
        var line = $(this)
        var words = line.text().split(/\W+/);
        $.each(words, function(i,word){
            if (!index[word]) { index[word]=[]; }
            index[word].push(line);
        });
    });
}


text:
Q: Adding conditional logic (IF, THEN) in Salesforce HTML email templates I'm struggling with adding IF, THEN conidition to my HTML Classic Email template and hoping someone can help.
I am trying to say if Cohort Owner's name is 'X', then post the X link, if Cohort Owner's name is 'Y', then post the Y link and if Cohort Owner's name is 'Z' then paste the Z link.
This is the statement I am using in SF that is not outputting what I'd like
{!IF({!Cohorts__c.OwnerFirstName} = "Bob", "Boblink", " ")}
{!IF({!Cohorts__c.OwnerFirstName} = "Tim", "Timlink", " ")}
{!IF({!Cohorts__c.OwnerFirstName} = "Anna", "Annalink", " ")}

This is the output it gives me when I send an email.
 = "Bob", "Boblink", " ")} = "Tim", "Timlink", " ")} = "Anna", "Annalink", " ")}

I'd like the output to be dependent on Cohort Owner and have the output as, i.e Here is.. Annalink (if Cohort Owner is Anna)
Any suggestions?

A: Merge fields start with {! and end with }. You do not use {! or } within the merge field. In addition, you can use a CASE statement, which is easier to read.
{!CASE(Cohorts__c.OwnerFirstName,
  "Bob", "Boblink",
  "Tim", "Timlink",
  "Anna", "Annalink",
  "")}

Or, if you prefer the IF statements, you can nest them together:
{!IF(Cohorts__c.OwnerFirstName = "Bob", "Boblink",
IF(Cohorts__c.OwnerFirstName = "Tim", "Timlink",
IF(Cohorts__c.OwnerFirstName = "Anna", "Annalink", " ")))}


text:
Q: How to combine multiple .pcd files into a single .pcd file which contains point cloud data (python)? There are suggestions available in online to use "laser_scan_assembler", but i have no idea how to implement that.

A: You can simply concatenate the point clouds using the PCL library:
typedef pcl::PointXYZ PointType;
typedef pcl::PointCloud<PointType> CloudType;

// Load the PCD files
CloudType::Ptr cloud1(new CloudType);
CloudType::Ptr cloud2(new CloudType);
pcl::io::loadPCDFile("cloud1.pcd", *cloud1);
pcl::io::loadPCDFile("cloud2.pcd", *cloud2);

// Put in one output cloud
CloudType::Ptr output(new CloudType);
*output += *cloud1;
*output += *cloud2;

// Save the output file
pcl::io::savePCDFileASCII("output.pcd", *output);

Note that this simply concats the points. The input clouds have to be in the same coordinate system, otherwise a registration is needed first.
You can also use the bash executable pcl_concatenate_points_pcd to concat multiple PCD files.


text:
Q: Vuepress site not loading properly when deployed on github pages The website loads on my localhost perfectly fine as below.

But the problem when deployed to gh-pages, it looks like below. Looks like it is not reading config.js file from the docs/.vuepress/ folder.

While deploying to github pages, it is said to add base: <REPO Name>, I did that as well. In my Repository, it is currently removed.
What am I missing here? Please help.
Your are free to check out my Repository and see if you can help. Thanks in advance!!


text:
Q: im trying to capture client PC name in my web project, i found gethostname() but it captures only host name, Any help will be appreciated.! Thank You these are the methods which i tried..
$device_name = gethostname();
$device_name = getenv('COMPUTERNAME');
$device_name = php_uname();


text:
Q: `navigator.geolocation.getCurrentPosition()` gets stuck and doesn't fire callbacks in Chrome. In the depths of an application I need to use the Geolocation API.
    var that = this;

    if(Modernizr.geolocation){
      $(this).addClass("loading");

      navigator.geolocation.getCurrentPosition(function(position){
        that.handleGeoSuccess(position); // defined elsewhere
      },function(error){
        that.handleGeoError(error); // defined elsewhere
      }, {maxAge: 0, timeout: 1000});
    } else {
      that.handleGeoError(); // defined elsewhere
    }

This happens inside of a click-event. Chrome (25.0.1364.155) prompts for permission but none of the callbacks are fired, neither when accepting nor when denying geolocation information. Even asking again using setTimeout didn't work. No callbacks are fired.
I'm quite stuck here and don't know where to look. Any ideas?
btw it works in Firefox (19.0)and Safari (6.0.2), current Chrome Canary behaves the same.


text:
Q: jQuery in VisualForce is not working I know this is very basic!
I am learning to implement jQuery in VisualForce page development. As part of that I have tried the following code (just playing around). The purpose of the code is: If I click on the button, the input text field should populate with the text which is not happening. Please let me know if there is anything wrong in this.
<apex:page standardController="Account">
<apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" />
<script>
    $(document).ready(function(){
        $("#button").click(function(){
            $(#sampleText).val('This is Sample Text');
        });
    });
</script>
<apex:form >
<apex:pageBlock title="Testing jquery">
<apex:inputText id="sampleText" />
<apex:commandButton id="button" value="Save"/>
</apex:pageBlock>
</apex:form></apex:page>

A: Any element that starts with apex: will have a "managed Id", which includes some prefixes like "j_0:j_10:j11:...". Since jQuery basically uses document#querySelectorAll, you need to use the "ends-with" notation:
$("input[id$='button']")

A: You should read these articles:

*

*$Component

*Using $Component to Reference Components from JavaScript

*Best Practices for Accessing Component IDs
You do not need to use an "ends with" selector to get your script working. The approach recommended by Salesforce is to use the $Component global variable, and this works just fine:
<apex:page id="thePage">
    <apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" />
    <script>
    (function (D, $) {
        "use strict";
        $(function(){
            var literalButtonId = "{!$Component.thePage.theForm.theBlock.button}",
                literalInputId = "{!$Component.thePage.theForm.theBlock.sampleText}",
                button = D.getElementById(literalButtonId),
                input = D.getElementById(literalInputId);
            $(button).click(function(event) {
                event.preventDefault();
                $(input).val('This is Sample Text');
            });
        });
    }(document, jQuery.noConflict()));
    </script>
    <apex:form id="theForm">
        <apex:pageBlock title="Testing jquery" id="theBlock">
            <apex:inputText id="sampleText" />
            <apex:commandButton id="button" value="Save" />
        </apex:pageBlock>
    </apex:form>
</apex:page>

Personally, however, I prefer class selectors, which feel like less of an abuse of the system:
<apex:page>
    <apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" />
    <script>
    (function ($) {
        "use strict";
        $(function(){
            $(".sampleButton").click(function() {
                $(".sampleInput").val('This is Sample Text');
            });
        });
    }(jQuery.noConflict()));
    </script>
    <apex:form>
        <apex:pageBlock title="Testing jquery">
            <apex:inputText styleClass="sampleInput" />
            <apex:commandButton styleClass="sampleButton" value="Save" />
        </apex:pageBlock>
    </apex:form>
</apex:page>


text:
Q: Creating .additem for combobox I have got a list of tariffs that i have set up on an autofilter so that when a specific sales channel is selected and password is correct it shows only the tariffs available to that channel.
My problem is that I cant seem to figure out how to get the command button to also populate the combobox.
my .additem code below keeps returning a

"Permission Denied" error

Dim TLoc As Range
Dim ws As Worksheet
Set ws = Worksheets("Tariff Matrix")
Set TLoc = Range("Tariffs")

For Each TLoc In ws.Range("Tariffs")
    With MobilePricing.Tariff1
        .AddItem TLoc.Value
    End With
Next TLoc

Any assistance will be greatly appreciated.

A: First you need to check the RowSource of your ComboBox, if it's not empty, empty it.
Then as you want to have only the visible cells (after the autofiler); you need to use Range("Tariffs").SpecialCells(xlCellTypeVisible).
Here is your amended code :
Dim TLoc As Range
Dim ws As Worksheet
Set ws = Worksheets("Tariff Matrix")
Set TLoc = Range("Tariffs")

For Each TLoc In ws.Range("Tariffs").SpecialCells(xlCellTypeVisible).Cells
    With MobilePricing.Tariff1
        .AddItem TLoc.Value
    End With
Next TLoc

To loop on your UserForm Controls, use something like this :
Dim Ctrl As Control

For Each Ctrl In Me.Controls
    If TypeName(Ctrl) <> "ComboBox" Then
    Else
        MsgBox Ctrl.Object.Name
        'Your code for one combobox (everyone will be referenced as Ctrl)
    End If
Next Ctrl


text:
Q: Nuxt Apollo GraphQL error: Variable of required type was not provided I am using Nuxt.js with Apollo and trying to access GraphQL from WordPress. I do manage to get data so I know it works.
I am trying to display a post depending on its URI, in the file _slug.vue.
pages/
--| _slug/
--| index.vue

The issue is when I try to pass a variable to the query. I get the following error GraphQL error: Variable "$uri" of required type "ID!" was not provided. (I know there is a post/data on the page/URI I am accessing).
<template>
  <article>
    {{ post }}
  </article>
</template>

<script>
import fetchPost from '~/apollo/fetchPost.gql'

export default {
  apollo: {
    post: {
      query: fetchPost,
      varibles() {
        return {
          uri: this.$route.path,
        }
      },
    },
  },
}
</script>

While the fetchPost.gql file looks like this (I have also tried inlining the query, but it makes no difference).
query queryPost($uri: ID!) {
  post(id: $uri, idType: URI, asPreview: false) {
    categories {
      nodes {
        name
        uri
      }
    }
    content(format: RENDERED)
    date
    excerpt(format: RENDERED)
    featuredImage {
      node {
        altText
        caption(format: RENDERED)
        sourceUrl(size: LARGE)
        mediaItemUrl
      }
    }
    id
    modified
    postId
    slug
    title(format: RENDERED)
    uri
  }
}

The nuxt.config.js looks like this.
apollo: {
    clientConfigs: {
      default: {
        httpEndpoint: process.env.WPGRAPHQL_ENDPOINT,
      }
    }
  },

  router: {
    extendRoutes (routes, resolve) {
      routes.push({
        name: 'custom',
        path: '/:slug*',
        component: '~/pages/_slug.vue'
      })
    }
  },

Anyone have any idea why I get the error, and how I could fix it?

A: If you use typescript and linters, the tool chain would prevent such problems immediately and save you a lot of time.

A: I wrote variables the wrong way. So the following works.
 variables() {
    return {
      uri: this.$route.path,
    }


text:
Q: Check for internet connection on Javascript Ok, I got this case. I got this app build on angular.js with a back-end build on node.js ... it works fine by all means.
The client got a crappy connection to the internet. It goes online and offline every now and then. What I need to do is a routine that pings my server to check for connection on it. If it fails, I need to ping to something else (lets say : google.com) so I can check two things:
1.- My server is online (or not)
2.- The client has no internet connection.
Ping to server works fine using this routine:
function hostReachable(host) {  // Handle IE and more capable browsers
    var xhr = new ( window.ActiveXObject || XMLHttpRequest )( "Microsoft.XMLHTTP" );
    var status;
    // Open new request as a HEAD to the root hostname with a random param to bust the cache
    xhr.open( "GET", "//" + host + "/?rand=" + Math.floor((1 + Math.random()) * 0x10000), false);
    // Issue request and handle response
    try { xhr.send(); return (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304); }
    catch (error) { return false; }
    }
 }

function check() {
if (!hostReachable(window.location.host)) {
    if (!hostReachable('www.google.co.ve')) {
        alert('No se pudo establecer conexión con el sistema. Revise su conexion a internet.');
    } else {
        alert('Existe un problema con el sistema. Por favor contacto a los administradores.');
    }
} else {
    console.log('Connected...');
}
}

check();

The deal is that checking google.com goes with cross-domains problems. so the question is very simple. Is there a way to check for internet connectivity like this ?

A: If you send a cross-domain request and the server you are trying to ping against doesn't accept it, they will send back an access-denied status.  I think that is 403, but you would want to check firebug / chrome dev tools to see what the actual code is.  Then, if you get that code, you know at the very least the request was sent and a response was received.
--edit--
Here is an example of what I mean on JSFiddle.  Be sure to check the network requests on chrome dev tools / firebug.  It is sending a request to www.google.com, and receiving a 404 status code in the response.
Sidenote: As it turns out, different servers send back different codes when denying cross-domain requests.  It seems 401, 403, and 404 are the most popular ones.  For anyone looking at this problem in the future, you will want to check which codes the site(s) you ping against are sending back.

A: You could try making a request for a javascript resource from google or some other highly reliable cdn.  It would not be subjected to cross-domain restrictions.


text:
Q: How to send JSON to my python script? Currently I'm using this function to send my JSON from a chrome extension. This is the client code from javascript sending the data.
function callPython(){
    var url  = 'http://AWS_IPNUMBER/';
    var data = {'bob':'foo','paul':'dog'};
    $.ajax({
        url: url,
        type: 'POST',
        contentType:'application/json',
        data: JSON.stringify(data),
        dataType:'json',
        success: function(data){
            var jsonObj = $.parseJSON(data);
            alert(jsonObj.encPassword);
        },
        failure: function(errorMsg) {
            alert(errorMsg);
        }
    });
}

This is the server code for Python:
s = socket()
s.bind(('', 80))
s.listen(4)
ns, na = s.accept()

while True:
    try:
        data = ns.recv(8192)
    except:
        ns.close()
        s.close()
        break

    data = json.loads(data)
    print data

The problem is that although it is listening, data is empty at data = ns.recv(8192). Then data = json.loads(data) doesn't work since data is empty.  Why is this? I thought it may be a problem with my security group on AWS but if I go to http://AWS_IPNUMBER/ I get the header from the browser while running the python script.

A: You may have better luck with a good framework like tornado or django.
I say this because in your code you are trying to parse an http POST with json.loads. HTTP isn't that simple. You will need to deal with the request and headers before you get to the body, and this can be spread out across multiple packets. Why try to reinvent the wheel when you can setup a standards compliant server from a well established project.

A: The data that $.ajax function will put is a complete HTTP request, which json.loads() won't understand. In this case you need to instantiate a HTTP server which will process the HTTP requests and then process the HTTP payload with json.loads().


text:
Q: How to get list of all child elements with field from parent I have list of dicts that contains another list in one of fields. I want to "flatten" that list, so it gives me every subelement with one field (or some fields) from parent copied into it. Example:
Source data:
[
    {
        "name": "A",
        "foo": "x",
        "bar": 1,
        "subelements": [
            {
                "baz": "xyz",
                "foobar": "abc"
            },
            {
                "baz": "zzz",
                "foobar": "def"
            }
        ]
    },
    {
        "name": "B",
        "foo": "Y",
        "bar": 4,
        "subelements": [
            {
                "baz": "yyy",
                "foobar": "aaa"
            },
            {
                "baz": "xxx",
                "foobar": "bbb"
            },
            {
                "baz": "www",
                "foobar": "bbb"
            }
        ]
    }
]

Expected result:
[
    {
        "baz": "xyz",
        "foobar": "abc",
        "foo": "x"
    },
    {
        "baz": "zzz",
        "foobar": "def",
        "foo": "x"
    },
    {
        "baz": "yyy",
        "foobar": "aaa",
        "foo": "Y"
    },
    {
        "baz": "xxx",
        "foobar": "bbb",
        "foo": "Y"
    },
    {
        "baz": "www",
        "foobar": "bbb",
        "foo": "Y"
    }
]

A: This is not currently possible to do without parent node reference. Parent node access is still listed as a feature request

A: Do you have to use JMESPath? It's not complicated to do this in Vanilla JS:
ans = [];
input.forEach(elem =>
    elem["subelements"].forEach(subElem => {
        ans.push(Object.assign({
            foo: a["foo"]
        }, subElem))
    })
);

Or, if you like a little more FP,
ans = Array.prototype.concat.apply([], input.map(elem =>
    elem["subelements"].map(subElem =>
        Object.assign({
            foo: a["foo"]
        }, subElem)
    )
));

If you're serverside with ECMAScript 2018 or are polyfilling it, then you can replace Object.assign({foo: a["foo"]}, elem) with {foo: a["foo"], ...elem}. ECMAScript 2015 lets you do [].concat(...input.map(_)) for the second solution.


text:
Q: How can I show that the Knapsack problem is in NP? I want to show that the problem below, also known as the Knapstack Problem, is in NP (non-deterministic polynomial time). Where should I start?

Given $n$ items numbered $1$ through $n$ so that $i^{th}$ item has weight $w_i$ and
   value $v_i$, determine whether it is possible to select some of these
   items with total weight at most $W$ and total value at least $V$.

A: Loosely speaking, being in NP means it's possible to verify any proposed solution efficiently. If someone proposes a selection of items, all you have to do to verify the proposal is to add up the weights and see you get at most $W$, and add up the values and see you get at least $V$.


text:
Q: Accidentally changed the attributes of all the files and folders of a user to Read-only Story behind: I wanted to upload a file located in a hidden folder(by default). The file explorer that prompted by the file uploading site did not have the "Hidden items" checkbox in the View tab(didn't have the tab panel at all). I right clicked and clicked properties, thought by changing the attributes to hidden would display the hidden files(I don't know what was going on in my mind). It showed up a progress bar with 6 something minutes remaining, got to know that something was up. Cancelled it. Wanted to revert what I just had done, did the Read-only and let it complete. Later found out that it had un-hided all the hidden files and folders too. I gave all the administration permissions.
It's only been done to C:\Users\USER1
(I don't have/want to revert back using a system restore)
I want to revert all this, and want the default setup. Any help?

A: There is no practical way to restore permissions across a user profile folder. The permissions are not the same across all the folders and files, and the permissions for your specific computer will vary widely based on the applications you have installed, how you have them configured, and other factors.
The correct thing to do in this situation is to create an entirely new user account and login with it to create new profile folders, then move the necessary files from the messed up profile to the new profile.
Once you're sure everything necessary has been moved across and you have a good backup of the old stuff, delete the old profile folders and user account.


text:
Q: LXC (proxmox) JBD high (100%) IO utilisation We have a dedicated server running a number of smaller guest VMs containing for example, HTTP server, MySQL and some real-time applications.
However we find that JBD inside the guests are often spiking to 100% disk util approximately every 5-10 seconds. This causes the real-time applications to hang for ~500-1000ms when it attempts to perform disk accesses because it is too busy.
There are no significant amount of activity in log files and using noatime, nobarrier and we are unable to disable the journal. MySQL and the HTTP server are doing some IO activity, but not 100%.

A: If this particular case, the high IO usage was being caused by a cron job executing a set of chmod and chown commands on a regular basis. On a non-virtual host, these commands were executed much faster, but inside the virtual host, these commands were much much slower to execute and caused high disk wait times.
By removing these set of commands, performance returned to normal and we no longer experienced the odd hangs.


text:
Q: hosts file windows server 2008 I am trying to change the entry in HOST file windows 2008 server so that I can host multiple user friendly website for learning purpose.
Find attached an image of my host file and IIS setting. Both "Site1.com" and "Default Web site" point to same folder "wwwroot". But if I type "http:www.site1.com or http://site1.com" will not display anything on browser. Instead if I type http://localhost, the browser displays the default IIS7 html page. How to fix so that I can type site1.com and display II7 default page.

A: You need to set the Host Name for the Site1.com site to accept requests for www.site1.com also make sure that site1.com is bound to port 80. Select Bindings... from the Actions/Edit Site section of IIS Manager for the site. You settings should look like the following:

Update: Just noticed that you have your host files entries commented out... Remove the # from the beginning of the lines for www.site1.com and it should work...


text:
Q: Inclusion-exclusion in dynamic programming There are N soldiers (numbered from 1 to N). Each soldier has some subset of skills out of M different skills (numbered from 1 to M). The skill-set of an army is the union of skill-sets of its constituent soldiers. How many different subsets of soldiers satisfy are there which have specific skill-set requirement
Problem Link
According to the Explanation problem reduces to finding the number of subsets of these numbers whose OR is exactly equal to the required value, say req

Let f(i) be the number of numbers j such that j OR i = i.Then the answer is
∑i(−1)^popcount(i xor req)(2^f(i)−1) for all i such that i OR req is req
Please Explain the above formula and How it cameI know No. of ways to choose N element is (2^n-1) but why this term (−1)^popcount(i xor req)
Please Explain the algorithm.

A: This is inclusion exclusion.
Let's examine a simplified version of the problem. Assume you had 2 sets A, B. Assume you are looking for the size of the subset that has exactly 1 element.
First, you calculate |A| + |B|. But in here, you counted the size of the intersection | A [intersection] B| twice, both in |A| and in |B|, so you reduce it and get |A| + |B| - |A [intersection] B|.
Similarly for 3 sets, you first add the sizes of all sets: |A| + |B| + |C|.
Then, you reduce all "connections" between two sets |A [intersection] B|, |A [intersection] C|, |B [intersection] C|. But now, you removed too much elements, you also removed the elements in |A [intersection] B [intersection] C|. To overcome it, you add this size.
So, generalizing it - you get for n sets, and m desired properties:
#of items with m properties:
E(m) = sum { (-1)^(r-m) * Choose(r,m) * W(r) }
Where:
W(r) = summation of all intersections of size i, or formally:
W(r) = sum { W(p_k_1,...,p_k_r) | 1<=k_1<k_2<...<k_r<=n }
W(pk1,...,pkr) = |X_k1 [intersection] X_k2 [intersection] .... [intersection] X_kr|

This explains how the (-1)^x  comes to play, we repeatidly include (add) and exclude (reduce) sizes. (-1)^x allows us to "automatically" reduce/add for every element in the summation.

As you said, popcount(i xor req) is counting the number of "up" bits in the representation of i^req. That means, popcount() is effectively your index i at the above formula, and your sets are: X_i = all soldiers with required property i.
This means if k = popcount(i XOR req), i got exactly k "required" properties, and belongs in the above summation to the value when r=k, and thus the property add/substract depends on the value of (-1)^k = (-1)^popcount(i XOR req)

A: After reading the editorial and got AC myself, I do not think it is that easy to understand the application of "Inclusion-Exclusion Principle" here, this problem is around Codeforces Div.1 Problem C / D level, for example, this one: http://codeforces.com/contest/449/problem/D
Rewritten Version@2016

Previous answer is too messy, I try to clean it up and rewrite a more readable answer

I am going to explain why the solution works, but not how to come up with such solution, I think that's more about experience.
Big Picture Explanation
First, do not over think the problem, given a[1..N], the solution is literally all subsets that can produce req
Being said, how can we find all subset that can produce x?
As the solution shows, let's define f(i)

Let f(i)be the number of numbers  such that j OR i = i.

If you find it hard to understand, think its physical meaning:

For any i,  j OR i = i iff j can be produced by take away some binary bit 1 away from i

For example, if i = 7, then j can be 0,1,2...,7;  if i=5, then j can be 0,1,4,5
So, 2^f(i) - 1 is indeed the # of possible subsets which can produce i when OR i
Hold a second here, make sure you get over the above part first.
Now what if i = req itself?  What does it means? Which subsets are counted in 2^f(req)-1? How does 2^f(req)-1 related to the answer we want?

We want the # of subsets which OR all elements will produce req
2^f(req)-1 gives the # of subsets which OR all elements OR req will produce req

Can you smell that 2^f(req)-1 is likely count more than we need?
Think like this: There are some subsets 2^f(req)-1 counts, which OR all elements can only produce x where x can be produced by take away some binary bit 1 from req (See block Quote above)
So, we have to minus something from 2^f(req)-1, and here comes Inclusion-Exclusion Principle.
Let's say we want to minus those subsets which OR all elements is equal to x, which is req take away one binary bit 1
With similar thoughts, you will find that you have to minus 2^f(x)-1 , for all possible x, here, remember x is all numbers which is req take away one binary bit 1
But then, you are going to minus more than you should, because different x may share same y, where y is req take away two binary bit 1, or y is x take away one binary bit 1, you are suppose to remove exactly one time for each y from 2^f(req)-1, but in the process of minus 2^f(x)-1, you have minus multiple times for some y!
By Inclusion-Exclusion Principle, you have to add them back...Let's have a little summary here:

What we want is 2^f(req)-1  -  2^f(x)-1  + 2^f(y)-1 ... where x is set of numbers equal to req remove one binary bit 1, y is set of numbers equal to req remove two binary bit 1 (or x remove one binary bit 1)

Can you see the pattern here? Yes, that's the -1^popcount() part in the formula
For all i <= req, every bit of i is either same as req or 0, then i xor req is equal to req - i(remove all 1-bit of i),  so popcount(i xor req) indeed gives the # of binary bit 1 to be removed from req in order to get i
Combined whole story, the formula is formed: Sum (-1)^popcount(i xor req) * (2^f(i) - 1) for all i such that i OR req = req
DP to calculate f(i)

for(int i=0;i<20;i++)
    for(int j=0; j<=(1<<20); j++) {
         if(j&(1<<i)) {
             f[j] += f[j^(1<<i)];
         }
    }

Here is the DP part to calculate f(i)
Note that it is base on the following recurrence relation:

f(i) = i itself + f(some j which is i remove some bit 1)
So, f(i) = 1 + f(i xor (1 << j)) if i's j-th bit is 1

Note that i xor (1<<j) must be smaller than i, hence the DP order.


text:
Q: Outlook Add-in does not trigger when out is in cache What I am trying to do is to do is perform an action after a new email is received. I can get this working when I am using the online mode in outlook but not when outlook is in cached mode. The message is not moved otherwise.
I have tried
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
    outlookNameSpace = this.Application.GetNamespace("MAPI");
    inbox = outlookNameSpace.GetDefaultFolder(
            Microsoft.Office.Interop.Outlook.
            OlDefaultFolders.olFolderInbox);

    items = inbox.Items;
    items.ItemAdd +=
        new Outlook.ItemsEvents_ItemAddEventHandler(Quarantine);
}

And
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{

    //triggers when new email comes in
    this.Application.NewMail += new Microsoft.Office.Interop.Outlook.
ApplicationEvents_11_NewMailEventHandler
(Quarantine);

}

I have also tried NewMailEx but cannot get to trigger even if outlook is using the online mode so I have not idea what to do with that.

A: You need to handle the NewMailEx event which is fired once for every received item that is processed by Microsoft Outlook. The item can be one of several different item types, for example, MailItem, MeetingItem, or SharingItem. The EntryIDsCollection string contains the Entry ID that corresponds to that item. Here is what MSDN states:

The NewMailEx event fires when a new message arrives in the Inbox and before client rule processing occurs. You can use the Entry ID returned in the EntryIDCollection array to call the NameSpace.GetItemFromID method and process the item. Use this method with caution to minimize the impact on Outlook performance. However, depending on the setup on the client computer, after a new message arrives in the Inbox, processes like spam filtering and client rules that move the new message from the Inbox to another folder can occur asynchronously. You should not assume that after these events fire, you will always get a one-item increase in the number of items in the Inbox.#

The ItemAdd event is fired when one or more items are added to the specified collection. This event does not run when a large number of items are added to the folder at once.
Finally, the signature of ItemAdd and NewMailEx event handlers is different. You can't use the same function to handle both of them.


text:
Q: When to use Singleton vs Transient vs Request using Ninject and MongoDB I'm not quite sure when I should use SingletonScope() vs TransientScope() vs RequestScope() when I do my binding in my global.cs file.
I have for example my call to MongoSession (using NoRM and the mvcStarter project http://mvcstarter.codeplex.com/) which is set to SingletonScope but I created a repository that use this MongoSession object to make calls to Mongo easier, e.g., I have a NewsRepository which uses MongoSession to fetch my News items from the data. As an example I have a call that fetches News items that has DisplayOnHome set to true and get the latest by CreationDate. Should such a repository be SingletonScope or would RequestScope would be more appropriate?
When should I use each of it and why?

A: I guess the answer would depend on whether your MongoSession represents a unit of work or not. Most database related classes that I've worked with (mostly in the context of ORM, such as NHibernate or EF4) revolve around a context, entities, and tracked state that represent a unit of work. A unit of work should never be kept around longer than the length of time required to perform the given unit of work, after which the unit should be committed or rolled back. That would mean you should use RequestScope.
If your MongoSession is not a unit of work, you could keep it around for the lifetime of an MVC session, in which case SessionScope would then be appropriate.

A: In general in a web app, you want state to be request scope as much as possible.
Only in the case of very low level optimisations are you ever likely to run into a case where its appropriate to create singleton objects (and the chances even then are that you'll pull such caching / sharing logic out into another class which gets pulled in as a dependency on your other [request scope] objects and make that singleton scope). Remember that a singleton in the context of a web app means multiple threads using the same objects. This is rarely good news.
On the same basis, transient scope is the most straightforward default (and that's why Ninject 2 makes it so) - request scope should only come into the equation when something needs to be shared for performance reasons, etc. (or because that's simply the context of the sharing [as mentioned in the other answer]).

A: From deleted question as requested by @shankbond above

The Disposal is not necessarily performed synchronously on your main request thread as one might assume.
You probably want to stash a Block and then Dispose() it at an appropriate phase in your request (how are you going to handle exceptions?)
Have a look in the Ninject Tests for more examples (seriously, go look - they're short and clear and I didnt regret it when I listened the 3rd time I was told to!)
See http://kohari.org/2009/03/06/cache-and-collect-lifecycle-management-in-ninject-20/

A: I am having this issue too, Lately, I started working on MongoDB. MongoDB recommends singleton for MongoClient. So I am still not sure about my implementation, and I am confused. I implemented the Mongo in the DI container two ways, and I am not sure which one is good. Let's take the first approach

*

*Here I return a singleton instance of IMongoClient
services.AddSingleton(_ =>
{
return new MongoClient(con.ConnectionString);
});
Then,
services.AddScoped<IMongoDatabase>(s =>
                {
                    var client = p.GetRequiredService<IMongoClient>();
                    return client.GetDatabase(con.DatabaseName);
                });

Then, return a scoped for my IMongoDatabase. In my repo, I inject the IMongoDatabaseand then call my DB.
    _dataContext = mongoDBClient.GetCollection<SomeCollection>(GetCollectionNameFromAppSetting((settings.DPUBotCollectionName)));

The second one I was returning an IMongoDatabase as a singleton:
services.AddSingleton<IMongoDatabase>(_ =>
            {
                //var connectionString = con;

                return new
         MongoClient(con.ConnectionString).GetDatabase("SomeDatabase");
            });

Monog says their MonogClient and IMongoDatabase are thread-safe. I am not sure which approach is right. I would appreciate it if you could give me an answer.


text:
Q: General guidelines in making a choice between Combinational or Sequential approach? I have to design a functional unit, which can  be done either using Sequential Circuits or combinational.  I have to make a choice. Development time is not an issue, but resource usage and space are-should be minimum. I understand that there may not be a law stating which choice will be economical but are there  any general guidelines in making such choices keeping in mind the constraints (resource usage i.e amount of silicon, and space)

A: You haven't mentioned clock rate or performance but these are the most critical determinants of the correct approach to use, along with resource usage.
There is no single answer; typically you would explore different tradeoffs and select a best fit from among them.
Typically, if you start with a purely combinational solution, you will end up with a fairly large circuit, operating fairly slowly, delivering an output in a single clock cycle with a fairly long clock period. The longest combinational path (normally the longest chain of gates) determines the clock speed.
You would normally add registers to its inputs and/or outputs, to synchronise all incoming and outgoing signals to a common clock (avoiding issues of race conditions and timing hazards)
Now if that meets your size and speed targets : job done.
If not, explore tradeoffs to improve the failing aspects.
Reduce the resource usage
If the resource usage is too high, identify repetitive sub-operations, and serialise them, e.g. adding one bit at a time in a single bit adder. You now need n clock cycles (plus some overhead) to achieve an n-bit result. However the computation is not n times slower. To whatever extent you have shortened the combinational path, you can increase the clock speed to recover some of the lost time.
The combinational logic occupies 1/n of the area. However you need to stream one bit per cycle through it, i.e. storing your data in shift registers, and shifting one bit at a time out of them. This adds resources.
Get it right however, and intermediate results may only need one bit of storage, as they are passed on to other serial elements. Input and output registers were recommended anyway; they can be shift registers with parallel load capability adding very little to the design size.
This can be the smallest implementation of all.
Good examples of this architecture can be found in the valve (vacuum tube) architectures of about 1950, where every gate was large, power hungry and expensive. It is entirely possible to recreate similar designs in FPGA and they are absurdly small for their performance.
Increase performance
If the design is too slow, it is usually possible to break the combinational paths by inserting pipeline registers. This adds area in the form of additional registers, but (by shortening the combinational path length) allows you to increase the clock speed.
Add (for example) three pipeline registers, breaking the path into 4 equal paths, and you can increase the clock rate by 4. Any particular result will take at least as long to generate, but there are 4 results "in the pipeline" being computed in parallel - by the same amount of combinational logic! A classic example of this approach is the Pentium 4
In some FPGA architectures, you get one register per group of gates "for free", so if the combinational version uses lots of gates and no registers, the pipelined version can be (in this example) 4* as fast for no additional area.
Note that if you have to pipeline one arm of an "If" statement for performance, you would have to add a pipeline register to the other arm, to "balance" the pipeline (get results out in the same clock cycle), regardless of the "if" condition.
This is only the briefest introduction to the choices facing you, but hopefully it gives you some ideas.


text:
Q: Netsuite transaction column field recalculate I created a new transaction column field called Margin and I added it to sales orders. I wrote a script to calculate margin based on the item fields however if you go back to edit the values, the script doesn't recalculate. How do I get it to recalculate when a user edits the values?
function postSourcing(type, name){
    if(name == 'item'){
    var unitPrice = nlapiGetCurrentLineItemValue('item','rate');
    nlapiLogExecution('DEBUG', 'Price', + unitPrice);
    var itemid = nlapiGetCurrentLineItemValue('item', 'item');
    var avgCost = nlapiGetCurrentLineItemValue('item','lastpurchaseprice');
    nlapiLogExecution('DEBUG', 'Cost', + avgCost);

   var marginCalc = Math.round((((unitPrice - avgCost)/unitPrice)*100) * 10)/10;
   nlapiLogExecution('DEBUG', 'Margin', + marginCalc);
   nlapiSetCurrentLineItemValue('item','custcol9', marginCalc);
   avgCost = Math.round(avgCost * 100)/100;
   nlapiSetCurrentLineItemValue('item','lastpurchaseprice', avgCost);

   var dollarPro = unitPrice - avgCost;
   nlapiSetCurrentLineItemValue('item','custcoldollarprofit', dollarPro);

   var itemQty = nlapiGetCurrentLineItemValue('item','quantity');
   var extDollar = dollarPro * itemQty;
   nlapiSetCurrentLineItemValue('item','custcolextdollarprofit',extDollar);
   nlapiCommitLineItem('item');

   }
}

A: Are you sure that a change to the item field is firing a Post-Sourcing event? Do you see your log messages? You could try moving to Field Changed event instead just to see if that works. You could also try the Recalc event.
As an aside, I would recommend console logging on the client side instead of nlapi logging for performance reasons. Logging back to NetSuite forces an HTTP request and record creation for each log statement.

A: So, on the postSourcing event, you have two parameters: type is the internal id of the sublist that changed, and name is the internal id of the field that changed.
So in the code you pasted above:
function postSourcing(type, name){
if(name == 'item'){

You are only triggering this code to run when the 'item' field in the item sublist changes. You have two choices:
add the unit price and unit cost fields to your 'if' statement
if(name == 'item' || name == 'lastpurchaseprice' || name == 'rate')

or have it run on the entire item list
if(type == 'item')

A: Here is what I ended up with. Thanks everyone for the tips! This is now working 100%. I hope this will be able to help anyone else who is trying to do the same thing or something similar.
/*
* Author: Laura Micek
* Date: 10/20/14
* Purpose: Populates the margin, $ profit and ext. $ profit custom fields on various transaction    forms.
* Uses a postsource event for the initial values and the field change event for the recalculation of values.
*/

function postSourcing(type, name) {

if(type == 'item') {

    var unitPrice = nlapiGetCurrentLineItemValue('item','rate');
    var avgCost = nlapiGetCurrentLineItemValue('item','lastpurchaseprice');

    /* calculates margin by subtracting average cost from unit price and then dividing by average cost.
     * It is then multiplied by 100 to get the percent. Used Math.round to round to one decimal place. */
    var marginCalc = Math.round((((unitPrice - avgCost)/unitPrice)*100) * 10)/10;
    nlapiSetCurrentLineItemValue('item','custcol9', marginCalc);
    avgCost = Math.round(avgCost * 100)/100;
    nlapiSetCurrentLineItemValue('item','lastpurchaseprice', avgCost);

    var dollarPro = unitPrice - avgCost;
    nlapiSetCurrentLineItemValue('item','custcoldollarprofit', dollarPro);

    var itemQty = nlapiGetCurrentLineItemValue('item','quantity');
    var extDollar = dollarPro * itemQty;
    nlapiSetCurrentLineItemValue('item','custcolextdollarprofit',extDollar);

    }

}

function reCalc(type, name) {

/*intialized the unit price here so that I could check if it was above zero.
 If you don't check, it will try to recalculate based on zero and you will
 get a invalid percent error*/
var unitPrice = nlapiGetCurrentLineItemValue('item','rate');

//check if quantity was updated
if(name == 'quantity') {
    var unitPrice = nlapiGetCurrentLineItemValue('item','rate');
    var avgCost = nlapiGetCurrentLineItemValue('item','lastpurchaseprice');

    var dollarPro = unitPrice - avgCost;
    nlapiSetCurrentLineItemValue('item','custcoldollarprofit', dollarPro);

    var itemQty = nlapiGetCurrentLineItemValue('item','quantity');
    var extDollar = dollarPro * itemQty;
    nlapiSetCurrentLineItemValue('item','custcolextdollarprofit',extDollar);
}

//checks if the unit price was change and if the price is greater than zero
if(name == 'rate' && unitPrice > 0 ) {
    unitPrice = nlapiGetCurrentLineItemValue('item','rate');
    var avgCost = nlapiGetCurrentLineItemValue('item','lastpurchaseprice');

    /* calculates margin by subtracting average cost from unit price and then dividing by average cost.
     * It is then multiplied by 100 to get the percent. Used Math.round to round to one decimal place. */
    var marginCalc = Math.round((((unitPrice - avgCost)/unitPrice)*100) * 10)/10;
    nlapiSetCurrentLineItemValue('item','custcol9', marginCalc);
    avgCost = Math.round(avgCost * 100)/100;
    nlapiSetCurrentLineItemValue('item','lastpurchaseprice', avgCost);
    }

}


text:
Q: call a function inside innerHTML I need to call a function inside innerHTML and this is my try but it doesn't work.
category.find({}, function(err, docs) {
    docs.forEach(function(d) {
          var id = d._id
          document.getElementById('result').innerHTML += '
' + d.name + '
'
    })
})

function insert(id){
  alert(id + "Inserted")
}

Here is the HTML Part:

A: Variables in onclick attributes are evaluated in the global scope, you can't refer to local variables. You need to replace id in the string with the actual value of the id variable. You can do this with a template literal.

const docs = [{
  id: "FgrbV2NTp72ie6xj",
  name: "Joe"
}, {
  id: "agfadsfasdfq23",
  name: "Fred"
}];

docs.forEach(function(d) {
  document.getElementById('result').innerHTML += `<li onclick="insert('${d.id}')">${d.name}</li>`
});

function insert(id) {
  alert(id + " Inserted")
}

A:

const docs = [{
  id: "FgrbV2NTp72ie6xj",
  name: "Joe"
}, {
  id: "agfadsfasdfq23",
  name: "Fred"
}];
let d = document;
d.g = d.getElementById;
let res = d.g('result');

let fragment = new DocumentFragment();
let el = null;
docs.forEach(function(item) {
  el = document.createElement('li');
  el.innerText = `${item.name}`;
  el.onclick = function(){
     alert(`${item.id}` + " Inserted");
  };
  fragment.appendChild(el);
});

res.appendChild(fragment);
ul{
cursor:default;
}

While innerHTML is easy to use, according to a discussant here:

...in general, .innerHTML is for small fragments of HTML to be
  inserted and parsed into a document ..

So, instead of solving the OP's query with respect to innerHTML, this solution purposefully avoids it by utilizing DOM manipulation and at the same time makes the desired function available as a handler for an onclick event of an
 element.  To achieve this end, the code creates a document fragment object.  As a result the code is able to add the LI elements as well as the id of each one and set the onclick event-property of each in a function invoked by the docs.forEach().   Also, I added some CSS to enhance the cursor when user clicks "Joe" or "Fred".


text:
Q: Why would I use typecasting in Swift? Why would i be using typecasting in Swift?
I'm learning the language and I came across the subject of typecasting (e.g. down and upcasting etc.), but in my eyes it seems like a bit of a hassle. Why would i typecast an object? When would this be useful in real life applications or code?
I've looked on the internet for a bit but I can not seem to find a unambiguous answer. I'm really stuck with this so some help would be great!
Thanks in advance!

A: The key case here is downcasting. You would do that because you might know what type an object really is, but the compiler doesn't know, so it won't let you send that type's messages to that object.
Example:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let dest = segue.destination as? FlipsideViewController {
        dest.delegate = self
    }
}

segue.destination is typed as UIViewController; that is just a fact, and is not up to you, because a segue's destination needs to be able to be any kind of UIViewController.
Only you know that this view controller is actually a FlipsideViewController. If you don't tell the compiler that, you can't set its delegate property (a plain vanilla UIViewController has no delegate property).
So to sum up: the common downcasting situation is when a type needs to be declared as the superclass because any subclass needs to be acceptable, but then in a particular instance you know what subclass it is so you need to cast down to that.

A: Typecasting is used when you are not sure about the type of any variable or class.
Suppose a variable value is setting from the server response . And it can be of multiple object type like String , Int , Double. Then you need typecasting to know what exactly type you are looking for.


text:
Q: Java get List of maps of maps from config.yml I'm trying to create a plugin where I'm storing some Minecraft items' data along with some properties.
This is my YAML file's content:
rates:
- 391:
    mul: 10000
    store: 5000
- 392:
    mul: 9000
    store: 5000

So it's basically a list of maps of maps(I think so at least).
This is my JAVA code where I'm trying to access the key 'mul' of '391':
List<Map<?,?>> rates;
rates= getConfig().getMapList("rates");
for(Map<?,?> mp : rates){
    Map <?,?> test = (Map<?,?>) mp.get("" + item);
    player.sendMessage(test.toString());// HERE I get null pointer exception, and the following lines if this line wasn't there in the first place
    player.sendMessage("Mul is: " + test.get("mul"));
    player.sendMessage("Store is: " + test.get("store"));
}

As per suggested answer, here is my test code, where I still get NullPointerException:
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Map;

import net.sourceforge.yamlbeans.YamlException;
import net.sourceforge.yamlbeans.YamlReader;

public class Test {

public static void main(String[] args) throws FileNotFoundException, YamlException{
    YamlReader reader = new YamlReader(new FileReader("config.yml"));
    Map map = (Map) reader.read();
    Map itemMap = (Map) map.get("391");
    System.out.println(itemMap.get("mul"));//This is where I get the exception now
    System.out.println(itemMap.get("store"));
}
}

A: Parsing yaml by hand can be tedious and error prone.  It might be easier to use a library like yamlbeans.
http://yamlbeans.sourceforge.net/
package com.jbirdvegas.q41267676;

import com.esotericsoftware.yamlbeans.YamlReader;

import java.io.StringReader;
import java.util.List;
import java.util.Map;

public class YamlExample {
    public static void main(String[] args) throws Exception {

        String yamlInput =
                "rates:\n" +
                        "- 391:\n" +
                        "    mul: 10000\n" +
                        "    store: 5000\n" +
                        "- 392:\n" +
                        "    mul: 9000\n" +
                        "    store: 5000";

        YamlReader reader = new YamlReader(new StringReader(yamlInput));
        Map map = (Map) reader.read();
        // rates is a list
        List<Map> rates = (List<Map>) map.get("rates");
        // each item in the list is a map
        for (Map itemMap : rates) {
            // each map contains a single map the key is [ 391|392 ]
            itemMap.forEach((key, value) -> {
                System.out.println("Key: " + key);
                // the value in in this map is itself a map
                Map embededMap = (Map) value;
                // this map contains the values you want
                System.out.println(embededMap.get("mul"));
                System.out.println(embededMap.get("store"));
            });
        }
    }
}

This prints:
Key: 391
10000
5000
Key: 392
9000
5000

This is a simple usecase but yamlbeans also provides GSON like reflective class model population if that would be better suited for your needs.

A: Your assumptions that that YAML is a list of maps is wrong. At the top level is  is a map with a single key-value pair, the key of which is rates and the value is a sequence with two elements.
Each of those elements is mapping with a single key value pair, the key of which is a number (391, 392) and the value of which is a mapping with two key-value pairs each.
That there is a dash (-) at the left hand doesn't imply the that at the top level there is a sequence (there are no lists in a YAML file, that is construct in your programming language). If a sequence is a value for a specific key, those sequence elements can be at the same indentation level as the key, as in your YAML file.


text:
Q: Como fazer um tutorial de primeiro acesso ao site? Gostaria de criar um Tutorial de Primeiro Acesso ao meu Site, aqueles que mostram o que significa cada campo do site, preciso de uma dica de como fazer ou se existe algum Framework para este tipo de interação com o usuário, efetuei algumas pesquisas e não encontrei nada, provavelmente porque não sei o nome correto deste tipo de interação. Alguém teria alguma dica?

A: Acredito que a melhor ferramenta seja:
http://bootstraptour.com/ segue a documentação, exemplo:
var tour = new Tour({
  steps: [
  {
    element: "#my-element",
    title: "Title of my step",
    content: "Content of my step"
  },
  {
    element: "#my-other-element",
    title: "Title of my step",
    content: "Content of my step"
  }
]});

Super facil, basta conhecimento em javascript.

A: Quando se esta utilizando Bootstrap, o bootstraptour é a melhor opção como o @Guerra propos, mas caso o contrário eu recomendo o hopscotch. Com ele você define os steps com json, é bem simples:
{
      id: "welcome_tour",
      steps: [
        {
          target: "header",
          placement: "bottom",
          title: "This is the navigation menu",
          content: "Use the links here to get around on our site!"
        },
        {
          target: "profile-pic",
          placement: "right",
          title: "Your profile picture",
          content: "Upload a profile picture here."
        },
        {
          target: "inbox",
          placement: "bottom",
          title: "Your inbox",
          content: "Messages from other users will appear here."
        }
      ]
    }