text:
Q: Error decrypting message encrypted using AES/GCM/NoPadding in Android I'm currently using AES/GCM/NoPadding to perform cipher operations.
My encryption code:
fun encrypt(plainText: ByteArray, key: Key): ByteArray? {
        var resultText: ByteArray? = null
        try {
            val cipher = Cipher.getInstance(ALGORITHM)
            cipher.init(Cipher.ENCRYPT_MODE, key)

            val cipherText = cipher.doFinal(plainText)

            resultText = ByteBuffer.allocate(1 + cipher.iv.size + cipherText.size)
                    .put(cipher.iv.size.toByte())
                    .put(cipher.iv)
                    .put(cipherText)
                    .array()
        } catch (e : Exception) {
            Logger.e(TAG, "Error encrypting plain text", e)
        }

        return resultText
    }

My decryption code:
fun decrypt(cipherTextWithHeaders: ByteArray, key: Key): ByteArray? {
        var plainText: ByteArray? = null
        try {
            val cipher = Cipher.getInstance(ALGORITHM)

            val ivSize = cipherTextWithHeaders[0].toInt()
            val iv = ByteArray(ivSize)
            System.arraycopy(cipherTextWithHeaders, 1, iv, 0, ivSize)
            cipher.init(Cipher.DECRYPT_MODE, key, GCMParameterSpec(ivSize * 8, iv))

            val headerLen = 1 + ivSize

            val cipherText = ByteArray(cipherTextWithHeaders.size - headerLen)
            System.arraycopy(cipherTextWithHeaders, headerLen, cipherText, 0, cipherTextWithHeaders.size - headerLen)

            plainText = cipher.doFinal(cipherText)
        } catch (e : Exception) {
            Logger.e(TAG, "Error decrypting cipher text", e)
        }

        return plainText
    }

I get this exception while doing doFinal in decrypt method above:
javax.crypto.IllegalBlockSizeException
    at android.security.keystore.AndroidKeyStoreCipherSpiBase.engineDoFinal(AndroidKeyStoreCipherSpiBase.java:519)
    at javax.crypto.Cipher.doFinal(Cipher.java:1736)

I tried the below option during encryption:
val temp = ByteArray(12)
SecureRandom().nextBytes(temp)
cipher.init(Cipher.ENCRYPT_MODE, key, GCMParameterSpec(96, temp))

But this throws the below error:
java.security.InvalidAlgorithmParameterException: Caller-provided IV not permitted
    at android.security.keystore.KeyStoreCryptoOperationUtils.getExceptionForCipherInit(KeyStoreCryptoOperationUtils.java:85)
    at android.security.keystore.AndroidKeyStoreCipherSpiBase.ensureKeystoreOperationInitialized(AndroidKeyStoreCipherSpiBase.java:265)
    at android.security.keystore.AndroidKeyStoreCipherSpiBase.engineInit(AndroidKeyStoreCipherSpiBase.java:148)
    at javax.crypto.Cipher.tryTransformWithProvider(Cipher.java:2659)
    at javax.crypto.Cipher.tryCombinations(Cipher.java:2570)
    at javax.crypto.Cipher$SpiAndProviderUpdater.updateAndGetSpiAndProvider(Cipher.java:2475)
    at javax.crypto.Cipher.chooseProvider(Cipher.java:566)
    at javax.crypto.Cipher.init(Cipher.java:973)
    at javax.crypto.Cipher.init(Cipher.java:908)

A: The GCM auth tag length is not related to the IV length. The standard for AES-GCM is actually 12-bytes IV and 128 bits GCM tag, see RFC 5288, Section 3.
Example:
String input = "abcdef";

byte[] key = new byte[16];
(new SecureRandom()).nextBytes(key);

Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");

cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"));
byte[] ciphertext = cipher.doFinal(input.getBytes());
byte[] iv = cipher.getIV();
GCMParameterSpec gcmspec = cipher.getParameters().getParameterSpec(GCMParameterSpec.class);
System.out.println("ciphertext: " + ciphertext.length + ", IV: " + iv.length + ", tLen: " + gcmspec.getTLen());

cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), new GCMParameterSpec(128, iv));
byte[] plaintext = cipher.doFinal(ciphertext);

System.out.println("plaintext : " + new String(plaintext));

Prints:
ciphertext: 22, IV: 12, tLen: 128
plaintext : abcdef

Try changing GCMParameterSpec(ivSize * 8, iv) to GCMParameterSpec(128, iv).
Though  the issue could also be outside, i.e. the ciphertext could be badly encoded or cut off somewhere. Check cipherText.length.

java.security.InvalidAlgorithmParameterException: Caller-provided IV not permitted

That is a limitation of the Android crypto implementation; it wants to generate the IV itself during encryption.


text:
Q: Application vs Service vs Intent I am creating a project which connects to an embedded Bluetooth chip. Currently I have it set up with a separate application class which controls all the bluetooth functionality.
My program initialized with a main menu that has 9 buttons. In the main screen I create the connection to the Bluetooth device. Each button brings me to a separate Activity. Each activity needs to receive different pieces of data from the Bluetooth chip.
My question to you all is, would it make sense for me to use a service instead of an application? From what I understand of a service, it is used because there is always something running in the background. However in this case nothing needs to be running in the background ( unless keeping the connection with the Bluetooth device counts), data is only sent/received when an Activity asks for it.
Or, am I completely off track and shouldn't use either? Just a simple class to act as my data container which can be passed through intents? I know this will work, but am very new to Android and intents seem to be a bit messy. I would rather not use intents if I didn't have to.

A: I'm also building up a bluetooth connection, and i put the whole communication stuff in a service and bind to this service with every activity that needs to use the connection. This works pretty well for me. You might want to choose this way too.
Actually i earlier realised a way holding the connection in the application, but now i prefer the service way, because i'm using the application for global states.
Using service also reduces the need of intents to a very small amount :)

A: In your case a static property for the bluetooth connection would be the most pragmatic solution

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why doesn't my ng-repeat work(angularJs) I use angularjs(1.6). And I'm having a little trouble with ng-repeat. I have in my constructor an object array (with question, title...). And depending on today's date I get an object from the array using a variable. This object I want to display with ng-repeat, but I must have made a mistake I think. Nothing happens.
Here's an example of the object in the constructor:
 this.questions = [
    {
      date: '20/3',
      question: `How odl are you ?`,
      answer: { r1: '12', r2: '28', r3: '32' },
    },
    {
      date: '21/3',
      question: `What's your name? ?`,
      answer: { r1: 'Math', r2: 'Eric', r3: 'Ben' },
    },....
 ]

The variable that returns the object with the values I want to display according to the day:
var dateObj = new Date();
var month = dateObj.getUTCMonth() + 1;
var day = dateObj.getUTCDate();
const today = day + "/" + month;

this.newDates = this.questions.find(q => q.date === today)

I want to display what the newDates object contains.
And here is the html:

{{ ::newDate.question }}

I must have made a stupid mistake or maybe I can't display the data of a dynamically created object...I can't find the solution if you can help me.

A: You need to use Array.filter() which return an Array where as Array.find() object
this.newDates = this.questions.filter(q => q.date === today)

Note: If you are expect a single object keep your existing code and don't use ngRepeat just directly use

{{ ::$ctrl.newDates.question }}

A: You should be using filter instead of find.
this.newDates = this.questions.filter(q => q.date === today)


text:
Q: How do I show the line number and frame in a catch exception? I'm trying to write the line number and frame to a text file but I cannot get it to work.  From what I've read online the way I've written this should work but it's not actually outputting any line numbers making my debugging quite hard.  Can anyone assist in perhaps pointing out where my code could be wrong?
catch (Exception e)
        {
            var st = new StackTrace(e, true);
            var frame = st.GetFrame(0);
            var line = frame.GetFileLineNumber();
            var sw = new System.IO.StreamWriter(filename, true);

            sw.WriteLine(
                DateTime.Now.ToString() + "\r\n"
                + e.Message + "\r\n"
                + e.InnerException + "\r\n"
                + e.Source + "\r\n"
                + frame + "\r\n"
                + line);
            sw.Close();

        }

It does output some information just not the line / frame numbers.
Here is an example of what's getting output.
22/08/2016 08:34:24
Input string was not in a correct format.
StringToNumber at offset 12099653 in file:line:column <filename unknown>:0:0 0

Also please note the application is running in Debug not Release.

A: Make sure your application is built in DEBUG mode. If it is in Release, than some information like line numbers are not included in exception texts.
Another possible reason is that you edited Debug configuration for your project and disabled debug information (Project settings => Build => Advanced => Output debug info )
And finally you need pdb files for line numbers and they should be in same folders as your .exe / .dll. By default, they are there, until you manually remove them or copy parts of your application to another location and run there.


text:
Q: Tracking an object with a ROI around the location in the previous frame I'm working on a c++ system that tracks a drone via opencv motion detection. The problem occurs when there is a lot of untracked motion in camera sight. The system sometimes sees other motion and then thinks this is the drone that I'm trying to locate. The problem is that the drone then starts doing things it should not. So I'm trying to figure out if I can reduce the tracking field that my system won't make illogical decisions
EDITED: Is there a way to track the drone depending on a ROI around the position the drones was located in the last frame. So that my program only checks in a ROI where the drone could fly to within the time frame of 1 frame. So the tracker can not locate the drone at the other side of the camera view.


text:
Q: Explanation of generic > in collection.sort/ comparable code? I use comparable interface all the time to provided natural ordering for my class through collection.sort.
Basically if I have a person class, I will get it to implement Comparable interface and will provide the implementation of compareTo. However in the definition of Collections.sort in javadocs, I see this signature
public static <T extends Comparable<? super T>> void sort(List<T> list)

I don't understand this generics definition at all? Shouldn't it just say
<T implements Comparable<T>>

Can someone help me with this?

A: You always use extends with generics wildcards, even if the type parameter implements an interface.
If you look at a class that implements Comparable, you'll see that it actually (should) implement Comparable<T>, where T is the class itself.
It makes sense if you think about the type paramter passed to the Comparable interface and how it's used in the compareTo() method.
As PM 77-1 has eloquently pointed out, the super keyword allows for either the class, T, or one of its parents to implement Comparable.

A: Actually, it means that T can implement Comparable<? super T>, not just Comparable<T>.
For example, it means that a Student class can implement Comparable<Person>, where Student is a subclass of Person:
public class Person {}

public class Student extends Person implements Comparable<Person> {
    @Override public int compareTo(Person that) {
        // ...
    }
}

In this case, a List can be sorted by Collections.sort() but only based on Person's properties, because you pass the Student instance into compareTo() as a Person (unless you downcast it, of course).
In practice however, you'll never see a Student class implement Comparable<Person>. That's because Person will probably have implemented Comparable<Person>, and Student inherits it implementation. The end result is the same however: you can pass a List<Student> to Collections.sort() and have it sorted on Person's properties.
The difference between Comparable<T> and Comparable<? super T> is more obvious in the overloaded version of Collections.sort() that takes a Comparator<? super T>:
class ByAgeAscending implements Comparator<Person> {
    @Override public int compare(Person a, Person b) {
        return a.getAge() < b.getAge();
    }
}

List<Student> students = getSomeStudents();
Collections.sort(students, new ByAgeAscending());


text:
Q: how to get a CSSStyleSheet object from a HTMLStyleElement element Is it possible to get the CSSStyleSheet object (document.styleSheets[0]) from a HTMLStyleElement (document.createElement('style')) ?
I would like to dynamically add css rules to a not-inserted-in-the-document-yet <style> element.

A: It is possible to get a CSSStyleSheet object from a <style> element.
var style = document.createElement('style');
document.head.appendChild(style);
var styleSheet = style.sheet // Will give you the associated CSSStyleSheet

This will only work after the <style> element has been appended to the document.
Not exceptionally well documented and very difficult to find by poking around in console.

A: You can add rules before you add the style element to the document.
A couple notes-
Older IE browsers cannot add child nodes to a style element, so assign to the element's styleSheet.csstext property for them.
Make sure you append the new element to the head of the document.
function addStyle(css, media1, title1){
    var el= document.createElement('style');
    el.type= 'text/css';
    if(media1) el.media= media1;
    if(title1) el.title= title1;
    if(el.styleSheet) el.styleSheet.cssText= css;//IE
    else{
        el.appendChild(document.createTextNode(css));
    }
    //return el without the next line if you want to append it later
    return document.getElementsByTagName('head')[0].appendChild(el);

}

var cs1= [
    '#yw_psq, #yw_psq h2{background-color: green; color: white;}',
    '#yw_psq_div{margin: 1ex; position: relative; text-align: center;}',
    '#ps_counter{color: white; margin: 1ex 0 0 0; text-align: center;}',
    '#pzsq_grid  button{cursor: pointer; font-size: 1.2em; width: 100%;}',
    '#delaySpan{font-weight: bold; margin-left: 1em;}'
]

addStyle(cs1.join('\n'),'screen','yw_psq');

A: If you have access to the element to-be-inserted, you can add style info to it just like any other element. Once the element is inserted, the browser will re-flow the page and will pick up on any relevant CSS rules that apply. You don't need access to the stylesheet to style an element, you just need access to the element.


text:
Q: How to verify the toast message via appium with uiautomator2? I have write one app which include one button and it will show one toast message.
public void onClickShowToast(View view) {
    Toast.makeText(getBaseContext(), "Change port successfully", Toast.LENGTH_LONG).show();
}

And then, i write one test case with appium try to verify it.
//APPIUM Version: 1.6.3;
//JAVA: 1.8;
//JAVA Client: 5.0.0;
capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, AutomationName.ANDROID_UIAUTOMATOR2);

driver.findElementByXPath("//*[contains(@text,'Button')]").click();
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[contains(@text, 'port')]")))

But, the result is fail:

org.openqa.selenium.TimeoutException: Expected condition failed:
  waiting for presence of element located by: By.xpath:
  //*contains(@text, 'port')

A: The trick is finding the right XPath. I managed this using one of the following:
//android.widget.Toast
//android.widget.Toast[@text='toast text']

A: You can capture the toast like this:
WebElement toastView = androidDriver.findElement(By.xpath("//android.widget.Toast[1]"));
 String text = toastView.getAttribute("name");
Here is my solution.


text:
Q: Pagespeed delivers content with gzip header but not gzip content all out of nowhere? All out of nowhere our website did not longer load CSS.
The Chrome browser console showed
Error 330 (net::ERR_CONTENT_DECODING_FAILED)
With the httpie tool a similar error:
$ http "https://www.example.com/A.theme,,__dist,,_css,,_all.css,,q1669307021+typo3conf,,_ext,,_tiny_png,,_Resources,,_Public,,_Stylesheet,,_lightbox.css,,q1642153071+typo3conf,,_ext,,_example_theme,,_Resources,,_Public,,_Css,,_lazy-loading.css,,q1669307007+typo3conf,,_ext,,_theme,,_Resources,,_Public,,_Css,,_KeSearch,,_pagination.css,,q1642153071+typo3conf,,_ext[...],Mcc.Trdmt7Jhh6.css.pagespeed.cf.IAdiJ5fbh7.css"
HTTP/1.1 200 OK
Accept-Ranges: bytes
Cache-Control: max-age=31536000, public, no-transform
Connection: keep-alive
Content-Encoding: gzip
Content-Length: 161370
Content-Type: text/css
Date: Fri, 02 Dec 2022 10:37:04 GMT
Expires: Sat, 02 Dec 2023 10:37:04 GMT
Last-Modified: Fri, 02 Dec 2022 10:33:28 GMT
Server: nginx
Vary: Accept-Encoding
X-Content-Type-Options: nosniff
X-Original-Content-Length: 161410
X-Serve: Apache2

http: error: ContentDecodingError: ('Received response with content-encoding: gzip, but failed to decode it.', error('Error -3 while decompressing data: incorrect header check'))

We were able to solve this problem by
sudo touch /var/cache/mod_pagespeed/cache.flush
But we are wondering if this could happen again.
Did anybody see such a problem before?
Page speed version:
# apt show mod-pagespeed-stable
Package: mod-pagespeed-stable
Version: 1.13.35.2-r0
Priority: optional
Section: httpd
Maintainer: mod_pagespeed developers <mod-pagespeed-dev@googlegroups.com>
Installed-Size: 22,0 MB
Pre-Depends: dpkg (>= 1.14.0)
Depends: libc6 (>= 2.17), apache2
Conflicts: mod-pagespeed-beta
Replaces: mod-pagespeed-beta
Download-Size: 8.309 kB
APT-Manual-Installed: yes
APT-Sources: http://dl.google.com/linux/mod-pagespeed/deb stable/main amd64 Packages


text:
Q: Will RS 485 to RS 232 converter change the half duplex mode to full duplex mode? I am using an RS 485 serial connection through which I need to send S19 files for my boot loader project. Since it is a half duplex mode of connection, I need to toggle a dedicated pin before sending and receiving. I am using this terminal application. I got the desired output when I sent a string.
But I couldn't get any output when I try to load a file (s19 file to be specific).
Is it because of the Half-Duplex connection I use ?
Will an RS 485 to RS 232 converter change the mode from Half duplex to Full duplex ?
UPDATE
I am working on Freescale's MKE02Z64VLD2 microcontroller. I just now found out that there is no RTS CTS pin in my controller. (Check Comment Link 1)
This is the Serial connection which I use,
And the Terminal application is not a boot loader GUI, I found it in this site. (Check comment Link 2)
Thanks for helping.
I am posting the Links in the comments section because I dont have enough reputation to post more than 2 links

A: No.  A converter merely changes the electrical signalling and gives you an explicit (typically modem control line reuse) or automatic (time based) control of the transmit enable.
Adaptation to a half-duplex scheme must be made by the software at each end.
As for why exactly your setup failed, that is impossible to answer with the limited information given, however it software not written with this mode of communication in mind could be a key part of the problem.

A: At this point you should expand your question with morerdetails: what MCU board do you use, what rs485 transceiver you use (wiring), on the PC side what RS232/485 converter?
If your bootloader (PC and MCU) work in half duplex, PC sends data and waits for ACK from MCU, the MCU awaits data and after receive sends ACK, no communication in both directions ever exists. Only then you can set the terminal to use RTS on TX - this implies that the rs232/485 converter uses RTS from rs232 to enable/disable transmission on rs485 (it's a specific converter). The same has to be done on MCU, rather using toggle command use set/reset.
The success is at any time under question, if you don't have full access to patch the bootloader adding extra timeouts, hw handsake..etc. Is the terminal window on your picture a bootloader GUI?


text:
Q: Where I can find exception or error logs in magento 2? I am new to Magento. Please tell me where the errors are stored in Magento?

A:
1. After Magento Installation, you should set the developer mode by this command

php bin/magento deploy:mode:set developer
By setting Developer Mode, Errors are displayed in the browser and can be seen by users.

2. You can check the errors for var/log and var/reports folder

Errors that get in var/reports are more detailed.

3. This will display PHP errors in the browser.

You can enable display error reporting from index.php in magento root directory index.php, you can add below code after the starting of <?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

4. Enable Template Path Hints

The 'Template path hints' is a diagnostic tool that adds notation with the path on each template of Magento 2 platform, login to your Magento 2 Admin panel,
STORES > Configuration > ADVANCED > Developer > Debug >
Set Enabled Template Path Hints for Storefront, Enabled Template Path Hints for Admin, and Add Block Class types to Hints to YES.

Alternatively, you can enable template-hints directly from the terminal using a command.
php bin/magento dev:template-hints:enable
php bin/magento dev:template-hints:disable

5. Remove Cache:- Always remember to cache:flush after the changes, this will solve most of the problems and give permission to var/ folder.

chmod -R 777 var/ pub/ generated/
php bin/magento cache:clean
php bin/magento cache:flush
rm -rf var/generation/ var/view_preprocessed/ pub/static/frontend/ pub/static/_requirejs/ var/cache var/di var/page_cache pub/static/_cache

Hope it helps.

A: Logs will be presented in the following folder in magento 2,
magento_root/var/log/

Each log is intended for capturing different logs.
(or)
You can also check errors directlr in browser if you change the Magento mode to developer if it is used in local environment.Initially it will be in default mode
It can be changed in following file,
magento_root/app/etc/env.php
'MAGE_MODE' => 'developer'

A: See Magento error reports in the
var/log folder.
Generally, you can see 2 files there: system.log and exception.log.
system.log
Magento 2 runs in the production mode (not developer mode) then it does not show the actual error message on the screen, but shows a generic message: There has been an error processing your request and creates a detailed error report in the var/reports folder. You can find the error report file there by its report ID which is shown on the screen.


text:
Q: How to resolve Failed to execute goal org.apache.maven.plugins:maven-resources-plugin I am trying to run the code but I have been experienceing this below error..
Using JBOSS 4.0.5 server, Netbeans 7
could anyone please help me resolve this issue?
Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:2.5:resources (default-resources) on project plant: Error loading property file 'C:\Documents and Settings\xxxxx\My Documents\NetBeansProjects\plant\src\main\filters\${env}.properties' -> [Help 1]

To see the full stack trace of the errors, re-run Maven with the -e switch.
Re-run Maven using the -X switch to enable full debug logging.

For more information about the errors and possible solutions, please read the following articles:
[Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

A: the unresolved reference in the path you have there:
src\main\filters\${env}.properties

suggests that the maven project requires the property "env" to be set to something, possibly a *.properties file name. since youre not providing/setting this property it is left as-is and your project fails to find a file called
${env}.properties

if youre running maven from the command line you can set the property same as any java property:
mvn [your normal maven arguments] -Denv=something

if youre running it from any IDE im sure there's a way to provide the properties as well.


text:
Q: image now showing when called from database SOLVED!
so ive created an image upload page which saves the image to a folder and sends the file name to the DB, ive checked to see if they are actually being added to the DB and folder which they are, but when i call the data to another page to display the images i get broken images.
below is my code to call the images, its some code ive scraped together from various tutorials as they gave me the same problem as im having now.
UPDATE:
ive managed to get the images showing but now im faced with being shown the same image for each row of data called, the id and img_name and right for each row but the image is always the same as the first listed.
UPDATED CODE:
<?php
//connect to database
include ('connect.php');

//save the name of image in table
$query = mysql_query("select * from tbl_img") or die(mysql_error());

//retrieve all image from database and store them in a variable
while ($row = mysql_fetch_assoc($query))
{
    $img_name = $row['img'];
}
?>

<?php

include ('connect.php');

$img_id = mysql_query("SELECT * FROM tbl_img");

while ($row = mysql_fetch_assoc($img_id))
{

$id = $row['img_id'];

echo "
$id

$img_name

";

echo "

";

}

?>

A: If you start the path  of image with / you mean an absolute path where / is the DocumentRoot folder  (or the directory of virtualhost)
With src ="includes/xxx/image.png" you mean that includes is in the same folder with the php script. If it is not you can use relative path like
src="../includes/xxx/image.png"  for example

A: <?php

include ('connect.php');

$img_id = mysql_query("SELECT * FROM tbl_img");

while ($row = mysql_fetch_assoc($img_id))
{
$img_name = $row['img'];
$id = $row['img_id'];

echo "
$id

$img_name

";

echo "

";

}


text:
Q: How to set keyboard shortcuts from a script I appear to be suffering from this bug that means my custom keyboard shortcuts are lost on reboot. I have 8 custom shortcuts, and re-setting all 8 via the GUI method for setting keyboard shortcuts is tedious.
I am using 12.10 and Unity. The keyboard shortcuts I want to customise are

*

*"Shift to workspace left" (right/above/below) - with shortcut CtrlAltl (h/k/j)

*"Move window one workspace to the left" (right/up/down) - with shortcut ShiftCtrlAltl (h/k/j).

(At least those are the names I see in the keyboard shortcut dialogs.)
So until the bug is fixed, I would like to be able to run a script to set all 8 after I have logged in. So what command line program and options do I need to run to set a keyboard shortcut?

A: I think you can achieve that effect using a script like this (only deals with switching desktop, but it can be extended changing switch-to-workspace* with move-to-workspace*):
#!/bin/bash
gsettings set org.gnome.desktop.wm.keybindings switch-to-workspace-up "['<Control><Primary><Alt>k']"
gsettings set org.gnome.desktop.wm.keybindings switch-to-workspace-down "['<Control><Primary><Alt>j']"
gsettings set org.gnome.desktop.wm.keybindings switch-to-workspace-left "['<Control><Primary><Alt>h']"
gsettings set org.gnome.desktop.wm.keybindings switch-to-workspace-right "['<Control><Primary><Alt>l']"

NOTE: Maybe the <Primary> part in shortcut is redundant. Try by yourself.
To automate the process you can also make this script run at startup, using the "Startup Applications" program.


text:
Q: Confusion in selecting number of state variables Generally we take no. Of state variable equal to number of independent energy storing elements ,
let's take two examples -
1.a RC circuit with voltage source as an input ,so here we can take  different State variables but we need only 1minimum state variable ,so we generally take voltage across capicitor and with the help of this state variable and input we can calculate any possible system variable.
2.A partical of some  mass  and an input force ,so same as RC circuit ,it has only one energy storing element(mass) ,so it also requires only one state variable.
But in almost every books
why in case of mass elements (or mechanical systems in 2nd example) state variables are taken as position and velocity rather than only position?
isn't we unnecessary increasing one extra variable or there are some other reasons that I'm not aware?
When RC circuit and a single mass element is analogous then why 1st require only one minimum state variable while other require two?

A:
why in case of mass elements (or mechanical systems in 2nd example) state variables are taken as position and velocity rather than only position?

I think if you read the part of the book around 'mechanical systems', you'll find that when they have two state variables, they're doing the sums for a mass-spring system. A mass and a force is fairly uninteresting, acceleration of a mass due to gravity for instance is just a quadratic in time.
With a mass and a spring, there are two energy storage elements, and it's convenient to use position for the spring potential energy and velocity for the mass kinetic energy.

A: When we have a mass not connected to a spring, we need only one state to describe the system. A mass not connected to a spring has only one energy storing element as you rightly pointed out. Mass stores kinetic energy which is a function of velocity and not of position. Hence, we need not consider position as a state variable.
Example
A good example for not storing position as a state variable is a motor used to operate a (centrifugal) pump. We are not interested in the angular position of the motor since the rate of pumping is dependent only on the motor velocity. If you look up literature / text books where the motor state is modelled for the above purpose, only the velocity state is modelled.

But in almost every books

If you have examples of books which model only one state (velocity) please edit them into to the question. It is highly likely that the example those books mention is similar to the example above.
Reasons for adding additional states

isn't we unnecessary increasing one extra variable or there are some other reasons that I'm not aware?

Using more state variables than the minimum number are used when (not an exhaustive list)

*

*The additional state is important for the particular application

*A sensor in the system measures that state and we want to model that sensor (e.g. a motor system where the important state is velocity, but it is not directly measured; but the position is measured using an encoder and the velocity is calculated from the position measurements)

*The resulting system with additional states is easier to analyse. In optimal control (and optimisation) problems, additional slack and other (co)state variables are added to the original problem description.


text:
Q: What could cause a discrepancy between local/development and production routing in rails? Everything in my local environment works fine, but in production on heroku, ajax links which render content at vanity urls ex. /t/tags instead of /atags/1 render an error concerning a lack of id:
ActionView::Template::Error (No route matches {:action=>"show", :controller=>"atags", :id=>nil} missing required keys: [:id]):

This makes even less sense, because if I navigate into production to '/t/tags' for example, the page loads fine. So ajax at the route is broken while the same route via a regular rendered view is functional.
What could be causing this error and discrepancy between development and production environments?
I checked routes on heroku and locally and they are identical.
The js that is rendering the view is: $("#tag_posts").html("<%= escape_javascript(render @atag) %>"); So I wonder if it has something to do with @atags path being interpreted differently in production for some reason or what?
The links that are broken are being constructed by:
link_to(piece.downcase, atag_path(Atag.find_by(tag:piece[1..-1].downcase)),
:class => 'post_hashtag', :remote => true, :onclick => "location.href='#top'")

And these links constructed by that same code work fine in production minus the remote:true and :onclick => "location.href='#top'" at rendering regular pages.
    link_to(piece.downcase, atag_path(Atag.find_by(tag:piece[1..-1].downcase)),
              :class => 'post_hashtag')

And just to note again, both of these types of links work fine in development, just only the latter in production. Any insight into this oddity would be greatly appreciated!
Thanks!
EDIT: I think I've almost narrowed it down. In the atags controller in show I defined:
@atag = Atag.find_by_tag(params[:id])

Where/how would I make an equivalent definition for other views? That might solve the problem in production. Thanks!

A: Within the methods at hand piece[1..-1] is the tag and the base of the route is /t/ so changing atag_path(Atag.find_by(tag:piece[1..-1].downcase)) to "/t/" + piece[1..-1] solved the issue, as it directly passes the route as a string. Further, it's much faster than having to go back to the database to find the route.
I'm uncertain/curious why it was fine locally but not in production, though.


text:
Q: How do you prove $\lim_{n\to\infty} 1/n^{1/n}$ using only basic limit theorems? How do you prove $\lim_{n\to\infty} \frac {1}{n^{1/n}}$ using only basic limit theorems? I thought it was $0$, but my book lists the solution as $1$. How come?

A: Consider $$a_n=\frac {1}{n^{1/n}}$$ and take logarithms $$\log(a_n)=\frac 1 n \,\log(\frac 1 n)=-\frac{\log(n)}n$$ So, since $n$ varies faster then $\log(n)$, then $\log(a_n)\to 0$ and so $a_n\to 1$.

A: Hint: Use $ \lim_{n\to \infty} (a_n)^{1/n}=l $ if $\lim_{n\to \infty}\frac{a_{n+1}}{a_n}=l$

A: Method $1$: Clearly, $n^{1/n}>1$ for all $n \in \mathbb{N}$. Let $n^{1/n} = (1+a)$. We will prove that $a \to 0$ as $n \to \infty$. For $n \geq 2$, we have
$$n = (1+a)^n \geq \dfrac{n(n-1)}2a^2 \implies a^2 \leq \dfrac2{n-1}$$
Hence, as $n \to \infty$, we have $a \to 0$, which means that $n^{1/n} \to 1$.

Method $2$: From AM-GM, for $a > 1$, we have
$$\dfrac{a+a+\cdots+a+n}n \geq \sqrt[n]{na^{n-1}} \implies (1+a) - \dfrac{a}n \geq n^{1/n}a^{1-1/n}$$
Taking the limit as $n \to \infty$, we obtain
$$\lim_{n \to \infty} n^{1/n}a \leq (1+a) \implies \lim_{n \to \infty} n^{1/n} \leq 1+\dfrac1a$$
for all $a \in \mathbb{R}$. Taking the limit as $a \to \infty$, we obtain
$$n^{1/n} \leq 1$$
Further, $n^{1/n} \geq 1$ for all $n$. Hence, we have $\lim_{n \to \infty} n^{1/n}=1$.

A: $$\lim_{n\to\infty}\frac{1}{n^{\frac{1}{n}}}=\lim_{n\to\infty}n^{-\frac{1}{n}}=\lim_{n\to\infty}\exp\left(\ln\left(n^{-\frac{1}{n}}\right)\right)=\lim_{n\to\infty}\exp\left(-\frac{1}{n}\ln\left(n\right)\right)=$$
$$\lim_{n\to\infty}\exp\left(-\frac{\ln\left(n\right)}{n}\right)=\exp\left(-\lim_{n\to\infty}\frac{\ln\left(n\right)}{n}\right)=\exp\left(-\lim_{n\to\infty}\frac{\frac{\text{d}}{\text{d}n}\left(\ln\left(n\right)\right)}{\frac{\text{d}}{\text{d}n}\left(n\right)}\right)=$$
$$\exp\left(-\lim_{n\to\infty}\frac{\frac{1}{x}}{1}\right)=\exp\left(-\lim_{n\to\infty}\frac{1}{x}\right)=\exp\left(-0\right)=\exp(0)=e^0=1$$


text:
Q: Convertir string a nombre de variable Tengo un pequeño programa que funciona como una calculadora en notación posfija, entonces tengo implementado ciertas funciones trigonométricas, para ello, uso la librería math.
He generado una lista de las operaciones que quiero hacer con:
dir(math). Pero claro, mi programa después, devuelve un string con la operación que quiere realizar, por ejemplo un string cos y un valor para calcularlo. Mi pregunta es si hay alguna forma de por ejemplo pasar dicho string al nombre propio de math, por ejemplo algo como: 'math.' + 'cos'. Y de ahí pasar a que devuelva la variable de math, es posible?
Muchas gracias

A: Usa un diccionario en el que la clave sea la cadena y el valor la función del módulo math, de otro módulo o una propia creada por ti:
import math

def minimo_comun_multiplo(a, b):
    pass

operaciones = {
    "cos": math.cos,
    "acos": math.acos,
    "atan": math.atan,
    "sin": math.sin,
    "tan": math.atan,
    "sqrt": math.sqrt,
    "mcm": minimo_comun_multiplo
    }

Puedes también establecer varias cadenas o alias para una misma función si lo necesitas:
operaciones = {
    "cos": math.cos,
    "coseno": math.cos,
    ...
}

Con tu diccionario definido, solo debes usar la cadena para buscar la función correspondiente en él y directamente llamarla con los operandos correspondientes:
operacion = "sin"
operador = 45
funcion = operaciones.get(operacion)
if funcion is None:
    print("Operación no disponible")
else:
    print(funcion(operador))

Si existe la posibilidad de que se introduzcan operaciones no válidas o no disponibles usar dict.get junto a un condicional es una buena idea para solventar estos casos.
Si quieres generar el diccionario de forma automática puedes tirar del módulo inspect:
import math
import inspect

operaciones = dict(inspect.getmembers(math))

esto incluye ciertos métodos y atributos especiales que no vas a necesitar como __name__, __doc__, __file__, etc. Para no incluirlos basta con usar un condicional a la hora de generar el diccionario:
import math
import inspect

operaciones = {nombre: func for nombre, func in inspect.getmembers(math)
               if not nombre.startswith("__")}

La otra opción es usar getattr cada vez que necesitas una operación:
import math

operacion = "sin"
operador = 45

funcion = getattr(math, operacion, None)
if funcion is None:
    print("Operación no disponible")
else:
    print(funcion(operador))


text:
Q: Internet sometimes randomly pops out and won't work anymore (Except some pages) My internet connections sometimes drops randomly, and can only be fixed by restarting. When it drops, I notice a lot of ERR_CONNECTION_FAILED errors and not working connections. The weird part is that some websites (E.g. Google (always) and some other still function correctly), sometimes without the CSS (the style). Localhost seems to be down too (???) on both Wamp and Xampp. I tried to investigate this problem on Google, and have already spent several weeks to months trying to fix it. Errors I get in the event viewer are the following:

TCP/IP failed to establish an outgoing connection because the selected
  local endpoint was recently used to connect to the same remote
  endpoint. This error typically occurs when outgoing connections are
  opened and closed at a high rate, causing all available local ports to
  be used and forcing TCP/IP to reuse a local port for an outgoing
  connection. To minimize the risk of data corruption, the TCP/IP
  standard requires a minimum time period to elapse between successive
  connections from a given local endpoint to a given remote endpoint.

And

A request to allocate an ephemeral port number from the global TCP port space has failed due to all such ports being in use.

I tried resetting the winsock and firewall but it does not have any effect (Link). I am also getting Access Denied even though I'm the administrator when running netsh int ip reset reset.txt. Error log:
C:\WINDOWS\system32>netsh int ip reset reset.php
Resetting Compartment Forwarding, OK!
Resetting Compartment, OK!
Resetting Control Protocol, OK!
Resetting Echo Sequence Request, OK!
Resetting Global, OK!
Resetting Interface, OK!
Resetting Anycast Address, OK!
Resetting Multicast Address, OK!
Resetting Unicast Address, OK!
Resetting Neighbor, OK!
Resetting Path, OK!
Resetting Potential, OK!
Resetting Prefix Policy, OK!
Resetting Proxy Neighbor, OK!
Resetting Route, OK!
Resetting Site Prefix, OK!
Resetting Subinterface, OK!
Resetting Wakeup Pattern, OK!
Resetting Resolve Neighbor, OK!
Resetting , OK!
Resetting , OK!
Resetting , OK!
Resetting , OK!
Resetting , failed.
Access is denied.

Resetting , OK!
Resetting , OK!
Resetting , OK!
Resetting , OK!
Resetting , OK!
Resetting , OK!
Resetting , OK!
Restart the computer to complete this action.

I have tried to see if it was a problem with the home network, but quickly came to the conclusion that that was not the problem, as all devices work normally and this bug also affects my LocalHost.
It affects both cable and WiFi. Webpages sometimes do not load with ERR_CONNECTION_FAILED, and after about a 10 minutes it will randomly load (Not all webpages). Current connections like for example voice communications still work (E.g. Discord), but will eventually not work after switching from server for example. My taskbar (well Explorer.exe) also sometimes refreshes randomly
I have tried resetting the network, the firewall, using other WiFi USB sticks, changing IP, changing DNS, but nothing seems to work. I would not like to reset my computer.

A: My internet connections sometimes drops randomly
Try completely reinitialising all network states.
Run the following commands in an elevated cmd shell:

*

*Reset WINSOCK entries to installation defaults:
netsh winsock reset catalog

*Reset TCP/IP stack to installation defaults:
netsh int ip reset reset.log

*Reset Firewall to installation defaults:
netsh advfirewall reset

*Flush DNS resolver cache:
ipconfig /flushdns

*Renew DNS client registration and refresh DHCP leases:
ipconfig /registerdns

*Flush routing table (reboot required):
route /f


text:
Q: simple sharing code on facebook error OAuthException 104 I'm having a php website with sharing code on facebook and Sharethis buttons and script. The head tag contains the fb:app_id, og:title, og:url,og:image but debugging the URL displays the following error
  {
   "error": {
   "message": "An access token is required to request this resource.",
   "type": "OAuthException",
   "code": 104,
   "fbtrace_id": "GO7opPlWLTI"
   }
 }

The debug page displays this error
fb:app_id hasn't been included in the meta tags. Specify the app ID so that stories shared
to Facebook will be properly attributed to the app. Alternatively, app_id can be set in url
when open the share dialog. Otherwise, the default app id( 966242223397117 ) will be assigned

When I use the graph to display the page as what facebook gets I don't find the head tag at all. In php it's included in every page and the source code of my page has no errors.

A: Go to the following page:
https://www.facebook.com/insights
Then use the "Create an App" and "Add your Domain" buttons to generate the app id for your site to be included in the meta tags on your web pages.

<meta property="fb:admins" content="xxxxxxxx" />
<meta property="fb:app_id" content="yyyyyyyy" />


text:
Q: Can Anyone tell me that how we can create the custom template for particular pages in drupal8? I am beginner to Drupal-8, I don't know how to create custom template file for particular design for particular page.
For Example,
If I have created bellow pages in Drupal-8 and I want each of the page's custom template,
Like :

*

*Home

*About Us

*Services

*Contact Us

So for this how can I create custom template? Please anyone help me out to how can I achieve this?

A: Heyo!
So, Drupal page templating is managed through TWIG templates in your theme. You should first create a custom theme, which you can do following this guide:
https://www.drupal.org/docs/8/theming
Once you have a theme, you can create .twig files that will provide you with the means to control the html structure of the pages. Specific instructions are in this guide here:
https://www.drupal.org/docs/8/theming/twig/working-with-twig-templates
For example, creating a custom front page involves creating this file page--front.html.twig in your /templates folder. Different pages will require ovverides based on their name or node which is detailed in the above guide. However, it most likely is best practice to use a page.html.twig file to set a default style for the pages of your site and not have custom overrides for each node.
If you're new to twig, here's a link to twig tutorials. It's very simple and nice-and-easy to use!
https://symfonycasts.com/screencast/twig/basics

A: Drupal Website Design is Theme Based. There are plenty of themes to install in the Drupal.org. Seeing the particular theming documentation you can know how to customise your design.
You can look into some theming tutorials available in youtube also.


text: Q: Dynamically rotate text horizontally in jquery I would like to add a functionality to rotate text horizontally in jquery plugin. I found one plugin called jqueryrain but it is rotating 360 deg clock/anti-clock wise.


text:
Q: Running Ubuntu Eclipse C++ Helloworld I'm trying to run a Hello world C++ on Eclipse on Ubuntu 12.04. I installed g++ and wrote this code:
#include<vector>
#include<string>
#include <iostream>
using namespace std;
int main()
{
    cout << "Hello World" << endl;
    return 0;
}

Compile output:
**** Build of configuration Debug for project TopCoder ****

make all
make: Nothing to be done for `all'.

**** Build Finished ****

Run output message:
Launching TopCoder has encountered a problem
Error starting process

Error starting process.
Exec_tty error:Cannot run program "/media/01CCE00FA6888D80/Achieve/Eclipse/TopCoder/Debug/TopCoder": Unknown reason
Exec_tty error:Cannot run program "/media/01CCE00FA6888D80/Achieve/Eclipse/TopCoder/Debug/TopCoder": Unknown reason
Exec_tty error:Cannot run program "/media/01CCE00FA6888D80/Achieve/Eclipse/TopCoder/Debug/TopCoder": Unknown reason

when I put the source code on ext4 drive it builds and run
I changed
proc            /proc           proc    nodev,noexec,nosuid 0       0

in /etc/fstab to
proc            /proc           proc    dev,exec,suid 0       0

But no usefulness.

A: You're tring to run an application from the /media/01CCE00FA6888D80 volume. Removable USB? The most likely culprit is  noexec as an option to the default mount command line.
check if noexec is part of the options for mounting the filesystem using:
grep noexec /proc/mounts

if this results in output indicating that noexec is in effect for the file system then try:
sudo mount -o remount,exec /media/01CCE00FA6888D80

Also, if the removable volume is NTFS, your milage may vary.

A: Try to build it from the command line. Then you will know if the problem is involved with g++ or with eclipse. I guess you should change your compiler path somewhere in the eclipse, are you sure you have eclipse-cdt? THe easiest way to compile it is:

g++ yourfile.cpp

A: Your problem is that you're workspace is probably on a different drive than the one you installed ubuntu on

A: You are running you project over Linux . i  had facing same issue when my project was in my E drive  . i gave read -write permission but still  that was not enough for me . The same error was keep coming when i was trying to run the project .
I have shifted my project in my Home folder ,gave  permission  and the project ran !! .
I  believe there was a problem with some permission for LINUX  C compiler .


text:
Q: Read/interpret XML query estimation plan to get estimate rows count I'm trying to programtically get the estimated rows for a query in c#.NET
I'm setting
"SET SHOWPLAN_XML ON;";

before running a query, to get the estimation plan.
The thing returned for a simple select on one table contains a lot of data and I see that EstimateRows attribute is present 3 times in the XML.
For a query which JOINs multiple tables The EstimateRows is present even more times.
Example:
 <?xml version="1.0" encoding="UTF-8"?>
<ShowPlanXML xmlns="http://schemas.microsoft.com/sqlserver/2004/07/showplan"         Version="1.5" Build="14.0.100.430">
 <BatchSequence>
  <Batch>
     <Statements>
        <StmtSimple StatementText="SELECT COUNT(DISTINCT co.Id) FROM Campaign &#xd;&#xa;as ca JOIN KPI_EmailOpened as eo ON eo.CampaignId = ca.Id JOIN Contact&#xd;&#xa; AS co ON co.Id = eo.ContactId &#xd;&#xa;WHERE co.FirstName = &apos;John&apos;" StatementId="1" StatementCompId="1" StatementType="SELECT" RetrievedFromCache="false" StatementSubTreeCost="2.98809" StatementEstRows="1" SecurityPolicyApplied="false" StatementOptmLevel="FULL" QueryHash="0x5E01ED198558D453" QueryPlanHash="0xBD8133A97EEAAC2C" CardinalityEstimationModelVersion="130">
           <StatementSetOptions QUOTED_IDENTIFIER="true" ARITHABORT="true" CONCAT_NULL_YIELDS_NULL="true" ANSI_NULLS="true" ANSI_PADDING="true" ANSI_WARNINGS="true" NUMERIC_ROUNDABORT="false" />
           <QueryPlan NonParallelPlanReason="EstimatedDOPIsOne" CachedPlanSize="48" CompileTime="9" CompileCPU="9" CompileMemory="816">
              <MemoryGrantInfo SerialRequiredMemory="3072" SerialDesiredMemory="3104" />
              <OptimizerHardwareDependentProperties EstimatedAvailableMemoryGrant="17616030" EstimatedPagesCached="1101001" EstimatedAvailableDegreeOfParallelism="1" MaxCompileMemory="4603408" />
              <RelOp NodeId="1" PhysicalOp="Compute Scalar" LogicalOp="Compute Scalar" EstimateRows="1" EstimateIO="0" EstimateCPU="1e-007" AvgRowSize="11" EstimatedTotalSubtreeCost="2.98809" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row">
                 <OutputList>
                    <ColumnReference Column="Expr1003" />
                 </OutputList>
                 <ComputeScalar>
                    <DefinedValues>
                       <DefinedValue>
                          <ColumnReference Column="Expr1003" />
                          <ScalarOperator ScalarString="CONVERT_IMPLICIT(int,[globalagg1005],0)">
                             <Convert DataType="int" Style="0" Implicit="1">
                                <ScalarOperator>
                                   <Identifier>
                                      <ColumnReference Column="globalagg1005" />
                                   </Identifier>
                                </ScalarOperator>
                             </Convert>
                          </ScalarOperator>
                       </DefinedValue>
                    </DefinedValues>
                    <RelOp NodeId="2" PhysicalOp="Stream Aggregate" LogicalOp="Aggregate" EstimateRows="1" EstimateIO="0" EstimateCPU="1.1e-006" AvgRowSize="15" EstimatedTotalSubtreeCost="2.98809" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row">
                       <OutputList>
                          <ColumnReference Column="globalagg1005" />
                       </OutputList>
                       <StreamAggregate>
                          <DefinedValues>
                             <DefinedValue>
                                <ColumnReference Column="globalagg1005" />
                                <ScalarOperator ScalarString="SUM([partialagg1004])">
                                   <Aggregate Distinct="0" AggType="SUM">
                                      <ScalarOperator>
                                         <Identifier>
                                            <ColumnReference Column="partialagg1004" />
                                         </Identifier>
                                      </ScalarOperator>
                                   </Aggregate>
                                </ScalarOperator>
                             </DefinedValue>
                          </DefinedValues>
                          <RelOp NodeId="3" PhysicalOp="Hash Match" LogicalOp="Aggregate" EstimateRows="1" EstimateIO="0" EstimateCPU="0.00188442" AvgRowSize="15" EstimatedTotalSubtreeCost="2.98809" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Batch">
                             <OutputList>
                                <ColumnReference Column="partialagg1004" />
                             </OutputList>
                             <MemoryFractions Input="1" Output="1" />
                             <Hash>
                                <DefinedValues>
                                   <DefinedValue>
                                      <ColumnReference Column="partialagg1004" />
                                      <ScalarOperator ScalarString="COUNT(*)">
                                         <Aggregate Distinct="0" AggType="COUNT*" />
                                      </ScalarOperator>
                                   </DefinedValue>
                                </DefinedValues>
                                <HashKeysBuild />
                                <RelOp NodeId="5" PhysicalOp="Nested Loops" LogicalOp="Left Semi Join" EstimateRows="10934.3" EstimateIO="0" EstimateCPU="0.0457056" AvgRowSize="9" EstimatedTotalSubtreeCost="2.98609" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row">
                                   <OutputList />
                                   <NestedLoops Optimized="0" WithUnorderedPrefetch="1">
                                      <OuterReferences>
                                         <ColumnReference Database="[mydb]" Schema="[dbo]" Table="[Contact]" Alias="[co]" Column="Id" />
                                         <ColumnReference Column="Expr1013" />
                                      </OuterReferences>
                                      <RelOp NodeId="7" PhysicalOp="Index Seek" LogicalOp="Index Seek" EstimateRows="10934.4" EstimatedRowsRead="10934.4" EstimateIO="0.0601111" EstimateCPU="0.0121848" AvgRowSize="19" EstimatedTotalSubtreeCost="0.0722959" TableCardinality="1e+007" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row">
                                         <OutputList>
                                            <ColumnReference Database="[mydb]" Schema="[dbo]" Table="[Contact]" Alias="[co]" Column="Id" />
                                         </OutputList>
                                         <IndexScan Ordered="1" ScanDirection="FORWARD" ForcedIndex="0" ForceSeek="0" ForceScan="0" NoExpandHint="0" Storage="RowStore">
                                            <DefinedValues>
                                               <DefinedValue>
                                                  <ColumnReference Database="[mydb]" Schema="[dbo]" Table="[Contact]" Alias="[co]" Column="Id" />
                                               </DefinedValue>
                                            </DefinedValues>
                                            <Object Database="[mydb]" Schema="[dbo]" Table="[Contact]" Index="[IX_Contact_FirstName]" Alias="[co]" IndexKind="NonClustered" Storage="RowStore" />
                                            <SeekPredicates>
                                               <SeekPredicateNew>
                                                  <SeekKeys>
                                                     <Prefix ScanType="EQ">
                                                        <RangeColumns>
                                                           <ColumnReference Database="[mydb]" Schema="[dbo]" Table="[Contact]" Alias="[co]" Column="FirstName" />
                                                        </RangeColumns>
                                                        <RangeExpressions>
                                                           <ScalarOperator ScalarString="&apos;John&apos;">
                                                              <Const ConstValue="&apos;John&apos;" />
                                                           </ScalarOperator>
                                                        </RangeExpressions>
                                                     </Prefix>
                                                  </SeekKeys>
                                               </SeekPredicateNew>
                                            </SeekPredicates>
                                         </IndexScan>
                                      </RelOp>
                                      <RelOp NodeId="8" PhysicalOp="Index Seek" LogicalOp="Index Seek" EstimateRows="1" EstimatedRowsRead="30.0011" EstimateIO="0.003125" EstimateCPU="0.000190001" AvgRowSize="9" EstimatedTotalSubtreeCost="2.86809" TableCardinality="2.95e+008" Parallel="0" EstimateRebinds="10933.4" EstimateRewinds="0" EstimatedExecutionMode="Row">
                                         <OutputList />
                                         <IndexScan Ordered="1" ScanDirection="FORWARD" ForcedIndex="0" ForceSeek="0" ForceScan="0" NoExpandHint="0" Storage="RowStore">
                                            <DefinedValues />
                                            <Object Database="[mydb]" Schema="[dbo]" Table="[KPI_EmailOpened]" Index="[KPI_EmailOpened_NCIDX_ContactCampaign]" Alias="[eo]" IndexKind="NonClustered" Storage="RowStore" />
                                            <SeekPredicates>
                                               <SeekPredicateNew>
                                                  <SeekKeys>
                                                     <Prefix ScanType="EQ">
                                                        <RangeColumns>
                                                           <ColumnReference Database="[mydb]" Schema="[dbo]" Table="[KPI_EmailOpened]" Alias="[eo]" Column="ContactId" />
                                                        </RangeColumns>
                                                        <RangeExpressions>
                                                           <ScalarOperator ScalarString="[mydb].[dbo].[Contact].[Id] as [co].[Id]">
                                                              <Identifier>
                                                                 <ColumnReference Database="[mydb]" Schema="[dbo]" Table="[Contact]" Alias="[co]" Column="Id" />
                                                              </Identifier>
                                                           </ScalarOperator>
                                                        </RangeExpressions>
                                                     </Prefix>
                                                  </SeekKeys>
                                               </SeekPredicateNew>
                                            </SeekPredicates>
                                         </IndexScan>
                                      </RelOp>
                                   </NestedLoops>
                                </RelOp>
                             </Hash>
                          </RelOp>
                       </StreamAggregate>
                    </RelOp>
                 </ComputeScalar>
              </RelOp>
           </QueryPlan>
        </StmtSimple>
     </Statements>
  </Batch>

most of them show 1 as estimation, except two which are very close to the actual result:(around 10500 rows)
<RelOp NodeId="5" PhysicalOp="Nested Loops" LogicalOp="Left Semi Join" EstimateRows="10934.3" EstimateIO="0" EstimateCPU="0.0457056" AvgRowSize="9" EstimatedTotalSubtreeCost="2.98609" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row">
and
<RelOp NodeId="7" PhysicalOp="Index Seek" LogicalOp="Index Seek" EstimateRows="10934.4" EstimatedRowsRead="10934.4" EstimateIO="0.0601111" EstimateCPU="0.0121848" AvgRowSize="19" EstimatedTotalSubtreeCost="0.0722959" TableCardinality="1e+007" Parallel="0" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row">
I'm trying to find articles on how to read these values but couldn't find much.
Can you tell or point me to some articles which explain how to read this XML and how to get the estimated row count for any query?

A: As you do a count I think the 1 is the correct one for returning the number of records. This is also node 1 which is the aggregate/last step of the execution plan (you read them frm right to left). The other nodes are intermediate nodes with intermediate results (like the 10500) that are the basis for the count.


text:
Q: What do different bracket optional argument notations mean on MDN This is very trivial, but I like to know why things are the way they are.
I'm doing my best at writing js documentation for my apps and so I am using the jsDoc conventions and referring to MDN as a guide and bla bla bla but my question regards how the documentation is written on the MDN reference.
Take two simple methods:
console.log() and Math.min() and their syntax documented on MDN
console.log(obj1 [, obj2, ..., objN]);
console.log(msg [, subst1, ..., substN]);

Math.min([value1[, value2[, ...]]])

If I understand correctly console.log says, I require the first argument and the rest are optional. The optional arguments are indicated with a bracket + comma "[," whereas a required argument would be indicated with just a comma ",".
In addition, to refer to many arguments, the documentation is written as, "subst1, ..., substN".
Looking at Math.min this is very similar and obviously different, but why? I understand the first arg in Math.min is optional (returns Infinity) and in console.log it is not optional (you would get undefined). If I understand the syntax correctly the syntax for Math.min could be written as,
Math.min([value1, ..., valueN])

stating that ALL arguments are optional and that the method accepts zero or many arguments, but instead we get brackets around every argument.
Is there a reason for the difference in how the documentation is written and if so please explain what that difference is.

A: Actually I was always convinced that syntax fn(a, [b, c, d]) means that you can only use either fn(a) or fn(a, b, c, d).
But anyway, console.log and Math.min behave exactly the same way - they process all the arguments. There is no error if you provide zero arguments to either function. This is what I get in the console:
> Math.min()
Infinity
> console.log()
(nothing to output)

Also, return value of console.log is independent on the parameters - always undefined:
console.log()==console.log(666) //true


text:
Q: python locate items in lists of list and 'float' object is not subscriptable I'm trying to locate items in lists of list and use the items to do calculation. But TypeError: 'float' object is not subscriptable occurred.
Here's the question/lists:
history_lists=[[1,2,3,4],[2,3,1],[5,8,0,1]]

I want to locate the last two item in each list in history_lists, and calculate the average.
Here's my codes:
def get_question(self):

    combined_lists_history.append(var1)
    combined_lists_history.append(var2)

    history_lists = [[] for _for _ in range(max(combined_lists_history[1::2]))]

    for i in range(1, len(combined_lists_history),2):
           history_lists[combined_lists_history[i]-1].append(combined_lists_history[i-1])

 # this codes are for recreating a list of lists
 # combined_lists_history = [1,**1**,3,**1**,5,**3**,4,**1**,2,**2**,3,**2**,1,**2**,8,**3**,0,**3**,1,**3**,2,**1**,]
 # history_lists=[[1,2,3,4],[2,3,1],[5,8,0,1]]

def get_avg(self):

    for i, lst in enumerate(history_lists):
           (history_lists[i][-1] + history_lists[i][-2])/2.0
          # for each list in history_lists, retrieve last two item

A: You can achieve this succinctly with a list comprehension:
history_lists=[[1,2,3,4],[2,3,1],[5,8,0,1]]
averages=[(history_list[-1] + history_list[-2]) / 2.0 for history_list in history_lists]

Your error was likely because whatever is calling your function is expecting a list to be returned but since you're using return in your loop it's instead receiving a single float. This will be fixed by simply returning the averages list as generated above.
Edit: Added missing parentheses

A: Using your style, instead of more Pythonic approaches:
history_lists=[[1,2,3,4],[2,3,1],[5,8,0,1]]
averages = []

# Don't use "list" as a variable name since that's a keyword
for lst in history_lists:
    avg = (lst[-1] + lst[-2]) / 2.0
    averages.append(avg)

print averages

Alternatively, if you want all of them averaged:
history_lists=[[1,2,3,4],[2,3,1],[5,8,0,1]]
total_count = 0
total_sum = 0

for lst in history_lists:
    total_count += 2.0
    total_sum += lst[-1] + lst[-2]

total_average = total_sum / total_count

print total_average

A: i think you want to do something more along these lines...
average = 0
for list in history_lists:
    final += (list[-1] + list[-2])/2
print average


text:
Q: Avoiding email being marked as spam when sent through gmail mail server Hi all (before closing based on the title, please read the bottom parragraph),
I'm having some small issues with emails being sent out from the C#/ASP.Net webapp that I'm currently developing.
We don't send emails out on mass, only to a single address, sometimes with a CC address.
The emails we are sending out contain one attached file, which is a single page PDF file (They are actually invoices in PDF format).
It's happened a couple of times that our emails have been flagged as spam. The content of the email is HTML without any images, and the HTML itself is not very complicated at all (Simply 4 p tags and an a tag with a mail to).
We have a company domain set up using the Gmail smtp server, and the email account with we use to send this email is called automated.emailer.
When created the System.Net.MailMessage, I am adding a simple name to the which is "XXX invoicing" (XXX is substituting our company name) using the MailAddress constructor which takes a display name, a replyto address of Invoicing@example.com and the from address is automated.emailer@example.com. The content has been checked against many sp
These emails are fairly important, so we need to do all we can to avoid them being caught as spam. I would appreciate any ideas on why these emails would be considered spam? It may be that, in order to make sure the IP of our domain matches the IP of the mail server, we need to install an exchange. This seems like a strong approach and I'd be keen to see if anyone has solved this problem in another way.
I have tried to ask this question with as much info as possible, to avoid this question being closed, since i've seen many questions regarding email spam closed with a reference to the below question, which I read, but didn't find an answer to my question.
How do you make sure email you send programmatically is not automatically marked as spam?

A: Probably better on superuser.com rather than here. But have you tried looking at SPF records? Might boost your credibility to spam filters.

A: I use the free service over at Port25. You send an email to their verifier address and get a reply with a pretty detailed breakdown of your ham score:
http://www.port25.com/support/authentication-center/email-verification/


text:
Q: Django query by related object with calculated value I have this Class structure:
class A(models.Model):
    pass

class B(models.Model):
    CHOICE_1 = 'example-1'
    CHOICE_2 = 'example-2'
    CHOICE_3 = 'example-3'
    EXAMPLE_CHOICES = [
        (CHOICE_1, 'Example 1'),
        (CHOICE_2, 'Example 2'),
        (CHOICE_3, 'Example 3')
    ]

    choice = models.CharField(max_length=20, choices=EXAMPLE_CHOICES)
    important = models.BooleanField()
    parent = models.ForeignKey(A, on_delete=models.CASCADE, related_name="child")

I need to get all A objects that have related B objects filter by:

*

*At least one child have important=True

*At least one child have CHOICES_1 or CHOICE_2 in choice attr.

So far the query would be:
A.objects.filter(child__important=True, child__choice__in=[CHOICE_1, CHOICE_2])

HERE IT COMES THE QUESTION
Also, I need to get an extra calculated field which value should be:

*

*If A has only CHOICE_1 childs --> calculated value = "Example 1 only"

*elif A has only CHOICE_2 childs --> calculated value = "Example 2 only"

*elif A has childs, some CHOICE_1 and some CHOICE_2 --> calculated value = "Both"
Requirements:

*

*Django 2.2

*Using single query


text:
Q: How to emulate the array_join() method in spark 2.2 For example, if I have a dataframe like this:
|sex|        state_name| salary| www|
|---|------------------|-------|----|
|  M|   Ohio,California|    400|3000|
|  M|           Oakland|     70| 300|
|  M|DF,Tbilisi,Calgary|    200|3500|
|  M|            Belice|    200|3000|
|  m|    Sofia,Helsinki|    800|7000|

I need to concatenate as a String the comma separated values in the "state_name" column with a delimiter specified by me. Also, I need to put a string at the end and the beginning of the generated string (the opposite of a strip() method or function).
For example, if I want an output like this:
|cool_city                       |
|--------------------------------|
|[***Ohio<-->California***]      |
|[***Oakland***]                 |
|[***DF<-->Tbilisi<-->Calgary***]|
|[***Belice***]                  |
|[***Sofia<-->Helsinki***]       |

The solution that I've already coded with Spark 3.1.1 is this:
    df.select(concat(lit("[***"),
    array_join(split(col("state_name"),","),"<-->"),lit("***]")).as("cool_city")).show()

The problem is that the computer where this will be running is using Spark 2.1.1 and the array_join() method isn't supported in this version (it's a pretty big project and upgrading the  Spark version isn't over the table). Im pretty new using scala/spark and I don't know if there's another function that could help me emulating the array_join() use or if someone knows where to find the way to code a UDF with the same usefulness.
I would greatly appreciate your help!

A: I don't know Scala, but try this:
df.select(concat(lit("[***"),
                 concat_ws("<-->", split(col("state_name"), ",")),
                 lit("***]")).as("cool_city")).show()

UPDATE
Avoiding column split:
df.select(concat(lit("[***"),
                 regexp_replace(col("state_name"), ",", "<-->"),
                 lit("***]")).as("cool_city")).show()


text:
Q: Writing a function with arguments that indicate what function to apply Is there a way to write a function in which one of the arguments indicates what function to apply?
For example, if I have a function:
mf = function(data, option, level)

where I want option to tell whether to calculate the mean, median or sd of a data set?

A: Yes, one option is to just pass a function to option. E.g.
mf <- function(data, option) {
    option <- match.fun(option)
    option(data)
}

set.seed(42)
dat <- rnorm(10)
mf(dat, option = mean)

Which gives:
> set.seed(42)
> dat <- rnorm(10)
> mean(dat)
[1] 0.5472968
> mf(dat, option = mean)
[1] 0.5472968
> sd(dat)
[1] 0.8354488
> mf(dat, option = sd)
[1] 0.8354488

match.fun() is the standard R way of matching to an available function. In the example I pass the function itself, but match.fun() allows other ways of referring to a function, for example as a character string:
> mf(dat, option = "mean")
[1] 0.5472968

match.fun() returns a function that can be used as any other function, hence option() is a function that is essentially the same as the function passed to the option argument or is the function named in the option argument.
It isn't clear how the level argument was supposed to be used to I have ignored that above.
I should probably add that if you want to pass in any arguments to the applied function then you'll want to use ... in the function definition, e.g.:
mf <- function(data, option, ...) {
    option <- match.fun(option)
    option(data, ...)
}

Hence we can do things like this
set.seed(42)
dat2 <- rnorm(10)
dat2[4] <- NA
mean(dat2)
mean(dat2, na.rm = TRUE)
mf(dat2, mean, na.rm = TRUE)

the last three lines giving
> mean(dat2)
[1] NA
> mean(dat2, na.rm = TRUE)
[1] 0.5377895
> mf(dat2, mean, na.rm = TRUE)
[1] 0.5377895

A: There is a bit of a problem in that "data set" in R usually means a dataframe and there is no median.data.frame so you need to use both lapply and do.call:
  df <- data.frame(x=rnorm(10), y=rnorm(10))
 mf = function(data, option="mean") {lapply( data,
                                       function(col) do.call(option, list(col))) }
 mf(df)
#-------------
$x
[1] 0.01646814

$y
[1] 0.5388518

You did not indicate what "level" was supposed to do, so I left it out of the equation,
> mf(df, sd)
$x
[1] 1.169847

$y
[1] 0.8907117


text:
Q: Google Spreadsheet Arrayformula with IF and AND condition I need some help with google spreadsheet. I tried everything but somehow I am not able to figure out how to solve this.
I have 5 columns, 4 of them are "Blue, Yellow, Green and White" and the other is "Result"
In the Result it should contain the value from the other columns but with some conditions.
In the screenshot I entered the Results manually. I tried everything I am capable of like Arrayforumula(Ifs(and(CONDITIONS)) etc but not working. I spend literally 10h and would really appreciating any help. is that even possible?
Example: https://i.stack.imgur.com/ifpzK.png

A: The following formula in E2 will produce all the required results in the 'Result' column:
=arrayformula(if(mmult(n(istext(B2:D10)),{1;1;1})=0,A2:A10,substitute(trim(transpose(query(transpose(B2:D10),,9^9)))," ","+")))

Making this work with infinite ranges would need more work. It also might not work as expected if both the 'Blue' column and the other three are blank in a given row (I think) - you didn't define this as a possibility.


text:
Q: iReport: Passing parameters from a main report query to a dataset query for a table or list I understand how to pass parameters from a main report to a subreport, since there's a specific field for this in the subreport object. However, I'd like to do the same thing with a table or list object as a consumer (rather than a subreport). Is it possible?
For example, say I have a parameter of 'customerID' that I can populate with a main report query, but I can't seem to pass this parameter to the table's dataset's SQL query.
I've tried, and continue to try, various combinations of parameters, fields, and variables, but to no avail.
Does this sort of thing require a subreport implementation?
(If it matters and isn't obvious, I'm using JDBC)

A: To pass the parameters from main report to the table or list datasources in the iReport 3.6.7+, you need to do following steps:
1) create required parameters in the main report by right clicking on the parameters section of main report------> add parameter-------->set the properties (data type) of newly added parameter to your desired one.
2) create equivalent parameters in the table/List's data source's parameters section exactly as in step 1.
3) from report explorer, right click on the table and click on Edit Table DataSet ------> Select the parameters tab ----------->Click on add ---------->Choose the parameter (which you created in the dataset's parameter section in step 1) from upper combo (i.e. Dataset parameter name) ------> then click on lower button (i.e.) assign value expression i.e. the params which you added in step 1.
source : http://hamroblog-sristi.blogspot.fr/2011/04/passing-parameters-from-main-report-to.html

A: Don't know what version you are using, but I was able to do it in iReport 3.7.6.
First I add the parameters to the dataset.
Then, to pass the values to the parameters, right-click on the Table in Report Inspector, choose "Edit table datasource".  Go to "Parameters" tab.  Each dataset parameter can take its value from parameter, field, or variable from the main report.

A: I make a quick test report to replicate what you were doing and it worked.
Here are the steps I took.

*

*Create a parameter in your report e.g. customerID

*Pass it to your main report in a hashmap.
hashmap.put("customerID", "12345");

*In the report set the property The language of for the dataset query to SQL.

*Set the property Query text to something similar as is bellow.
select * from * customers c where c.ID=$P{customerID}

A: To pass the parameters from main report to the table or list datasources in the iReport upper version we need to do following steps:

*

*create required parameters in the main report by right clicking on the parameters section of main report------> add parameter-------->set the properties (data type) of newly added parameter to your desired one.

*create equivalent parameters in the table/List's data source's parameters section exactly as in step 1.

*from report explorer, right click on the table and click on Edit Table DataSet ------> Select the parameters tab ----------->Click on add ---------->Choose the parameter (which you created in the dataset's parameter section in step 2.) from upper combo (i.e. Dataset parameter name) ------> then click on lower button (i.e.) assign value expression i.e. the params which you added in step 1.


text:
Q: Let $X$ be a compact Hausdorff space. Let $\mathcal{A}$ be a collection of properly .. let $X$ be a compact Hausdorff space. Let $\mathcal{A}$ be a collection of closed connected subsets of $X$ that is simply ordered by proper inclusion. Then
\begin{equation*}
Y = \bigcap_{A \in \mathcal{A}} A
\end{equation*}
is connected.
Follow the hint : If $C \cup D$ is a separation of $Y$, then choose disjoint open sets $U$ and $V$ of $X$ containing $C$ and $D$ respectively and show that:
\begin{equation*}
\bigcap_{A \in \mathcal{A}} (A - (U \cup V))
\end{equation*}
is not empty.
I checked the proof and I'm quoting it:

Just follow the hint. $Y$ is closed. Therefore, both sets $C$ and $D$ are closed in $X$ . Since $X$ is compact, they are compact as well, and, by exercise 5, since $X$ is also Hausdorff, there are open and disjoint $U$ and $V$ containing them. $A−U−V$ are closed, nonempty (otherwise, since $U$ and $V$ are disjoint and both contain a point of $Y$ , there would be a separation of $A$ , which is connected) and nested (here we use the fact that the initial sequence is nested, otherwise the result would not hold), therefore, since $X$ is compact, the intersection is nonempty. That implies that there is a point in $Y$ that is not in $U \cup V$ and, therefore, not in $C \cup D$ . Contradiction.

Bold parts are the parts I couldn't get
B1: Y is closed I get that, $C$ and $D$ are open in $Y$ (by definition of seperation). But that doesn't make $C$ and $D$ closed in $X$ ? By the subspace definition they are actually OPEN in $X$
B2: I don't know how that conclusion was reached.
B3 : Is $Y \subset U \cup V$ ?
Thanks..

A: $U$ and $V$ are disjoint and open in $Y$ and $U \cup V = Y$. This is what a separation of a set/subspace is commonly defined as.
So $U$ is the complement of an open set in $Y$ so $U$ is closed in $Y$ and as $Y$ is closed in $X$, $U$ is also closed in $X$. The same reasoning holds for $V$.
The $A \in \mathcal{A}$ are nested,so the sets $A \setminus (U \cup V)$ (which your proof's notation denotes as $A - U - V$) are also nested, as we just remove a fixed set from a nested family. If $A_1, A_2 \in \mathcal{A}$ then $A_1 \subseteq A_2$ or $A_2 \subseteq A_1$ (def. of nested) and so  $A_1 \setminus (U \cup V) \subseteq A_2 \setminus (U \cup V)$ or vice versa, depending on which one was true. These sets $A \setminus (U \cup V)$ are non-empty, as $U \cup V = Y = \bigcap \mathcal{A} \subseteq A$, and if the difference were empty , $U$ and $V$ (intersected with $A$) would form a separation of $A$, which cannot happen, as $A$ is connected.


text:
Q: Connecting to mysql database in php I am trying an example tutorial for AJAX suggest from here. I found an issue in the database.php file. it containts a code segment like this.
function db_connect($server = 'localhost', $username = 'root', $password = '123', $database = 'db_ajax_suggest', $link = 'db_link') {
    global $$link;

    $$link = mysql_connect($server, $username, $password);

    if ($$link) mysql_select_db($database);

    return $$link;
  }

My question is what is $link = 'db_link' in the code. I have worked with php before, but not a lot, I have not met a situation like this. All needed were $servername, $username, $password.
I am a java person more than PHP. In java I can use jdbc:mysql://localhost:3306/db_ajax_suggest.
But in this case, Hoe should set the database url?
Thank you!!

A: I think Only this much you needed to connect to your databases and work with your tables
$connect = mysql_connect('localhost','root','123');
if (!$connect) {
die('Could not connect to MySQL: ' . mysql_error());
}
mysql_select_db('db_ajax_suggest',$connect);

and for fetching data from table
$query = " your query ";
mysql_query($query) or die('SQL ERROR:'.mysql_error());

A: Write
mysql_connect($server, $username, $password) or die(mysql_error());

and for DB
mysql_select_db($database) or die(mysql_error());

and for your queries
mysql_query($q) or die(mysql_error());

I find nothing better solution than this.

A: mysql_connect can have four paramter.
like this
mysql_connect($server,$user,$pwd,$newlink,$clientflag)

In my my first three you already know. You might have confusiong about $newlink and $clientflag
$newlink= Return bool value means TRUE or FALSE.
Usage: If the connection is called again in the script. now new conection will be created. if its set to TRUE.
clientflag The client_flags parameter can be a combination of the following constants: 128 (enable LOAD DATA LOCAL handling), MYSQL_CLIENT_SSL, MYSQL_CLIENT_COMPRESS, MYSQL_CLIENT_IGNORE_SPACE or MYSQL_CLIENT_INTERACTIVE. Read the section about MySQL client constants for further information. In SQL safe mode, this parameter is ignored. **according to the php manual**
Check these link for further info
http://php.net/manual/en/function.mysql-connect.php
http://php.net/manual/en/mysql.constants.php#mysql.client-flags
Important Note: Please learn mysqli or PDO


text:
Q: How to select only text of h2 tag ignoring the other html tags I has as  tag For example Anirban bhattacharjee5.I want only the text of h2 tag like Anirban Bhattacharjee through jquery.I give  a try but it returns Anirban Bhattacharjee5.

anirban bhattacharjee5

Mycode
var name=$(".client_details h2").text()

A: You need to get the textnode of h2 and ignore the rest using:
$('.client_details h2').contents().filter(function() {
  return this.nodeType === 3; //Node.TEXT_NODE
}).text();

Working Demo

A: .contents() is the method you are looking for. You can use it like below:

var h2 = $("h2").contents()[0];

console.log(h2);

anirban bhattacharjee5

so you can use:
var h2 = $(".client_details h2").contents()[0];

A: Use this:
$(".client_details").find("h2").contents()[0]

The above line will return you "anirban bhattacharjee"


text:
Q: Dataframe rows and column calling
I don't understand the error in the picture. Is this the correct ways to acess rows? Then how do you acess columns?

A: Here, you need .loc for accessing, something like below:
df.loc['Row 1']

You can view details in documentation of loc.


text:
Q: Models don't show up in the django admin My model does not show up in the Django admin.
I don't understand this. I have been doing this several times before:
from django.contrib import admin
from djntra.models import Thing

class ThingAdmin(admin.ModelAdmin):
    pass

admin.register(Thing, ThingAdmin)

I have no clue what's going on.

A: There was a typo in my code. You need to use admin.site.register(). The site was missing.
This works:
from django.contrib import admin
from djntra.models import Thing

class ThingAdmin(admin.ModelAdmin):
    pass

admin.site.register(Thing, ThingAdmin)


text:
Q: Use Kendo UI switch in a web application I am trying to use a Kendo mobile widget - switch in my web application as below:

<input id="btnConvert" type="checkbox" onclick="onChange();" />

 $(document).ready()
    {
        $("#btnConvert").kendoMobileSwitch({
            onLabel: "UK",
            offLabel: "US"
        });
    }
    function onChange(e) {
        alert(e.checked);//true of false
    }

But its not firing the click event. i tried the onchange event which is also not working.
Also i tried
    $('input:checkbox').change(function () {
}

but no success...

A: Define a change handler event in your switch definition.
$("#btnConvert").kendoMobileSwitch({
    onLabel: "UK",
    offLabel: "US",
    change : function (e) {
        alert("You changed the value");
    }
});

See the documentation here.


text:
Q: TypeError when using Google Vision API in Firebase Cloud Functions I'm trying to get a sample for the use of the Google Vision API within Firebase Cloud Functions to work but it fails.
I'm using the unmodified sample provided on Github: https://github.com/firebase/functions-samples/tree/master/moderate-images
EDIT:
Here is my source file:

/**
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for t`he specific language governing permissions and
 * limitations under the License.
 */
'use strict';

const functions = require('firebase-functions');
const mkdirp = require('mkdirp-promise');
const gcs = require('@google-cloud/storage')();
const vision = require('@google-cloud/vision')();
const spawn = require('child-process-promise').spawn;
const path = require('path');
const os = require('os');
const fs = require('fs');

/**
 * When an image is uploaded we check if it is flagged as Adult or Violence by the Cloud Vision
 * API and if it is we blur it using ImageMagick.
 */
exports.blurOffensiveImages = functions.storage.object().onChange(event => {
  const object = event.data;
  const file = gcs.bucket(object.bucket).file(object.name);

  // Exit if this is a move or deletion event.
  if (object.resourceState === 'not_exists') {
    return console.log('This is a deletion event.');
  }

  // Check the image content using the Cloud Vision API.
  return vision.detectSafeSearch(file).then(data => {
    const safeSearch = data[0];
    console.log('SafeSearch results on image', safeSearch);

    if (safeSearch.adult || safeSearch.violence) {
      return blurImage(object.name, object.bucket, object.metadata);
    }
  });
});

/**
 * Blurs the given image located in the given bucket using ImageMagick.
 */
function blurImage(filePath, bucketName, metadata) {
  const tempLocalFile = path.join(os.tmpdir(), filePath);
  const tempLocalDir = path.dirname(tempLocalFile);
  const bucket = gcs.bucket(bucketName);

  // Create the temp directory where the storage file will be downloaded.
  return mkdirp(tempLocalDir).then(() => {
    console.log('Temporary directory has been created', tempLocalDir);
    // Download file from bucket.
    return bucket.file(filePath).download({destination: tempLocalFile});
  }).then(() => {
    console.log('The file has been downloaded to', tempLocalFile);
    // Blur the image using ImageMagick.
    return spawn('convert', [tempLocalFile, '-channel', 'RGBA', '-blur', '0x8', tempLocalFile]);
  }).then(() => {
    console.log('Blurred image created at', tempLocalFile);
    // Uploading the Blurred image.
    return bucket.upload(tempLocalFile, {
      destination: filePath,
      metadata: {metadata: metadata} // Keeping custom metadata.
    });
  }).then(() => {
    console.log('Blurred image uploaded to Storage at', filePath);
    fs.unlinkSync(tempLocalFile);
    console.log('Deleted local file', filePath);
  });
}

I've done the following steps:

*

*Created a working Firebase project

*Activated the Vision API and the billing for the project

*Initialized the Firebase Functions localy on my PC

*Installed needed npm modules with npm install

*Tried to deploy with firebase deploy
Then i got this error:
i  deploying functions
i  functions: ensuring necessary APIs are enabled...
+  functions: all necessary APIs are enabled
i  functions: preparing functions directory for uploading...

Error: Error occurred while parsing your function triggers.

TypeError: require(...) is not a function
    at Object.<anonymous> (C:\Users\xxxxxx\FirebaseTest\functions\index.js:21:47)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at C:\Users\Tobias\AppData\Roaming\npm\node_modules\firebase-tools\lib\triggerParser.js:18:11
    at Object.<anonymous> (C:\Users\xxxxxx\AppData\Roaming\npm\node_modules\firebase-tools\lib\triggerParser.js:38:3)

So he is complaining about this line:
const vision = require('@google-cloud/vision')();

My package.json looks like this:
{
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "scripts": {
    "serve": "firebase serve --only functions",
    "shell": "firebase experimental:functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "dependencies": {
    "@google-cloud/storage": "^1.5.2",
    "@google-cloud/vision": "^0.14.0",
    "child-process-promise": "^2.2.1",
    "firebase-admin": "^5.8.1",
    "firebase-functions": "^0.8.1",
    "mkdirp": "^0.5.1",
    "mkdirp-promise": "^5.0.1"
  },
  "private": true
}

Nice to know: Other attempts, for example to try out Cloud Storage triggers in other functions, are working pretty well with my Firebase project. Only the Vision API gives me that much trouble.
Can someone please give me a hint what went wrong with my setup?
Thank you!

A: I also experienced some headaches with Cloud Vision in FCF. My working solution looks like this:
const vision = require('@google-cloud/vision');
const visionClient =  new vision.ImageAnnotatorClient();

Then you should be able to do cool stuff like:
visionClient.labelDetection(someImageUri)

A: The problem is that you're using newer versions of the vision API than the sample code uses.  The sample code provides these dependencies:
"@google-cloud/storage": "^0.4.0",
"@google-cloud/vision": "^0.5.0",
"child-process-promise": "^2.2.0",
"firebase-admin": "^4.1.1",
"firebase-functions": "^0.5.1",
"mkdirp": "^0.5.1",
"mkdirp-promise": "^4.0.0"

You're using newer stuff:
"@google-cloud/storage": "^1.5.2",
"@google-cloud/vision": "^0.14.0",
"child-process-promise": "^2.2.1",
"firebase-admin": "^5.8.1",
"firebase-functions": "^0.8.1",
"mkdirp": "^0.5.1",
"mkdirp-promise": "^5.0.1"

So, you have two options.  Back down the dependency versions to match what's being used by the sample code, or change the sample to suit the versions you want to use.


text:
Q: How to set dynamically parameters when i call a constructor method My problem is to construct dynamically the call of constructors with the right number of parameters.
PHP7
I created a function createObjectFromJson which create an instance of object from a json file. The object classes already exist, and constructor methods can receive 0 or many parameters.
I have an array with the list of json properties to pass to constructor of the object.
My problem is to construct dynamically the call of the constructor with the right number of parameters.
<?
trait jsonHelper {
    static function jsonToObject(string $json)  {
        $constructArgument = ["foo"=>["p1","p2"]];
        $class = __CLASS__;
        $jsonArray = json_decode($json, true);
        // construit les arguments à passer au constructeur
        $arg;
        if(isset($constructArgument[$class])) {
            $arg = [];
            foreach($constructArgument[$class] as indice=>$constructArgument)

                $constructArgumentValue;
                if(isset($jsonArray[$constructArgument])){
                    $constructArgumentValue = $jsonArray[$constructArgument];
                }
                array_push($arg, $jsonArray[$constructArgument]);
            }
        }
        $objectReturn = new $class($arg);

        foreach($objectReturn as $key=>$value){
            // initialize each properties
            ....
        }
    }
}

class Foo {
    Use jsonHelper;

    public $p1;
    public $p2;

    function __construct($p1, $p2){
        $this->p1 = $p1;
        $this->p2 = $p2;
    }

}?>

With this code I have the following error :

Uncaught ArgumentCountError: Too few arguments to function
  Foo::__construct().

I understand I'm passing 1 argument ( one array) instead of 2 arguments expected. How convert an array to a correct arguments strings?

A: Use reflection:
$refClz = new ReflectionClass($class);
$objectReturn = $refClz->newInstanceArgs($arg);


text:
Q: Saving the state of the LED on illuminated momentary button I have three illuminated momentary buttons with a separate anode and cathode for the led.
 (source of image)
I want a circuit that illuminates the LED of the button that was most recently pushed.
My initial idea has been to use three SR Latches created using NOR gates. Connect the S or Q of each latch to the reset of the two other latches. But then this creates the opportunity for HIGH on both S and R which is disallowed. Right?
I imagine there are other ways to accomplish this without latches too. Any help is greatly appreciated.

A: The circuit you're looking for is called a "flip-flap-flop". It is essentially a 3-state (rather than 2-state) flip-flop. It can be implemented using a single 74xx27. It is the circuit on the right below:


text: Q: In App Purchases keep crashing Test Flight I am trying to test my In-App Purchases that work in the simulator but not in Test Flight. I am not sure why but my question is could it be possible that I didn't fill in the Agreements, Tax, and Banking information under the agreements section?


text:
Q: Windows 10 PRO: DBeaver + ODBC no connection I've an ODBC for 4D SQL connection correctly created on Windows manager:

which perfectly connects.
I have this very same connection up to 5 machines. All of them working without problems.
Then I install DBeaver with the common installations process: Next > Next > Yes > Next > ... Finish.
Then I create DBeaver connection with ODBC driver:

And as can be seen, perfectly connects and runs.
But this is where the problems begins. This very works on 4 of my 5 machines. Only on a server (Xeon machine) one, it doesn't.
This is the error I receive:

I commented on official DBeaver git forums, and they basically moved me away:
https://github.com/dbeaver/dbeaver/discussions/12612
I've tried to create a very simple Java code which connects through ODBC and compiled with JDK 7. If I run it trough Java JDK 7, it works and connects. But if I run with DBeaver emmbeded JRE or windows common installed Java JRE, it doesn't:
http://www.herongyang.com/JDBC/JDBC-ODBC-DSN-Connection.html
So it really seems to be a Java problem, but then, why it works on all other machines but this one?
I do exactly the very same thing on every machine, same installation process, same configuration ODBC process. Copy.
But it doesn't works on this server.
DBeaver downloads 2 files always, ODBC.dll and the java_7_bridge. And they work everywhere, but here.
How to solve?
The error log on connection:
2021-05-13 19:05:10.440 - org.jkiss.dbeaver.model.exec.DBCConnectException: Unexpected driver error occurred while connecting to the database
org.jkiss.dbeaver.model.exec.DBCConnectException: Unexpected driver error occurred while connecting to the database
at org.jkiss.dbeaver.model.impl.jdbc.JDBCDataSource.openConnection(JDBCDataSource.java:227)
at org.jkiss.dbeaver.ext.generic.model.GenericDataSource.openConnection(GenericDataSource.java:135)
at org.jkiss.dbeaver.model.impl.jdbc.JDBCExecutionContext.connect(JDBCExecutionContext.java:101)
at org.jkiss.dbeaver.model.impl.jdbc.JDBCRemoteInstance.initializeMainContext(JDBCRemoteInstance.java:100)
at org.jkiss.dbeaver.model.impl.jdbc.JDBCRemoteInstance.(JDBCRemoteInstance.java:59)
at org.jkiss.dbeaver.model.impl.jdbc.JDBCDataSource.initializeRemoteInstance(JDBCDataSource.java:109)
at org.jkiss.dbeaver.ext.generic.model.GenericDataSource.(GenericDataSource.java:107)
at org.jkiss.dbeaver.ext.generic.model.meta.GenericMetaModel.createDataSourceImpl(GenericMetaModel.java:90)
at org.jkiss.dbeaver.ext.generic.GenericDataSourceProvider.openDataSource(GenericDataSourceProvider.java:106)
at org.jkiss.dbeaver.registry.DataSourceDescriptor.connect(DataSourceDescriptor.java:897)
at org.jkiss.dbeaver.runtime.jobs.ConnectJob.run(ConnectJob.java:70)
at org.jkiss.dbeaver.runtime.jobs.ConnectionTestJob.run(ConnectionTestJob.java:103)
at org.jkiss.dbeaver.model.runtime.AbstractJob.run(AbstractJob.java:105)
at org.eclipse.core.internal.jobs.Worker.run(Worker.java:63)
Caused by: java.lang.NullPointerException
at sun.jdbc.odbc.JdbcOdbcDriver.initialize(JdbcOdbcDriver.java:453)
at sun.jdbc.odbc.JdbcOdbcDriver.connect(JdbcOdbcDriver.java:153)
at org.jkiss.dbeaver.model.impl.jdbc.JDBCDataSource.lambda$0(JDBCDataSource.java:176)
at org.jkiss.dbeaver.model.impl.jdbc.JDBCDataSource.openConnection(JDBCDataSource.java:195)
... 13 more
2021-05-13 19:05:10.506 -
java.lang.NullPointerException
at sun.jdbc.odbc.JdbcOdbcDriver.initialize(JdbcOdbcDriver.java:453)
at sun.jdbc.odbc.JdbcOdbcDriver.connect(JdbcOdbcDriver.java:153)
at org.jkiss.dbeaver.model.impl.jdbc.JDBCDataSource.lambda$0(JDBCDataSource.java:176)
at org.jkiss.dbeaver.model.impl.jdbc.JDBCDataSource.openConnection(JDBCDataSource.java:195)
at org.jkiss.dbeaver.ext.generic.model.GenericDataSource.openConnection(GenericDataSource.java:135)
at org.jkiss.dbeaver.model.impl.jdbc.JDBCExecutionContext.connect(JDBCExecutionContext.java:101)
at org.jkiss.dbeaver.model.impl.jdbc.JDBCRemoteInstance.initializeMainContext(JDBCRemoteInstance.java:100)
at org.jkiss.dbeaver.model.impl.jdbc.JDBCRemoteInstance.(JDBCRemoteInstance.java:59)
at org.jkiss.dbeaver.model.impl.jdbc.JDBCDataSource.initializeRemoteInstance(JDBCDataSource.java:109)
at org.jkiss.dbeaver.ext.generic.model.GenericDataSource.(GenericDataSource.java:107)
at org.jkiss.dbeaver.ext.generic.model.meta.GenericMetaModel.createDataSourceImpl(GenericMetaModel.java:90)
at org.jkiss.dbeaver.ext.generic.GenericDataSourceProvider.openDataSource(GenericDataSourceProvider.java:106)
at org.jkiss.dbeaver.registry.DataSourceDescriptor.connect(DataSourceDescriptor.java:897)
at org.jkiss.dbeaver.runtime.jobs.ConnectJob.run(ConnectJob.java:70)
at org.jkiss.dbeaver.runtime.jobs.ConnectionTestJob.run(ConnectionTestJob.java:103)
at org.jkiss.dbeaver.model.runtime.AbstractJob.run(AbstractJob.java:105)
at org.eclipse.core.internal.jobs.Worker.run(Worker.java:63)
Start Núcleo del equipo de soporte [org.eclipse.team.core 3.8.1100.v20200806-0621]
2021-05-13 19:10:03.725 - DBeaver is stopping
2021-05-13 19:10:03.726 - Stop RMI server
2021-05-13 19:10:03.727 - DBeaver shutdown completed