text:
Q: ValidateCredentials returns true for unknown user? I'm seeing some odd behaviour here using PrincipalContext.ValidateCredentials. The set-up is two Active Directory domains in parent/child setup (so we have primary domain company.com and sub-domain development.company.com).
When I validate credentials against the primary domain, ValidateCredentials behaves as expected, returning true for good user/pass pairs, and false for anything else.
However if I validate a user in the sub-domain, ValidateCredentials returns true for both good username/passwords AND invalid users. If I provide a valid user with an invalid password, it correctly returns false.
Now I'm working around it at the moment by doing UserPrincipal.FindByIdentity() first and if the user exists, then calling ValidateCredentials -- but I'd like to understand what's going on.
Another workaround I've looked at is by passing the username through as domain\username  as the MSDN entry for ValidateCredentials states:

In each version of this function, the userName string can be in one of
  a variety of different formats. For a complete list of the acceptable
  types of formats, see the ADS_NAME_TYPE_ENUM documentation.

...of which this form of username is listed. But this causes ValidateCredentials to always return true, no matter what combination of username and password I pass in.
The pertinent code is:
bool authenticated = false;

// Various options tried for ContextOptions, [etc] inc. explicit username/password to bind to AD with -- no luck.
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domain, null, ContextOptions.Negotiate, null, null))
{
    log(pc.ConnectedServer + " => " + pc.UserName + " => " + pc.Name + " => " + pc.Container);
    using (var user = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, username))
    {
        if (user != null)
        {
            log(user.DistinguishedName + "; " + user.DisplayName);
            authenticated = pc.ValidateCredentials(username, password);
        } else {
            log("User not found");
            // Debug only -- is FindByIdentity() needed. This should always return
            // false, but doesn't.
            authenticated = pc.ValidateCredentials(username, password);
        }
    }
}
return authenticated;

Any and all (sensible) suggestions welcome -- I'm scratching my head over this as it just goes against all expectations.
I ought to add: this is running as myself on my machine, both of which are members of the primary domain. However I've also tried running it in a command prompt on my machine  as a user of the sub-domain (runas /user:subdomain\user cmd) with exactly the same results.

A: Some amount of googling later (not that I've been in and out of google all day trying to find this anyway), I've found the answer.
Put simply, if the Guest account is enabled in the domain, ValidateCredentials will return TRUE for an unknown user. I've just checked the status of the guest user in development.company.com, and sure enough the account is enabled. If I have the guest account disabled, ValidateCredentials correctly returns false.
This is a fairly fundamental gotcha, not sure I'm keen on this behaviour... pity it's not explicitly mentioned on MSDN.

A: I have used ContextOptions.SimpleBind flag with ValidateCredentials it solved my problem..
Sample code:
    using (var context = new PrincipalContext(ContextType.Domain, "DOMAIN", null))
    {
        bool loginResult = context.ValidateCredentials(username, password, ContextOptions.SimpleBind); // returns false for unknown user
    }

A: Could it be related to this:

The ValidateCredentials method binds to the server specified in the
  constructor. If the username and password parameters are null, the
  credentials specified in the constructor are validated. If no
  credential were specified in the constructor, and the username and
  password parameters are null, this method validates the default
  credentials for the current principal.


text:
Q: Is there any way I could use linux commands in node.js windows? I am a php developer, and I am trying to convert my php knowledge to node.js. I just started working on this beautiful back-end development project for an app in node.js. I use Intellij IDEA on windows 8.1. I still code in php for a different project and sometimes I miss my Putty when i code in node.js and I don't like Intellij IDEA's windows terminal. I have been searching if there is a way that i can use Intellij IDEA's terminal with Linux commands on windows. I get really hard time to look for windows commands each time. Is there anyone has a recommendation about it? Thank you in advanced!

A: If you want to use Linux commands on Windows you need Cygwin. You can use Cygwin in the terminal inside Intellij IDEA. This is how to set it up

redpajama_set_name: RedPajamaStackExchange


text:
Q: rollback a sql table data as yesterday I have updated a sql table data by mistake. How can I revert back my changes to get the data as yesterday or before the update.
select id, number from mytable

A: If only you used a transaction to give you the option to roll back.
Sorry that without a transaction, you will need to reset the data from a back up.
For example,
BEGIN TRAN T1; UPDATE ImportantStuff SET ImportantValue

If its looks good;
COMMIT TRAN T1;

If it does'nt;
ROLLBACK TRAN T1


text:
Q: Why is the formula for the speed of sound in solids different from that in liquids and gases? We know that sound waves are longitudinal waves and that the propagation of longitudinal waves depends on the bulk modulus $B$ (volumetric elasticity). Why, then, does the speed of sound in a solid depend on the Young's modulus $Y$ of the medium and the density,
$$v = \sqrt{(Y/\text{density of the medium})}?$$
The form should be the same as for liquids and gases:
$$v = \sqrt{(B/\text{density of the medium})}.$$

A: There is more than one speed of sound in a solid. In an isotropic solid the  speed depend on the two Lame coeffcients $\lambda$ and $\mu$.   The  speed of longitudinal "p" waves in a bulk solid is
$$
c_{p}= \sqrt{\frac{E(1-\nu)}{\rho(1+\nu)(1-2\nu)}}
$$
where
$$
E=\mu\left(\frac{3\lambda+2\mu}{\lambda+\mu}\right)
$$
is Young's modulus and
$$
\nu=\frac 12 \frac{\lambda}{\lambda+\mu}
$$
is Poisson's ratio.
The speed of transverse "s" waves is
$$
c_s= \sqrt{\frac{\mu}{\rho}}.
$$
The simple formula
$$
c_{rod}= \sqrt{\frac {E}{\rho}}
$$
applies only to longitudinal waves in a long thin rod.
The physical reason for the differences in the longitudinal speeds is  that in a long thin rod, the material is free to contract laterally as the wave propagates, but in the infinite medium it is not.


text:
Q: Error while one hot encoding a column of list of strings I have a dataframe that contains information about cuisines and their respective ingredients. The ingredients are stored in a column with type of list of strings, ['ingredients'], as shown in the image below:

I tried to one hot encode each ingredient so I used the answer in this post for reference.
However, I got an error message shown below:
code:
train_w_stemming_df = pd.DataFrame(mlb.fit_transform(train_w_stemming_df['ingredients']),
         columns=mlb.classes_,
         index = train_w_stemming_df.index)

error message:
ValueError                                Traceback (most recent call last)
/usr/local/lib/python3.7/dist-packages/pandas/core/internals/managers.py in create_block_manager_from_blocks(blocks, axes)
   1670                 blocks = [
-> 1671                     make_block(values=blocks[0], placement=slice(0, len(axes[0])))
   1672                 ]

6 frames
ValueError: Wrong number of items passed 1, placement implies 43

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
/usr/local/lib/python3.7/dist-packages/pandas/core/internals/managers.py in create_block_manager_from_blocks(blocks, axes)
   1679         blocks = [getattr(b, "values", b) for b in blocks]
   1680         tot_items = sum(b.shape[0] for b in blocks)
-> 1681         raise construction_error(tot_items, blocks[0].shape[1:], axes, e)
   1682
   1683

ValueError: Shape of passed values is (29774, 1), indices imply (29774, 43)

How can I fix this error?


text:
Q: Permission for sockets - android manifest I've made a simple test application for reading RabbitMQ queues using java amqp lib (implementation 'com.rabbitmq:amqp-client:5.7.1').
But im having trouble when connecting to my rabbit server due to Android permissions (socket)
Here is the error message:
W/System.err: java.net.SocketException: socket failed: EPERM (Operation not permitted)
I've tried, successless, to add android.permission.INTERNET to the manifest. Here is what it looks like:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.androidwebsocket">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

What am I missing?
Edit
As requested, here is the full error stacktrace: https://pastebin.com/WAh2B4rP
And the code that triggers this error:
ConnectionFactory factory = new ConnectionFactory();
factory.setUsername("myuser");
factory.setPassword("mypass");
factory.setVirtualHost("/");
factory.setHost("myhost.io");
factory.setPort(5672);

connection = factory.newConnection(); //Error triggers here
channel = connection.createChannel();

A: I was missing
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

It should mentioned that connections MUST run in Background Threads, or otherwhise android will block it.
Also:
Uninstall app from emulator as suggested in
java.net.SocketException: socket failed: EPERM (Operation not permitted)


text:
Q: phonegap build whitelisting not working When using phonegap build, whitelisting doesn't seem to be working. When I run the application from a browser, all the ajax calls are successfull and the application works. I have the following config.xml:
<?xml version="1.0" encoding="UTF-8"?>
<widget xmlns="http://www.w3.org/ns/widgets" xmlns:gap="http://phonegap.com/ns/1.0"
id="com.company.Demo" version="1.0.0">
<name>Demo</name>
<description>
    ...
</description>
<author email="myEmailAddress">
    Jeroen Claes
</author>
<content src="index.html" />
<preference name="phonegap-version" value="cli-5.2.0" />
<preference name="orientation"                value="default" />        <!-- all: default means both landscape and portrait are enabled -->
<preference name="target-device"              value="universal" />      <!-- all: possible values handset, tablet, or universal -->
<preference name="fullscreen"                 value="true" />           <!-- all: hides the status bar at the top of the screen -->
<preference name="webviewbounce"              value="true" />           <!-- ios: control whether the screen 'bounces' when scrolled beyond the top -->
<preference name="prerendered-icon"           value="true" />           <!-- ios: if icon is prerendered, iOS will not apply it's gloss to the app's icon on the user's home screen -->
<preference name="stay-in-webview"            value="false" />          <!-- ios: external links should open in the default browser, 'true' would use the webview the app lives in -->
<preference name="ios-statusbarstyle"         value="black-opaque" />   <!-- ios: black-translucent will appear black because the PhoneGap webview doesn't go beneath the status bar -->
<preference name="detect-data-types"          value="true" />           <!-- ios: controls whether data types (such as phone no. and dates) are automatically turned into links by the system -->
<preference name="exit-on-suspend"            value="false" />          <!-- ios: if set to true, app will terminate when home button is pressed -->
<preference name="show-splash-screen-spinner" value="true" />           <!-- ios: if set to false, the spinner won't appear on the splash screen during app loading -->
<preference name="auto-hide-splash-screen"    value="true" />           <!-- ios: if set to false, the splash screen must be hidden using a JavaScript API -->
<preference name="disable-cursor"             value="false" />          <!-- blackberry: prevents a mouse-icon/cursor from being displayed on the app -->
<preference name="android-installLocation"    value="auto" />           <!-- android: app install location. 'auto' will choose. 'internalOnly' is device memory. 'preferExternal' is SDCard. -->

<!-- Plugins -->

<!-- Core plugins -->
<gap:plugin name="org.apache.cordova.battery-status" />
<gap:plugin name="org.apache.cordova.camera" />
<gap:plugin name="org.apache.cordova.media-capture" />
<gap:plugin name="org.apache.cordova.console" />
<gap:plugin name="org.apache.cordova.contacts" />
<gap:plugin name="org.apache.cordova.device" />
<gap:plugin name="org.apache.cordova.device-motion" />
<gap:plugin name="org.apache.cordova.device-orientation" />
<gap:plugin name="org.apache.cordova.dialogs" />
<gap:plugin name="org.apache.cordova.file" />
<gap:plugin name="org.apache.cordova.file-transfer" />
<gap:plugin name="org.apache.cordova.geolocation" />
<gap:plugin name="org.apache.cordova.globalization" />
<gap:plugin name="org.apache.cordova.inappbrowser" />
<gap:plugin name="org.apache.cordova.media" />
<gap:plugin name="org.apache.cordova.network-information" />
<gap:plugin name="org.apache.cordova.splashscreen" />
<gap:plugin name="org.apache.cordova.vibration" />
<gap:plugin name="cordova-plugin-whitelist" source="npm"/>

<!-- Third party plugins -->
<!-- A list of available plugins are available at https://build.phonegap.com/plugins -->

<!-- Define app icon for each platform. -->
<icon src="icon.png" />
<icon src="res/icon/android/icon-36-ldpi.png"   gap:platform="android"    gap:qualifier="ldpi" />
<icon src="res/icon/android/icon-48-mdpi.png"   gap:platform="android"    gap:qualifier="mdpi" />
<icon src="res/icon/android/icon-72-hdpi.png"   gap:platform="android"    gap:qualifier="hdpi" />
<icon src="res/icon/android/icon-96-xhdpi.png"  gap:platform="android"    gap:qualifier="xhdpi" />
<icon src="res/icon/blackberry/icon-80.png"     gap:platform="blackberry" />
<icon src="res/icon/blackberry/icon-80.png"     gap:platform="blackberry" gap:state="hover"/>
<icon src="res/icon/ios/icon-57.png"            gap:platform="ios"        width="57" height="57" />
<icon src="res/icon/ios/icon-72.png"            gap:platform="ios"        width="72" height="72" />
<icon src="res/icon/ios/icon-57-2x.png"         gap:platform="ios"        width="114" height="114" />
<icon src="res/icon/ios/icon-72-2x.png"         gap:platform="ios"        width="144" height="144" />
<icon src="res/icon/webos/icon-64.png"          gap:platform="webos" />
<icon src="res/icon/windows-phone/icon-48.png"  gap:platform="winphone" />
<icon src="res/icon/windows-phone/icon-173.png" gap:platform="winphone"   gap:role="background" />

<!-- Define app splash screen for each platform. -->
<gap:splash src="res/screen/android/screen-ldpi-portrait.png"       gap:platform="android" gap:qualifier="port-ldpi" />
<gap:splash src="res/screen/android/screen-mdpi-portrait.png"       gap:platform="android" gap:qualifier="port-mdpi" />
<gap:splash src="res/screen/android/screen-hdpi-portrait.png"       gap:platform="android" gap:qualifier="port-hdpi" />
<gap:splash src="res/screen/android/screen-xhdpi-portrait.png"      gap:platform="android" gap:qualifier="port-xhdpi" />
<gap:splash src="res/screen/blackberry/screen-225.png"              gap:platform="blackberry" />
<gap:splash src="res/screen/ios/screen-iphone-portrait.png"         gap:platform="ios"     width="320" height="480" />
<gap:splash src="res/screen/ios/screen-iphone-portrait-2x.png"      gap:platform="ios"     width="640" height="960" />
<gap:splash src="res/screen/ios/screen-iphone-portrait-568h-2x.png" gap:platform="ios"     width="640" height="1136" />
<gap:splash src="res/screen/ios/screen-ipad-portrait.png"           gap:platform="ios"     width="768" height="1024" />
<gap:splash src="res/screen/ios/screen-ipad-landscape.png"          gap:platform="ios"     width="1024" height="768" />
<gap:splash src="res/screen/windows-phone/screen-portrait.jpg"      gap:platform="winphone" />

<access origin="*" />
<allow-intent href="*" />
<allow-navigation href="*" />
<!-- Added the following intents to support the removal of whitelist code from base cordova to a plugin -->
<!-- Whitelist configuration. Refer to https://cordova.apache.org/docs/en/edge/guide_appdev_whitelist_index.md.html -->
<!--     <allow-intent href="http://*/*" /> -->
<!--     <allow-intent href="https://*/*" /> -->
<!--     <allow-intent href="tel:*" /> -->
<!--     <allow-intent href="sms:*" /> -->
<!--     <allow-intent href="mailto:*" /> -->
<!--     <allow-intent href="geo:*" /> -->
<!--     <allow-intent href="*" /> -->
<platform name="android">
    <allow-intent href="market:*" />
</platform>
<platform name="ios">
    <allow-intent href="itms:*" />
    <allow-intent href="itms-apps:*" />
</platform>
<platform name="winphone">
</platform>

</widget>

I've also added the following to my index.html:
<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'">

I'm even using the following params before sending my jquery post to the server:
$.support.cors = true;
$.mobile.allowCrossDomainPages = true;

Each time I send an ajax request I receive a 403 error: forbidden
This is the ajax request I'm sending:
var sr = "<?xml version='1.0' encoding='UTF-8'?>";
sr += "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" >";
    sr += "<soap:Body>";
sr += "<wsse:Username>" + username + "</wsse:Username>";
sr += "<wsse:Password>" + password + "</wsse:Password>";
sr += "<\/soap:Body>";
sr += "<\/soap:Envelope>";

$.ajax({
    headers: {  'SOAPAction': "\"Login\""
                },
    url:"https://host:port/demo/Login",
    type: "POST",
    contentType: "text/xml; charset=utf-8",
    accepts:"application/xml; text/xml; \*/\*",
    dataType: "json",
    crossDomain: true,
    data: sr,
    processData: false,
    success: function(resp){...},
    fail: function(err){...}});

A: @Jeroen,
CORS or 'Access-Control-Allow-Origin' is not required. This is a common misconception with Phonegap. 'CORS' is a wevbrowser security protocol. It is not a Mobile App security protocol.
To be clear, the webview library used for Cordova/Phonega renders HTML, but it is NOT a webbrowser. The wikipedia explanation for CORS is half-bad, but the explanation works. CORS always starts with a webbrowser that is capable of CORS. Again, CORS does NOT exist on Cordova/Phonegap.
This FAQ should also help.
Top Mistakes by Developers new to Cordova/Phonegap see: #5
Your connections issue in the CSP. This is also a common mistake, mostly because all the examples are poor - including those on the Cordova and Phonegap website.
NOTE YOUR APP IS NOW INSECURE. IT IS UP TO YOU TO SECURE YOUR APP.
Add the following to your index.html. Note, the star (*) which is missing in your file.
<meta http-equiv="Content-Security-Policy"
         content="default-src *;
                  style-src * 'self' 'unsafe-inline' 'unsafe-eval';
                  script-src * 'self' 'unsafe-inline' 'unsafe-eval';">

You can also remove all Javascript from your index.html, it should have the same effect.
This whitelist worksheet should help with other parts.
HOW TO apply the Cordova/Phonegap the whitelist system
Make sure you also read the: whitelist matrix and the Whitelist CSP Examples
Best of Luck


text:
Q: What is the upper case variant to \scshape etc.? I have read on
https://en.wikibooks.org/wiki/LaTeX/Fonts
that there is no variant of \scshape for upper case. Also there seem to be problems with upper case that are addressed by the textcase package. However, using its \MakeTextUppercase does not work for me since it garbles my cross references.
I must have missed something or why is it possible to get small caps out of the box but not upper case? This is quite incredible. (I know that one could create a new \nameref command to get around the problem but that isn't feasible for me.)
Here are two examples:
Works great with \scshape:
\documentclass{scrartcl}
\usepackage{hyperref}
\usepackage{textcase}
\setkomafont{section}{
\normalfont
\scshape
}

\begin{document}
  \section{Test \nameref{sec:test2}}
  \section{Test2}\label{sec:test2}
\end{document}

Doesn't work with \MakeTextUppercase:
\documentclass{scrartcl}
\usepackage{hyperref}
\usepackage{textcase}
\setkomafont{section}{
\normalfont
\MakeTextUppercase
}

\begin{document}
  \section{Test \nameref{sec:test2}}
  \section{Test2}\label{sec:test2}
\end{document}


text:
Q: grails 3 ConstraintException I'm using grails 3.02 and all was fine, but since I moved several domain classes from another grails project I started seeing this error when I do start integration tests:

grails.validation.exceptions.ConstraintException: Exception thrown applying constraint [unique] to class [class com.mypackage.Individual] for value [true]: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6397593b has not been refreshed yet

The domain class code:
class Individual {

 String institutionId
 String email

 static mapping = {
    table 'db.individual'
    id generator: 'sequence', params: [sequence: 'db.individual_id_sequence']
    institutionId index: 'db.individual_institution_id_idx'
    email index: 'db.individual_email_idx'
 }

 static constraints = {
    institutionId(blank: false)
    email(unique: true)
 }
}

The strange thing is: this code is working in another project but does not want to work in this one, in where I moved it to. I compared configs(application.yml and application.groovy and build.gradle) - but all is basically the same.
Any help, grails gurus?

A: I think I have found why I had this exception. It was not related to constrains at all.
I just had some other fields in my domain class which used to be calculated, so it was unmapped field. But grails used to try to map this field into a real database column. Once I've defined my own getter(in which the field initializes) for this calculated field all became fine.
But the grails exception btw is stupid and disorienting - it does not describe the root cause at all.


text:
Q: Unable to mount location after installing Linux Mint I have been using Ubuntu for a while, but I decided to move to Linux Mint. I removed everything and clearly installed it. After the installation there are two parts which are File System and Toshiba. When I try to open Toshiba it says unable to mount location. Output of sudo fdisk -l can be seen below. By the way I have only one HDD (Toshiba).Moreover I shared two pics to be more clear:
Disk /dev/sda: 750.2 GB, 750156374016 bytes
255 heads, 63 sectors/track, 91201 cylinders, total 1465149168 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x8cecb72c

Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *        2048  1435547647   717772800   83  Linux
/dev/sda2      1435547648  1465147391    14799872   82  Linux swap / Solaris

A: I think that this 'Toshisba' icon represents graphically a whole drive as a device just like /dev/sda. Device cannot be mounted this way. Only partition formatted with filesystem which is represented in your case as 'File System' icon. I suggest to ignore it or maybe there is some setting in a filemanager to hide it.

A: Go into menu and search disks.
If you see that your partition is free and not initialized or created
just click on plus sign and create it.
Then you will see a play button beside the plus sign when the has been partition created. Just click on it and your partition will be mounted.


text:
Q: Building static lib with state multiple times So I have this example code that I compile using VS to a static library:
int val = 0;

int f(int i) {
    val += i;
    return val;
}

Because of the global the library has an internal state. I now want to use the function f in a program but multiple times and each call having its own state. So I compiled it twice with different names for f:
int val = 0;

int f1(int i) {
    val += i;
    return val;
}

which is compiled to f1.lib and
int val = 0;

int f2(int i) {
    val += i;
    return val;
}

which is compiled to f2.lib. Then I tried using it in my program which includes both libraries and looks like:
#include <iostream>

int f1(int i);
int f2(int i);

int main()
{
    int x = f1(1);
    int y = f2(1);

    std::cout << x << "\n";
    std::cout << y << "\n";
}

However, this doesn't compile I get an error that "int val is already defined in f1.obj".
This makes sense and could be solved of course by renaming the globals as well. However this is not feasible because for my real code there are too many variables/functions/structs/etc. that would require renaming.
Question: How can I compile the library code so that I can include it twice (or even more often), each include has its own internal state and I don't have to rename everything but only the function f which is used to interact with the library?

A: Different libaries should use different namespaces. Rarely it is a good idea to place stuff in the global namespace. Even then collisions cannot be completely excluded, but there are workarounds for this too. As you are in control of both libraries this isnt an issue here. Instead of renaming the function only, rename the namespace. Ie in the first:
namespace lib1 {
    int val = 0;

    int f(int i) {
        val += i;
        return val;
    }
}

And accordingly in the other library.


text:
Q: I am unable to connect to rabbitmq server in docker I am using docker compose to run a sbt process which connect to rabbitmq-server . Following is my docker compose file : -
version: "3"
services:
  web:
    # replace username/repo:tag with your name and image details
    image: abhishekkumargaya/messanger
    ports:
      - "1883:1883"
    links:
      - rabbit-server
      - redis
      - mysql
    networks:
      - webnet
  rabbit-server:
    image: "rabbitmq:3-management"
    hostname: localhost
    environment:
      #RABBITMQ_ERLANG_COOKIE: "SWQOKODSQALRPCLNMEQG"
      RABBITMQ_DEFAULT_USER : guest
      RABBITMQ_DEFAULT_PASS : guest
    ports:
      - "5672:5672"
      - "15672:15672"

    networks:
      - webnet

  redis:
    image: "redis:alpine"

  mysql:
    image: mysql
    container_name: database.dev
    command: mysqld --user=root --verbose

    ports:
      - "3306:3306"
    environment:
      MYSQL_DATABASE: "user_messages"
      MYSQL_USER: "test"
      MYSQL_PASSWORD: "root"
      MYSQL_ROOT_PASSWORD: "root"
      MYSQL_ALLOW_EMPTY_PASSWORD: "yes"

networks:
  webnet:
volumes:
  redis-data:

I am getting connection refused error. I am using default value to connect to rabbit server in my code .
private lazy val factory = new ConnectionFactory
val connection = factory.newConnection()

My docker file : -
FROM openjdk:8
ENV SBT_VERSION 0.13.16
RUN \
  curl -L -o sbt-$SBT_VERSION.deb http://dl.bintray.com/sbt/debian/sbt-$SBT_VERSION.deb && \
  dpkg -i sbt-$SBT_VERSION.deb && \
  rm sbt-$SBT_VERSION.deb && \
  apt-get update && \
  apt-get install sbt && \
  sbt sbtVersion

WORKDIR /app
ADD target/scala-2.11/messanger-assembly-1.0.jar /app
EXPOSE 1883
CMD java -jar messanger-assembly-1.0.jar

The error which I am getting is as follows :-
Caused by: java.net.ConnectException: Connection refused (Connection refused)
web_1            |  at java.net.PlainSocketImpl.socketConnect(Native Method)
web_1            |  at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
web_1            |  at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
web_1            |  at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
web_1            |  at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
web_1            |  at java.net.Socket.connect(Socket.java:589)
web_1            |  at com.rabbitmq.client.impl.SocketFrameHandlerFactory.create(SocketFrameHandlerFactory.java:60)
web_1            |  at com.rabbitmq.client.impl.recovery.RecoveryAwareAMQConnectionFactory.newConnection(RecoveryAwareAMQConnectionFactory.java:62)
web_1            |  at com.rabbitmq.client.impl.recovery.AutorecoveringConnection.init(AutorecoveringConnection.java:99)
web_1            |  at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:948)
web_1            |  at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:907)
web_1            |  at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:865)
web_1            |  at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:1018)
web_1            |  at com.abhishek.rabbitmq.RabbitMqConnectionFactory$.<init>(RabbitMqConnectionFactory.scala:15)
web_1            |  at com.abhishek.rabbitmq.RabbitMqConnectionFactory$.<clinit>(RabbitMqConnectionFactory.scala)

I am not properly understanding how these variable works :-
hostname: localhost
environment:
  #RABBITMQ_ERLANG_COOKIE: "SWQOKODSQALRPCLNMEQG"
  - RABBITMQ_DEFAULT_USER = guest
  - RABBITMQ_DEFAULT_PASS = guest

I kept this variable like this because by default my client is using host as localhost , user as guest and password as guest to connect to rabbitmq-server
If I am just running rabbitmq-server image with command -
docker-compose up --build

I am able to connect it through my localmachine .

A: I am able to connect now. To connect to rabbit container, I need to put host as rabbit in my web container.Similarily for connection to mysql and redis , I need to use host as mysql and redis respectively.

A: You can depend on localhost if you set network_mode for your web to "host"


text:
Q: Read huge tar.gz file stream-like way, line by line After some load tests I have a single 60 GB log file (the test stopped because this file used all disk space available). In order to be able to continue using the server, I had to tar-gzip this file, but now I would like to query this file without unpacking it as a whole. Is there a way to read this file line-by-line using tools available in linux command line?

A: Tested on CentOS 6
zcat file.tar.gz | tar -x -O -f -

A: Actually, you can simply open a .bz2 or .gz file in vim.
vim file.tar.bz2

And do your work there.
You can use bzcat or even bzgrep with .bz2, same as zcat or zgrep with .gz.
However, bzcat doesn't save much, as it actually also goes about and unpacks the file into stdout. So if you want to grep it, use zgrep or bzgrep.
It works nicely on huge files.
bzgrep "pattern" file.tar.bz2

bzcat file.tar.bz2

Tested on OSX 10.10


text:
Q: How do I reference programmatically generated $scope variables in my template? I have an array fetched from the server from which I generate a variable number of boolean flags and attach them to my $scope variable in my controller.
for (var i = 0; i < myArray.length; i++) {
    $scope['TeamId' + myArray[i].TeamId + 'IsVisible'] = ViewMatrixService['TeamId' + myArray[i].TeamId + 'IsVisible'];
}

How do I reference these variables in my template? I tried the below, but it doesn't work.

A: Just put them in a scope variable that you can explicitly reference.
$scope.team = $scope.team || {};
for (var i = 0; i < myArray.length; i++) {
    $scope.team['TeamId' + myArray[i].TeamId + 'IsVisible'] = ViewMatrixService['TeamId' + myArray[i].TeamId + 'IsVisible'];
}

Though as an alternate route, if it's always going to be determined by whatever iteration of doc.DocumentOwnerTeam is currently active, just assign it as a property to that.


text:
Q: How do replication agents enable NOT FOR REPLICATION mode? How do triggers/identity columns/check contrains marked as NOT FOR REPLICATION get bypassed when the user connecting is a "replication agent"?

If i am an SQL Server replication agent, and i connect to a server to perform replication, how do i indicate to SQL Server that i am a replication agent, so that not for replication rules are enabled on all tables?
Why am i asking?
Because (choose one):

*

*to expand the limits of human knowledge and understanding

*because i'm writing my own replication system

A: I believe this is done internally using sessionproperty():
declare @is_replicationagent bit
select @is_replicationagent = convert(bit, sessionproperty('replication_agent'))


text:
Q: How to do a query to mysql database AFTER client`s request in nodejs/socket.io? All examples i've seen were doing a query first and then send to client some info.
If I do a query FIRST and then use results in functions it works:
client.query(
  ('SELECT * FROM '+TABLES_USERS),
  function(err, results, fields) {
var Users = (results);
  io.sockets.on('connection', function (socket) {
      socket.on('event1', function (data) {
          var requser = Users[data];
      socket.emit('event2', requser);
});
  });
    client.end();
  });

But now i need to do a query on client's request.
I tried something like this but query doesn't work:
io.sockets.on('connection', function (socket) {
 socket.on('event1', function (data) {
        console.log('query required'); /*works*/
        client.query(
          ('SELECT * FROM '+TABLES_USERS+' WHERE id_user ='+data),
          function(err, results, fields) {
              if (err) {throw err; /*doesn't work*/
                console.log('error'); /*doesn't work*/ }
                console.log('query is done'); /*doesn't work too. so i think query just doesn't work cuz there are no error and no results*/
                socket.emit('event2', results);
                client.end();
                    });

 });
});

A: There are some things you are not doing ok (in my opinion) in the example above:
1) You don't ask for login after the client is connected to Socket.IO, instead you check to see if his session contains data that can verify is he's connected.
You should read the article about Express, Socket.IO and sessions., since it explains everything in detail (if you are using Express)
2) I think MongoDB, CouchDB and possibly other databases are better suited for realtime applications than MySQL.

A: I've solved the problem by using node-mysql-libmysqlclient instead of node-mysql. But if someone knows a way to do a query AFTER client's request in node-mysql, please tell me))


text:
Q: Maven: how to copy resources into WAR? I have an Eclipse webapp project that I am trying to migrate from Ant build to Maven build. I have a lot of non-Java files in my src/ folder, for example log4j2.xml, ehcache.xml, some .properties localization files etc.
When I run war:war target on this project, the resulting WAR file contains only the .class files in the WEB-INF/classes folder, all the non-Java files are missing. In Ant I did this:
<target name="copy-resources" depends="compile">
  <copy todir="${build}">
    <fileset dir="${src}">
      <exclude name="**/*.java"/>
    </fileset>
  </copy>
</target>

How do I achieve the same thing in Maven? I suspect I should be using the resources folder, but right now I am trying to migrate with as little changes to the original codebase as possible...

A: You can access these files from resources folder. I hope this
link helps.
You can also specify the folder, if it is not the default resources folder, in the pom.xml.  See
Specifying resource directories.
For example, if your folder has these files in src/my-resources, then you need to add this to the pom.xml, and then you would be able access it in code.
   <resources>
     <resource>
       <directory>src/my-resources</directory>
     </resource>
   </resources>


text:
Q: How to print the same document to multiple printers Any Way to print the same document to multiple printers by only one click using Javascript or Jquery ?

A: No, JavaScript can't do anything other than invoke the browser's print dialog


text:
Q: Unobtrusive validation ASP.NET MVC3 in my app I have modified my script files in order to allow comma as decimal separator instead of using a dot (issue related to localization).
The thing is, when I use the unmodified script (the min version) the validation works fine... the error messages displays instantaneously and dissapear also instantaneously on correct. But when I use the modified version (non min version), the error messages just won't show up until I hit the submit button, then the MVC flow occurs (controller->action->view) and the ModelState.isValid goes false, display the same view with the model and obviously the model errors added, with the unobtrusive message sided to the incorrect field. I then correct the value, I know the value is fine, but the message doesn't clear. With the error message still on screen I hit on submit, then the MVC cycle occurs without errors, with a successful end.
Does any of you know how to fix this? I don't know if I should generate a min version or extend that min version overwriting the function. I don't even know how to do another thing different from the one I've done.

A: I couldn't make this work as I expected... I just used the non .min version... several blogs in Internet use the same approach to make modifications, or use plugins with lots of jquery scripts (this approach of plugins is what I tried to avoid, because it makes really hard to give maintenance!)


text:
Q: Module - IIFE isn't automatically called I created a module but it is not automatically rendered in my page, I have to manually call Board.renderBoard() in the console for the Board to appear. What am I doing wrong ?
here's the entire code:
const Board = (() => {
  const board = document.querySelector('.board');
  const createTiles = () => {
    tile = document.createElement('div');
    tile.classList.add('tile');
    return tile;
  };
  const renderBoard = () => {
    for (let i = 0; i < 9; i++) {
      createTiles();
      board.appendChild(createTiles());
    }
  };
  return {
    renderBoard
  };
})();

A:
I created a module but it is not automatically rendered in my page, I have to manually call Board.renderBoard() in the console for the Board to appear.

JS doesn't just call function unless you tell it to call these functions.
Your module simply defines an object Board with a method renderboard. There's nothing that tells JS to call this method.
You could add the call right after declaring the module.
const Board = (() => {
  ...
})();
Board.renderBoard();

But if all you want is that the code initially builds the board you can do:
(() => {
  const board = document.querySelector('.board');
  const createTiles = () => {
    const tile = document.createElement('div'); // please declare your variables
    tile.classList.add('tile');
    return tile;
  };
  for (let i = 0; i < 9; i++) {
    createTiles(); // what is this line for?
    board.appendChild(createTiles());
  }
})();

or
(() => {
  const board = document.querySelector('.board');
  for (let i = 0; i < 9; i++) {
    const tile = document.createElement('div');
    tile.classList.add('tile');
    board.appendChild(tile);
  }
})();

or maybe even
document.querySelector('.board').innerHTML = '

'.repeat(9);


text:
Q: Why does Google Chrome not recognize my SameSite cookie? I'm trying to explore how Google Chrome handles SameSite cookies. So by using the console (ctrl+Shift+J), I added an aditional key-value pair for the cookie of a certain website I have an account on. I inputted the following code:
document.cookie="SameSite=strict"

I checked the remaining cookie and all original key-value pairs are still there, along with the newly added "SameSite=strict" pair.
Now, the problem is that Chrome doesn't act like it is supposed to according to the specification of the SameSite cookie. For example: when I go to wikipedia.org and click on a link that directs me to the website of the cookie, I'm logged in. Normally I would not be logged in, because Chrome isn't supposed to send along the cookie due to the "SameSite=strict" pair.
Am I overlooking something?

A: SameSite is not a cookie value. It's a cookie flag, like httpOnly and secure. So you cannot set it like document.cookie="SameSite=strict", because that sets a value.
Try with
document.cookie="mycookie=myvalue;SameSite=strict"

You can then observe in Chrome DevTools on the Application tab under Cookies that your cookie is in fact set as SameSite=strict, as opposed to just a plain cookie.


text:
Q: ReactJS ApexChart problem with displaying the correct xlabel I am using a basic chart from ApexChart and I have a problem with displaying the label correct in percentage.
my code for the xaxis:
xaxis: {
      labels: {
        formatter: function (val) {
          return Math.abs(Math.round(val)) + "%"
        }
      },
    },

at the moment if the data is at 1% the xaxis displays 0-1% it is possible to change that the xaxis to display 0-100% but the data to reach just to 1%
This is the chart that I am using
https://apexcharts.com/react-chart-demos/bar-charts/basic/
What I have so far:
Here you can see that my data is between 0% - 1% but I want to be 0 - 100% but just 0-1% to be highlighted, to be displayed.

A: You should set the min and max for xaxis to set a range.
xaxis: {
  min: 0,
  max: 100,
  labels: {
    formatter: function (val) {
      return Math.abs(Math.round(val)) + "%"
    }
  }
}


text:
Q: LINQ add sum of columns to list entry I'm currently working on a .net 5.0 application.
I need to use LINQ to do a complex query:

*

*Given is a List<Player>

*I need to transform the List<Player>, but keep all entries

*add the TotalScore for each Team to all Players in "SerieA"

Unfortunately I don't know how to properly calculate the TotalScore for each team for all Players in a league in C# LINQ extension method syntax.

*

*The player class:

public class Player
{
    public string Name { get; set; }
    public string Team  { get; set; }
    public int Score  { get; set; }
    public string League  { get; set; }
    public int TotalTeamScore  { get; set; }
}

*

*the program class

public class Program
{
    public static void Main()
    {
        // given is a List<Player> - I need to calculate the TotalScore for each team ONLY for Leage "SerieA"
        var players = new List<Player> {
            new Player { Name = "Alex", Team = "A", Score = 10, League = "SerieA", TotalTeamScore = 0 },
            new Player { Name = "Anna", Team = "A", Score = 20, League = "SerieA", TotalTeamScore = 0 },
            new Player { Name = "Berta", Team = "B", Score = 60, League = "SerieA", TotalTeamScore = 0 },
            new Player { Name = "Benny", Team = "B", Score = 40, League = "SerieA", TotalTeamScore = 0 },
            new Player { Name = "Charlie", Team = "C", Score = 40, League = "PremierLeague", TotalTeamScore = 0 },
            new Player { Name = "Connor", Team = "C", Score = 40, League = "PremierLeague", TotalTeamScore = 0 },
        };

        // I need to find a proper way to calculate the TotalTeamScore for each Team in league SerieA and add this score to the players...
        var teamTotalScores = players
                                .Where(p => p.League == "SerieA")
                                .GroupBy(p => p.Team)
                                .Select(p => new Player {
                                    TotalTeamScore = p.Sum(s => s.Score)
                                    // Score = x.Key ??
                                })
                                .ToList();

// desired result: same List<Player> - only the Total TeamScore of a Team in "SerieA" should be calculated for each team and added to each player in a team:
// new Player { Name = "Alex", Team = "A", Score = 10, League = "SerieA", TotalTeamScore = 30 },
// new Player { Name = "Anna", Team = "A", Score = 20, League = "SerieA", TotalTeamScore = 30 },
// new Player { Name = "Luke", Team = "B", Score = 60, League = "SerieA", TotalTeamScore = 100 },
// new Player { Name = "Lucy", Team = "B", Score = 40, League = "SerieA", TotalTeamScore = 100 },

// new Player { Name = "Charlie", Team = "C", Score = 40, League = "PremierLeague", TotalTeamScore = 0 },
// new Player { Name = "Connor", Team = "C", Score = 40, League = "PremierLeague", TotalTeamScore = 0 },
    }

Do you know how to solve this issue?
Do you know how to properly calculate the TotalScore for each team for all Players in a league in C# LINQ extension method syntax.

A: LINQ is designed for querying, whereas you need to modify the objects in the collection.
Whilst you could do this using Enumerable.Select, a standard foreach loop would be more appropriate:
var serieAPlayers = players.Where(p => p.League == "SerieA");

var teamScores = serieAPlayers
    .GroupBy(p => p.Team)
    .ToDictionary(grp => grp.Key, grp => grp.Sum(p => p.Score));

foreach (var player in serieAPlayers) player.TotalTeamScore = teamScores[player.Team];


text:
Q: Split portions from file to separate file in bash From here Split portion of string in bash, with some code changes,  I managed to achieve the goal.
Now, I want to save the text in separate file.
I tried:
awk '/[code]:/{flag=1} flag; /[/code]:/{flag=0}{x="/home/user/split/File"++i".txt";}{print > x;}' /home/user/bigfile.nfo

but I got many files with one or no line (empty file with 0 bytes)
How to write all content between [code] and [/code] to separate file ? As many text found between those tag, as many files should be created, that's my expectation
Where is my mistake in code ?
The bigfile content
blavbl
[code]
sdasdasd
asdasd
...
[/code]

line X
line Y
etc
...

[code]
...
test
test
[/code]

blabla

[code]
Single line
[/code]

After ran script I get some files with one line instead all text between blocks
I expect to have
File1.txt
sdasdasd
asdasd
...

File2.txt
...
test
test

File3.txt
Single line

Etc

A: A few issues with OP's current code:

*

*the characters [, ] and / have special meaning in awk regex patterns; one solution is to escape said characters when looking for them as literal characters

*OP should make sure a file's descriptor is closed once no more output is going to said file (this should keep awk from (potentially) crashing due to 'out of file descriptor' errors)

*OP's current patterns include a trailing : but no such character exists in OP's sample input (ie, [code]: will not match [code])

One awk idea:
awk '
/^\[code\]/   { outfile="/home/user/split/File" ++i ".txt"; next }
/^\[\/code\]/ { close(outfile); outfile=""; next }
outfile       { print > outfile }
' bigfile.nfo

NOTE: technically ] (sans the escape \) should also work
This generates:
$ head File*.txt
==> File1.txt <==
sdasdasd
asdasd
...

==> File2.txt <==
...
test
test

==> File3.txt <==
Single line


text:
Q: Override class in library used in web project I want to patch a java class of a library I use in a war project.
I has overriden the class with a new class with same canonical name, but in a Web application the original class is still loaded first. How can I control the class loading order?
I've started from this post, and readed about JAR Hell:
Override class in java
And used the maven example found here:
http://owenou.com/2010/07/20/patching-with-class-shadowing-and-maven.html
Basically is an auxiliar project that depends on a new patched jar with the overriden class and the original library, with a MANIFEST.MF with these libraries in the correct order in classpath. So other projects could use this auxiliar project.
This works fine in a standalone application, but in a Web project the original jar is still loaded first.
Any help?

A: I had the exact same issue and here is what I did to make it work.
My project was including a "ThatProject" library containing a ServiceFactory.java class causing a bug.
<dependencies>
    <dependency>
        <groupId>com.example.ThatGroup</groupId>
        <artifactId>ThatProject</artifactId>
        <version>${ThatProject.version}</version>
    </dependency>
</dependencies>

In my own project I created a same class to shadow the one of "ThatProject" (the path must match).
→ src\main\java\com\example\ThatGroup\ThatProject\ServiceFactory.java
In my pom.xml I used the maven-shade-plugin plugin as follows.
Please note how I am excluding the original ServiceFactory.java from the "ThatProject" library.
<build>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>${maven-compiler-plugin.version}</version>
            <configuration>
                <source>${java.version}</source>
                <target>${java.version}</target>
            </configuration>
        </plugin>
        <!-- Include all dependencies in JAR -->
        <plugin>
          <artifactId>maven-shade-plugin</artifactId>
          <version>2.2</version>
          <executions>
            <execution>
              <id>shade</id>
              <goals>
                <goal>shade</goal>
              </goals>
              <phase>package</phase>
              <configuration>
                <createDependencyReducedPom>false</createDependencyReducedPom>
                <filters>
                  <filter>
                    <artifact>com.example.ThatGroup:ThatClient</artifact>
                    <excludes>
                      <exclude>com/example/ThatGroup/ThatProject/ServiceFactory.class</exclude>
                    </excludes>
                  </filter>
                </filters>
              </configuration>
            </execution>
          </executions>
        </plugin>
    </plugins>
</build>

And that's it, it finally worked for me. In my case I was including all the files of my project with this configuration of pom.xml (including my shadowing version of ServiceFactory.java).
As mentioned, the original ServiceFactory.java was excluded during the maven build.
Hope this helps!

A: A dirty solution is to remove that class from the jar containing the version that you don't like to load.
Another solution is to reorder the classpath so your version comes before the old one. From java documentation:

Specification Order
The order in which you specify multiple class path entries is
  important. The Java interpreter will look for classes in the
  directories in the order they appear in the class path variable. In
  the example above, the Java interpreter will first look for a needed
  class in the directory C:\java\MyClasses. Only if it doesn't find a
  class with the proper name in that directory will the interpreter look
  in the C:\java\OtherClasses directory.

Please note that both solution are very dirty and future modification of your code can broke your functionalities (for example changing classpath or updating a jar).
The best way will be one of the following:

*

*extends the class and use only the new class

*implements the same interface in a new class and use it

A: If you control the application client, you could try to play with jar at runtime:
See this for loading
How to load a jar file at runtime
If you want also unloading:
Dynamic loading and unloading of jar
Or, you could try to launch in your web app, at "boot" , the precedent trick. Then you be sure of what classes you get.


text:
Q: Can I use "short of being exhaustive" in this case? I'm making a list and want the reader to know that this list is not complete, that it is only a part of a larger list...
Is it correct to say "this list is short of being exhaustive" in this case?
Is there a better way to say it?
Thanks
PS: on another note, can I say "this list is anything BUT exhaustive"?

A: You could say,

items include but are not limited to [list].

Or, at some point before or after the list, you could simply say,

this list is not comprehensive.

EDIT: I realise that I haven't really answered your question, sorry!
I think the phrase this list is short of being exhaustive conveys that almost all the items are included, or at least all the relevant ones, so if that's what you mean to say then by all means use it. You could add some further explanation: ... but includes all the salient points, for example.
As stated in one of the comments, this list is anything but exhaustive conveys that the list is far from complete, and emphasises that it should not be relied upon as to the complete content of the list.

A: This is a partial, very limited, list.
par·tial
ˈpärSHəl/
adjective
adjective: partial
    1.
    existing only in part; incomplete.
    "a question to which we have only partial answers"
    synonyms:   incomplete, limited, qualified, imperfect, fragmentary, unfinished
    "a partial recovery"
    antonyms:   complete, total
    2.
    favoring one side in a dispute above the other; biased.
    "the paper gave a distorted and very partial view of the situation"
    synonyms:   biased, prejudiced, partisan, one-sided, slanted, skewed, colored, unbalanced
    "a very partial view of the situation"


text:
Q: Numbering multiple occurences of a word in a long string I have a string like this:
*******voltage:156.7;****current:44;****voltage:98;current:0.9;***voltage:45;***

where the * is long-winded junk we don't care about.  What we want to do produce a new string, identical, but to find every "voltage" and replace it with voltage1, voltage2, etc.  so each voltage reading has a unique key name.   Likewise for current (and several others).
It is not clear what is the slickest way to do this in Perl.  It must be readable by modestly skilled Perl programmers and EEs.  Ultimate speed is not important, and we'd like to stick with built-in Perl capabilities rather than use some crazy module.  None of us modestly skilled guys have found a way to do this without making a nonworking mess of code.
There's probably a nice way to do this with regexes, but if it's a complex guru-only regex, never mind!
A second green checkmark if the solution can run on the ancient Perl version 5.6

A: #!/usr/bin/env perl

use strict; use warnings;

my $s = q{*******voltage:156.7;****current:44;****voltage:98;current:0.9;***voltage:45;***};

my $counter = 0;

$s =~ s/(voltage)/$1 . ++$counter/ge;

print "$s\n";

Output:
*******voltage1:156.7;****current:44;****voltage2:98;current:0.9;***voltage3:45;
***

A: Here is a slightly-modified version of Sinan's answer that adds support for 'current'. Additional tokens can be added easily by modifying the regular expression. Each distinct token has its own counter.
#!/usr/bin/env perl

use strict; use warnings;

my $s = q{*******voltage:156.7;****current:44;****voltage:98;current:0.9;***voltage:45;***};

my %counter;

$s =~ s/\b(voltage|current)\b/$1 . ++$counter{$1}/ge;

print "$s\n";

Output:
*******voltage1:156.7;****current1:44;****voltage2:98;current2:0.9;***voltage3:45;***


text:
Q: Calling state hook from outside its component When I run my current code it produces a button for each post in a local JSON file and if I click on the button it expands/contracts. I want to have a button that opens or closes all the posts but I'm unsure how to achieve this, my logic is that since externalData is an array of Post components, handleClick should simply be calling its own function but I get the error element.setOpenStatus is not a function when I press the Open All button.
function Post(props) {
  const [openStatus, setOpenStatus] = useState(true);

  if (openStatus) {
    return (
      <button onClick={() => setOpenStatus(false)}>

Title: {props.post.title}

User: {props.post.user}

Time: {props.post.time}

Content: {props.post.content}

      </button>
    );
  }

  return (
    <button onClick={() => setOpenStatus(true)}>

Title: {props.post.title}

User: {props.post.user}

Time: {props.post.time}

    </button>
  );
}

class AllPosts extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      externalData: [],

    };

    this.handleClick = this.handleClick.bind(this);
    this.renderPost = this.renderPost.bind(this);
  }

  renderPost(element) {
    return (
      <Post
        key={element.title}
        post={element}
      />
    )
  }

  checkIfExisting(post, key, value) {
    return post[key] === value;
  }

  // HERE things are going wrong
  handleClick() {
    this.state.externalData.forEach(element => {
      element.setOpenStatus({ openStatus: false });
    });
  }

  render() {
    this.props.data.forEach((element) => {
      if (!this.state.externalData.some(
        (post) => this.checkIfExisting(post, "key", element.title)
      )) {
        this.state.externalData.push(this.renderPost(element))
      }
    })

    return (

using local json file

        <button onClick={this.handleClick}>Open All</button>

          {this.state.externalData}

    );
  }
}

export default AllPosts;


text:
Q: webpack-dev-server start but doesn't reload on file changes I can't figure out why webpack is not reloading the page when a modification is detected. DevServer starts successful but doesn't automatically reload a page when code changes in the editor (js and css). I have to manually refresh the browser to see the changes.
I lost a couple of days and tried a lot of different settings but nothing works.
Now I am in the middle of a project, I can't drop webpack and the manual reloading starts to take a few seconds due to the size of the project itself. Only can save me now DevServer automatically reload.
Can anyone help me?
My project structure:

Here is my webpack.dev.js config:
const path = require("path");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const CopyPlugin = require("copy-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const WebpackBar = require("webpackbar");

module.exports = {

mode: "development",
entry: {
       index: path.resolve(__dirname, "./src/index.js"),
},

output: {
    path: path.resolve(__dirname, "./dist"),
    filename: "js/[name].js",
},

devServer: {
    contentBase: path.join(__dirname, '/dist'),
    watchContentBase: true,
    compress: true,
    port: 9001,
    inline: true,
    historyApiFallback: true,
    watchOptions: {
        poll: true,
        ignored: "/node_modules/"
    }
},

stats: {
    modules: false,
    entrypoints: false,
},

plugins: [
    new WebpackBar({}),
    new CleanWebpackPlugin({}),
    new CopyPlugin({
        patterns: [
            { from: "src/static/img", to: "static/img" },
            { from: "src/static/models", to: "static/models" },
        ],
    }),
    new MiniCssExtractPlugin({
        filename: "css/[name].css",
    }),
    new HtmlWebpackPlugin({
        template: "./src/index.html",
        filename: 'index.html',
        inject: "body",
        chunks: ['index'],
    })
],

module: {
    rules: [
        {
            test: /\.(scss|css)$/,
            use: [
                { loader: MiniCssExtractPlugin.loader, options: {} },
                { loader: "css-loader", options: { url: false } },
                { loader: "postcss-loader", options: {} },
                { loader: "sass-loader", options: {} },
            ]
        },
    ],
},
}

Here is my script :
"live": "webpack serve --config webpack.dev.js",

message I get after run script:
i 「wds」: Project is running at http://localhost:9001/
i 「wds」: webpack output is served from /
i 「wds」: Content not from webpack is served from C:\Users\isladjan\Desktop\RaD\dist
i 「wds」: 404s will fallback to /index.html
...
i 「wdm」: Compiled successfully.

Versions I'm running:
node: v15.13.0
"webpack": "^5.24.4",
"webpack-cli": "^4.5.0",
"webpack-dev-server": "^3.11.2",

Readings from: http://localhost:9001/webpack-dev-server
files which webpack-dev-server served


text:
Q: Listening for clicks on a disabled AlertDialog-Button I want to listen for clicks on the positive button of an AlertDialog, which I have disabled by calling button.setEnabled(false);.
How should I do this? If this is not possible, is there a known workaround?
PS. The reason I want to do this, is that I want to show a toast when somebody hits the button, saying "You need to do this before you can continue".

A: This is not a way to listen for clicks on a disabled button. This is a workaround.
I liked the result I got by changing the color of the button, making it look like it's disabled.
What you want to do:
// Instantiate positive button
  final Button posButton = ((AlertDialog) getDialog()).getButton(DialogInterface.BUTTON_POSITIVE);

// Save the original button's background
  final Drawable bg = posButton.getBackground();

// Set button's looks based on boolean
  if (buttonDisabled) {
      posButton.setTextColor(getResources().getColor(R.color.disabledButtonColor, null));
         // R.color.disabledButtonColor == #DBDBDB, which is pretty close to
         //    the color a disabled button gets.
      posButton.setBackgroundColor(Color.TRANSPARENT);
         // Color.TRANSPARENT makes sure all effects the button usually shows disappear.
  } else {
      posButton.setTextColor(getResources().getColor(R.color.colorPrimaryDark, null));
         // R.color.colorPrimaryDark is the color that gets used all around my app.
         //    It was the closest to the original for me.
      posButton.setBackground(bg);
         // bg is the background we got from the original button before.
         //    Setting it here also re-instates the effects the button should have.
  }

Now, don't forget to catch your buttons actions whenever it's "disabled"
public void onClick(View v) {
    if (buttonDisabled) {
        // Button is clicked while it's disabled
    } else {
        // Button is clicked while it's enabled, like normal
    }
}

That should do, have fun with it.


text:
Q: Dell XPS 13 Ivybridge, turns off randomly when on battery My laptop works perfectly when it's plugged in but when I am on battery, it will turn off randomly. Usually after 2 or 3 hours but not always. It will occasionally not turn off but freeze completely. In that case the screen has half of the pixel green or pink and there's a bit of flickering. When I turn the laptop on, it boots normally but it may turn off randomly again after a while.
I am wondering if disabling the power saving mode on some of the laptop components could help me figure out what's wrong.
Which component with a power saving mode should I try to disable?

*

*XPS 13 Ivybridge 8Gb RAM, 256 SSD, Ubuntu 14.10

*I got this laptop 1.5 years ago. The battery lasts around 5h.

Here's what I'm getting when I do upower -i /org/freedesktop/UPower/devices/battery_BAT0
  native-path:          BAT0
  vendor:               SIMPLO
  model:                Dell
  serial:               1885
  power supply:         yes
  updated:              Thu 27 Nov 2014 10:37:25 CET (20 seconds ago)
  has history:          yes
  has statistics:       yes
  battery
    present:             yes
    rechargeable:        yes
    state:               charging
    energy:              29.4002 Wh
    energy-empty:        0 Wh
    energy-full:         34.7578 Wh
    energy-full-design:  47.286 Wh
    energy-rate:         14.1192 W
    voltage:             8.2 V
    time to full:        22.8 minutes
    percentage:          84%
    capacity:            73.5055%
    technology:          lithium-ion
  History (charge):
    1417081015  84.000  charging
  History (rate):
    1417081045  14.119  charging
    1417080955  14.134  charging

A: Proabably it is your battery that is failing.
To check this run:
upower -e

Identify your battery and run:
upower -i /org/freedesktop/UPower/devices/battery_BAT0

Change the battery "path" accordingly.

A: I have found a workaround to my issue. If I set the brightness to 50% or more, I am not experiencing any freezes. However, when the battery gets low, the screen brightness is not consistent. There are some occasional drops of the brightness level.
Changing the battery should fix my issue completely.


text:
Q: Isolating Zend_Session in PHPUnit tests I am testing authentification functionality of my site. Zend_Auth is using as authorization engine. But auth status remains between tests and I need to write 'logout' in every tearDown.
Now everything is all right. But the problem is following. As for I know Zend_Auth uses Zend_Session for storing auth data. So, session is common for all tests. I am affraid that in future it can cause problems.
Can you tell me what is the best practice to make sessions for each test isolated?
Now I can imagine only manually starting session in setUp and stop in tearDown. But I have many tests and implementing this can take a lot of time.

A: PHPUnit allows you to define a shared fixture (a common set up) for a whole test suite. However, this solution just masks a flaw in the design of the tests, since it doesn't address their dependency on a common global state. A better solution is to use test doubles, creating custom stubs of certain classes to control the behaviour of chosen parts of the system.
In this case you could try to create a stub of Zend_Auth so that it skips the use of Zend_Session and returns the desired permissions for each unit test.


text:
Q: Small balloon/box appear near nofityicon I once have noticied when my Adobe Reader was updating, I saw a small balloon like it always has been. But then I wondered how I could make one of my own balloon/box/border things near my notifyicon. In XAML, I need a small ballon/box/border to appear near a notifyicon.

A: You can use NotifyIcon to set up baloon tips.  But if you want something which looks a bit cooler check out http://www.codeproject.com/KB/WPF/wpf_notifyicon.aspx. Looking at the screenshots there you should do that for sure.

A: Here you can find more information:
For hacking it onto the Win32 API:
http://codeproject.com/csharp/notifyballoon.asp
Using XAML:
http://www.hardcodet.net/projects/wpf-notifyicon


text:
Q: Getting sensible data back from a manually rendered form in Django I have the following form that is manually rendered in a Django template. By "manually rendered" I mean that there is no corresponding Form or ModelForm object in the code (the reasons/details for not using a Form object are a bit complex, and can be safely left out of this quesion). I have a mental block now and I can't seem to work out how to get this data in a usable form within the Django view. Specifically, how do I get the respective attendance_value and attendance_remarks for each workers_pks when the form is POSTed?
<form>

            Sl
            Worker
            Worker's Gender
            Work
            Unit cost of work
            Job
            Attendance	 {# 1 or less if unit is day, 8 or less if unit is hours #}
            Remarks	 {# if any #}

    {% for result in results %}

            {{ forloop.counter }}
            {{ result.worker.name }} <input type="hidden" name="workers_pks" value="{{ result.worker.pk }}" id="id_workers_pks_{{ forloop.counter }}">
            {{ result.worker.get_gender_display }}
            {{ result.work.name }}
            {{ result.work.unit_cost }} per {{ result.work.work_unit }}
            {{ result.job_handover.job.name }}

                <input type='text' name='attendance_value' id='id_attendance_value_{{ forloop.counter }}' />

                <input type='text' name='attendance_remarks' id='id_attendance_remarks_{{ forloop.counter }}' />

    {% endfor %}

</form>

Just to clarify, I know I can get the values by doing something like
workers = request.POST.getlist('workers_pks')
attendance_values = request.POST.getlist('attendance_values')
attendance_remarks = request.POST.getlist('attendance_remarks')
My main concern is how do I get the proper attendance_value and attendance_remarks for each corresponding workers_pks

A: Use the POST attribute of the request object -
def your_view(request):
    #...
    if attendence_value in request.POST:
        at_value = request.POST['attendence_value']

However I see you've got lots of inputs with the same name attribute (and the browser will construct the post data using the input names as keys). You'll need to change that. My recollection is that when django does this (with formsets), it adds a prefix to each name so that it can identify which object the input belongs with. I see you've already done this on the ids.
UPDATE
How about adding worker.pk into your name attribute -
<input type='text' name='attendance_value{{ result.worker.pk }}'>

Then in your view build the corresponding string -
for worker in workers:
    val_str = "attendance_value" + str(worker.pk)
    rmk_str = "attendance_remarks" + str(worker.pk)
    if val_str in request.POST:
        worker.attendance_value = request.POST['val_str']
    if mrk_str in request.POST:
        worker.attendance_remarks = request.POST['rmk_str']

You might want use a different loop (maybe loop through the inputs instead). But you get the idea.


text:
Q: Problem launching android AVM/SDK gui using the tools/android executable in the android SDK. Ubuntu 10.04, i686 Hi I just installed the android SDK along with Eclipse 3.5 on my i686 Thinkpad T60 running Ubuntu 10.04 (Lucid).  (Eclipse was installed via synaptic, i.e. a package from the repository.) I installed the eclipse add on and everything on the Eclipse end seems fine.  I also put the android-sdk tools directory on my user PATH.  Now launching tools/android without any arguments is supposed to bring up the SDK and AVD manager GUI, but instead I get the following error:
Exception in thread "main" java.lang.UnsatisfiedLinkError: no swt-gtk-3550 or swt-gtk in swt.library.path, java.library.path or the jar file
    at org.eclipse.swt.internal.Library.loadLibrary(Unknown Source)
    at org.eclipse.swt.internal.Library.loadLibrary(Unknown Source)
    at org.eclipse.swt.internal.C.<clinit>(Unknown Source)
    at org.eclipse.swt.internal.Converter.wcsToMbcs(Unknown Source)
    at org.eclipse.swt.internal.Converter.wcsToMbcs(Unknown Source)
    at org.eclipse.swt.widgets.Display.<clinit>(Unknown Source)
    at com.android.sdkmanager.Main.showMainWindow(Main.java:265)
    at com.android.sdkmanager.Main.doAction(Main.java:249)
    at com.android.sdkmanager.Main.run(Main.java:94)
    at com.android.sdkmanager.Main.main(Main.java:83)

The strange thing is I definitely have all the prerequisites installed, sun-java6-jdk, and open-java6-jdk and have tried switching between them.  Also if I look in synaptic I have libswt-gtk-3.5java installed.  Also he AVM/SDK manager launches fine when I launch it with eclipse.
(You may wonder why i care, but I like working from the command line, and considering using emacs as my IDE rather than Eclipse.)
If anyone knows how i can fix this please let me know.

A: (copied from Ubuntuforums http://ubuntuforums.org/showthread.php?t=1540054)
I had the same issue 12 months on. I discovered that it was because I had made the /tmp directory "noexec" as soon as I made it executable, we were fine.
sudo mount -o remount,exec /tmp

Hope this helps someone.

A: Additionally to what the user Bart well and correctly said I suggest to pay attention into the tip bellow:
Advanced linux users or geeks more often will face this issue.
A "tweak" (usually to get more speed) applied in /etc/fstab making /tmp as noexec will cause this problem.
Just open fstab and modify the entry as follow bellow:
sudo gedit /etc/fstab
If you have something like this just comment the line or modify the content:
tmpfs /tmp tmpfs defaults,noexec,nodev,nosuid 0 0
TO:
tmpfs /tmp tmpfs defaults,nodev,nosuid 0 0

A: Have a look at
android <command> --no-ui
This doesn't require SWT/GTK at all.

A: This is an old question, but I want to propose a less 'drastic' answer...
If you don't want to change your file-system mount, an alternative is that you can change the android tools startup script to explicitly specify the temporary directory that Java should use.
e.g. in the android-studio/sdk/tools directory, right at the end of the android script file is the command that executes java:
exec "$java_cmd" \
    -Djava.io.tmpdir=/home/me/android-studio/.tmp \
    -Xmx256M $os_opts $java_debug \
    -Dcom.android.sdkmanager.toolsdir="$progdir" \
    -classpath "$jarpath:$swtpath/swt.jar" \
    com.android.sdkmanager.Main "$@"

In this example I use "/home/me/android-studio/.tmp" but of course you change that to whatever you want.
Unfortunately this change will get overwritten if you update your Android tools so you would have to reapply it each time you update. You could instead export it in your profile as a global environment property (for all Java applications) instead of editing this script.

A: i also got this problem. I solved it by changing the ownership of the android sdk home directory (that i installed in '/opt') to me.
This was done with something like:
sudo chown -R <username> /opt/android-sdk-linux

And it worked fine !

A: just a better way to show the code.. consider this a comment from @Bart answer...
for some reason it tries to exec swt-lib from /tmp. that's wrong and dumb and i have no idea who's the culprit here (android or the java lib itself)
so, if you don't want to remount /tmp as RW, just symlink that swtlib dir to some place else. i moved it to the android dir.
(0) ~
hobo$ mv /tmp/swtlib-32 android/

(0) ~
hobo$ ln -sf ~/android/swtlib-32 /tmp/swtlib-32

(0) ~
hobo$ android/android-sdk-linux/tools/android

A: Just delete contents of tmp dir.
sudo rm -rf /tmp/*

Try to launch android sdk manager afterwards.
It worked for me.

A: If you want to launch sdk-manager via commandline, another option is, try running:
> sudo android sdk

This would run in admin mode giving you required permissions


text:
Q: mail function sending lots of duplicates I'm using the mail() function within a script to notify a sector of our company on some products.
The problem is they are receiving around 4-7 emails each time.
The mail() function is used in this function:
private function notifyOnCustoms($order_with_customs,$items){
        $headers = 'X-Mailer: PHP/' . phpversion();
        $email_address = 'support@ourcompany.com';
        $subject = "Order: {$order_with_customs['order_number']} contains Custom Products";
        $message = "In {$order_with_customs['order_number']}:\n";
        $index = 0;

        foreach ($items as $item){
            if ($this->isCustom($item)){
                $filename = $this->getItemProductImage($item, $index);
                $productSKU = $item['sku'];
                preg_match('/\d{4,6})\.jpg$/', $filename, $match);
                $message.= "Product: {$productSKU}\nFilename: {$filename}\n{$match[1]}\n\n\n";
            }
        }

        mail($email_address, $subject, $headers, $message);
        file_put_contents(HOLD_ORDER_PATH . $order_with_customs['order_number'] . '.json', json_encode($order_with_customs));
    }

and the method is used here:
if($this->hasCustomProducts($order['line_items'])){
            $this->notifyOnCustoms($order, $items);
            return "Order: {$order['order_number']} has custom items. Aborting the rest of the operations.";
        }

I also have some headers of the e-mails in case they are useful.
First e-mail:
X-Spam_Bar: /
X-Spam_Report: score=-0.0 tests=NO_RELAYS version=3.3.1 cmae=v=2.1 cv=ScrOKJhu c=1 sm=0 tr=0 a=7OsogOcEt9IA:10 a=5clJ4VCmAAAA:8 a=bK9mt9LiXbnJWSs7djgA:9 a=Q2D1RClc0W0A:10 a=dUXFEdsLsVoA:10
Envelope-To: support@ourcompany.com
X-Mt-Id: DA39A3EE5E6B4B0D3255BFEF95601890AFD80709
X-Mt-Id: 7E4828DD7C3F75C0E68D1D91C27E3568B1A2A07A
Return-Path: <serveradmin@ourcompany.com>
X-Spam_Score: -0.0
Delivery-Date: Fri, 11 Mar 2016 14:13:20 -0500
Received: from n31.c04.mtsvc.net ([72.47.228.31]:38551) by n50.mail01.mtsvc.net with esmtps (UNKNOWN:AES128-SHA:128) (Exim 4.72) (envelope-from <serveradmin@ourcompany.com>) id 1aeSUx-0006HM-S0 for support@ourcompany.com; Fri, 11 Mar 2016 14:13:20 -0500
Received: from ourcompany.com by n31.c04.mtsvc.net with local (Exim 4.80.1) (envelope-from <serveradmin@ourcompany.com>) id 1aeSUr-0002ul-60 for support@ourcompany.com; Fri, 11 Mar 2016 11:13:19 -0800
X-Spam_Score_Int: 0
Message-Id: <E1aeSUr-0002ul-60@n31.c04.mtsvc.net>
Order: 6593 contains Custom Products

Last copy (6th email):
X-Spam_Bar: /
X-Spam_Report: score=-0.0 tests=NO_RELAYS version=3.3.1 cmae=v=2.1 cv=bZVSDo/B c=1 sm=0 tr=0 a=7OsogOcEt9IA:10 a=5clJ4VCmAAAA:8 a=bK9mt9LiXbnJWSs7djgA:9 a=Q2D1RClc0W0A:10 a=dUXFEdsLsVoA:10
Envelope-To: support@ourcompany.com
X-Mt-Id: DA39A3EE5E6B4B0D3255BFEF95601890AFD80709
X-Mt-Id: 7E4828DD7C3F75C0E68D1D91C27E3568B1A2A07A
Return-Path: <serveradmin@ourcompany.com>
X-Spam_Score: -0.0
Delivery-Date: Fri, 11 Mar 2016 14:04:18 -0500
Received: from n19.c04.mtsvc.net ([72.47.228.19]:59467) by n50.mail01.mtsvc.net with esmtps (UNKNOWN:AES128-SHA:128) (Exim 4.72) (envelope-from <serveradmin@ourcompany.com>) id 1aeSME-0005is-LZ for support@ourcompany.com; Fri, 11 Mar 2016 14:04:18 -0500
Received: from ourcompany.com by n19.c04.mtsvc.net with local (Exim 4.80.1) (envelope-from <serveradmin@ourcompany.com>) id 1aeSM7-0007G2-N0 for support@ourcompany.com; Fri, 11 Mar 2016 11:04:17 -0800
X-Spam_Score_Int: 0
Message-Id: <E1aeSM7-0007G2-N0@n19.c04.mtsvc.net>
Order: 6593 contains Custom Products

Edit: Including calling function
public function prepareForAPI($order){
        $mOrder = $order;
        $mItems = $this->filterItems($order['line_items']);
        $mOrder['line_items'] = $mItems;

        if($this->hasCustomProducts($mItems)){
            file_put_contents('debug/debug_info.txt', "\nOrder with custom products.\n", FILE_APPEND | LOCK_EX);
            $this->notifyOnCustoms($mOrder, $mItems);
            exit;
        }
        else{
            file_put_contents('debug/debug_info.txt', "\nSending order :D\n", FILE_APPEND | LOCK_EX);
            return $this->pushToAPI($this->formatToAPI($mOrder));
        }
    }


text:
Q: Self hosted Wordpress freezes for 20 seconds before sending the page I have a website with Wordpress and PHPBB integrated - and it's been fine for months.. then all of a sudden, it's unbelievably slow to load.
There are no errors in the apache logs, but looking at the page in firebug shows a 20 second pause, before the page is delivered.
more confusing, on the same server, same apache installation, PHPBB loads in 30ms, no delay.
I tried the hogdetector wordpress plugin, which indicates that the delay is before the header is sent - which seems to agree with firebug.
Any ideas how to troubleshoot this one further?

A: Probably a DNS lookup problem ! Check DNS configuration.

A: If you have it running on a Linux (or Linux-like environment), try running a packet sniffer on it when doing a request and see what it's asking for and pausing. Something like tcpdump or wireshark. Run that, request some pages, see what the results are. If it's a DNS problem it should show up there. If networking is fine, then you would need to next start checking for local problems with the installation.

A: One of your WP plugins is likely at fault. Try disabling them one by one and seeing which one is causing the issue.

A: I observed (tcpdump) that when WordPress is attempting to load external content from the server side, it may retry 3 times when failing, waiting ~5 seconds between each attempt. That's  a 15 seconds systematic delay if external data is permanently unavailable; with further WordPress page processing, you get to your 20 seconds response time in Firefox as I did.
I experienced this issue with a youtube plugin, which attempted to load content from youtube.com directly from server. DNS resolutions were OK on my setup, however a firewall was sending TCP RESET to WordPress connexion attempts.
I solved this by disabling server side loading of external content (may or may not be the correct approach for you), with the following directive in wp-config.php:
define('WP_HTTP_BLOCK_EXTERNAL', true);
There is a complementary directive for fine grained control:
define('WP_ACCESSIBLE_HOSTS', 'example1.com, example2.com');

A: Really odd that the blog is slow but the BBS is fine. If possible use a browser on the server (text based?) or something like wget. If performance is correct locally the only thing I can think of is a proxy problem. Of course if the local performance is poor then at least you know it's on the sever.


text:
Q: Why is this integer not incrementing twice? I am confused by the results of the code below. Why does 'b' retain a seemingly incorrect value when doing these operations?
        int a = 0;
        int b = 5;
        a = b++;
        b = b++;
        Console.WriteLine("For b = b++; b=" + b.ToString()); // b should be 7 but it's 6
        a = 0;
        b = 5;
        a = b--;
        b = b--;
        Console.WriteLine("For b = b--; b=" + b.ToString()); // b should be 3 but it's 4
        a = 0;
        b = 5;
        a = b + 1;
        b = b + 1;
        Console.WriteLine("For b = b++; b=" + b.ToString());

Output
          b=6
          b=4
          b=6

Can anyone explain this behavior in C# and how it's working?

A: That's indeed the behavior of postfix operators, as detailed here.
For instance, when you write:
b = b++;

The following happens:

*

*The current value of b is saved,

*b is incremented,

*The saved value of b is produced by the postfix ++ operator,

*The value produced by the operator is assigned to b.

Therefore, b will indeed be assigned its original value, and the incremented value is lost.

A: Because the ++ and -- operators when placed after the value will evaluate to the value itself, and then increment/decrement the value after the evaluation.
So:
int a = 0;
int b = a++;

After running this code, b will equal 0 and a will equal 1.
This is as opposed to using the operators as prefixes:
int a = 0;
int b = ++a;

After running this code, b will equal 1 and a will equal 1.
This is documented behavior and has been around for a long time.

A: The instruction a=b++ is stored on the stack but not evaluated because it was not used after that.
To get the correct result, make that instruction have a sense fro example change that line:
Console.WriteLine("For b = b++; b=" + b.ToString());

by that one:
Console.WriteLine("For a = b++; a=" + a.ToString());
Console.WriteLine("For b = b++; b=" + b.ToString()); //should give 7

A: When you use
int a = 0;
int b = 5;
a = b++;
b = b++;

You set a to be 6, and after that you set b to be 6.
When you write b to commandline, it presents 6 because a was never used when incrementing b.
If you want to use a as well, you'd have to make
int a = 1;
int b = 5;
b = b++;
b += a;
Console.WriteLine("For b = a + b++; b=" + b.ToString());

But overall I don't see any use in this kind of incrementation.


text:
Q: Spring Tool Suite (Eclipse): Update to 4.7 causes multiple SLF4J bindings After I updated my STS based on Eclipse to 4.7, the build starts with a warning:
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/C:/Users/A329865/OneDrive/Apps/sts-4.6.0.RELEASE/plugins/org.eclipse.m2e.maven.runtime.slf4j.simple_1.16.0.20200610-1735/jars/slf4j-simple-1.7.5.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [file:/C:/Users/A329865/OneDrive/Apps/sts-4.6.0.RELEASE/configuration/org.eclipse.osgi/5/0/.cp/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.slf4j.impl.SimpleLoggerFactory]
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/C:/Users/A329865/OneDrive/Apps/sts-4.6.0.RELEASE/plugins/org.eclipse.m2e.maven.runtime.slf4j.simple_1.16.0.20200610-1735/jars/slf4j-simple-1.7.5.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [file:/C:/Users/A329865/OneDrive/Apps/sts-4.6.0.RELEASE/configuration/org.eclipse.osgi/5/0/.cp/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.slf4j.impl.SimpleLoggerFactory]

Even when I use a new STS 4.7 the same warning occurs.
I think the problem can be found in this line:
SLF4J: Found binding in [file:/C:/Users/A329865/OneDrive/Apps/sts-4.6.0.RELEASE/configuration/org.eclipse.osgi/5/0/.cp/org/slf4j/impl/StaticLoggerBinder.class]

But I don't know how to deactivate it. It's not a plugin or jar-file. It seems to be a part of the osgi bundle.
Maybe my assumption is wrong, but can anybody help me?


text:
Q: How to send data from angular app components to index.js(node server) I have tried many times but I don't know how to send variables to the server
I have these 3 variables inside angular components app.component.ts
import { Component, OnInit } from '@angular/core';
import { DataService } from 'src/app/services/data.service';
import { ChartDataSets, ChartOptions, ChartType } from 'chart.js';
import { Color, Label } from 'ng2-charts';
import {
  HttpHeaders,
  HttpParams,
  HttpClientModule,
  HttpClient,
} from '@angular/common/http';

@Component({
  selector: 'app-linechart',
  templateUrl: './linechart.component.html',
  styleUrls: ['./linechart.component.scss'],
})
export class LinechartComponent implements OnInit {
  public lineChartOptions: ChartOptions = {
    responsive: true,
    maintainAspectRatio: true,
    title: {
      display: true,
      position: 'left',
      text: 'worldwide Covid 19 Case Summary',
    },
    legend: {
      position: 'top',
      align: 'start',
    },
    // We use these empty structures as placeholders for dynamic theming.
    scales: {
      xAxes: [
        {
          ticks: {
            autoSkip: true,
            //max:500
            maxRotation: 0,
            minRotation: 0,
          },
        },
      ],

      yAxes: [{}],
    },
  };
  public lineChartLabels: Label[] = [
    '2006',
    '2007',
    '2008',
    '2009',
    '2010',
    '2011',
    '2012',
  ];

  public lineChartType: ChartType = 'line';

  public lineChartLegend = true;

  public lineChartData: ChartDataSets[] = [
    { data: [65, 59, 80, 81, 56, 55, 40], label: 'Series A' },
    { data: [28, 48, 40, 19, 86, 27, 90], label: 'Series B' },
  ];

  countries: any;
  countryCode: any;
  startDate: any;
  endDate: any;

  constructor(private oip: DataService, private http: HttpClient) {}

  ngOnInit() {
    this.oip.getCountries().subscribe((data) => {
      this.countries = data;
      console.log(this.countries);
    });
  }

  getCoronaDataRange(txtSD: any, txtED: any) {
    this.startDate = txtSD.value;
    this.endDate = txtED.value;
    console.log(this.startDate);
    console.log(this.endDate);

  }

  getCountryCode(countryCode: any) {
    this.countryCode = countryCode;
    console.log(this.countryCode);
  }
}

I want to pass them to inside the parameters of  my server index.js instead of             params: {
startDate:'2019-01-05',
endDate:'2020-09-21',
countryCode:'MY'
}
const express = require('express');
const axios = require('axios');
const cors = require('cors');
const app = express();
const http = require('http');
const server = http.createServer(app);
const port = 4600;

var corsOptions = {
    origin: ["http://localhost:4200","http://localhost:4000"]
}

app.use(cors(corsOptions));

app.get('/', (req, res) => {
    res.status(200).send('starting server');
})

app.get('/corona-data', (req, res) => {

    axios({
        method: 'GET',
        baseURL: 'https://api.oip.tmrnd.com.my',
        url: 'app/t/opendata.oip.tm.com.my/coronatracker/1.0.0/country',
        params: {
            startDate:'2019-01-05',
            endDate:'2020-09-21',
            countryCode:'MY'
        },
        headers: {
            Authorization : 'Bearer 0e9ceb08-9a2c-3311-999e-59a2989deb3f'
        }
    }).then((result) => {
        console.log(result.data);
        res.status(200).json(result.data);

    }).catch(error => {
        console.error('Error Has Occured');
        console.log(error);
        res.status(500).json(error.message);
    });
});

// Start the service
server.listen(port, () => {
    console.log('Server is listening to port ' + port);
})

A: Execute the below code when you want to request your API.
const myheader = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
    let body = new HttpParams();
    body = body.set('startDate', this.startDate);
    body = body.set('countyCode', this.coutryCode);
    body = body.set('endDate', this.endDate);
    http
      .post('/your-server-api-url', body, {
        headers: myheader),
      })
      .subscribe();


text:
Q: spring boot - no main artifact I have created a Spring Boot application, I have build the project and selected the main class and I have also added properties in my pom.xml:
<properties>
        <java.version>1.8</java.version>
        <start-class>com.mua.scraper.ScraperApplication</start-class>
    </properties>

Now the problem is when I try to run the .jar file, it tell me that MainClassNotFound. Here is a snap:

Later project will be opend here
After changing the command, here is my output:

Error:
No main artifact

A: You are missing -jar to properly run the jar file. It should be:
java -jar scrapper.jar

A: Actually the problem was in my artifact, so here is what I have done:

*

*Opened Project Structure(CTRL+ALT+SHIFT+S)

*Navigate to Artifacts -> JAR ->  From module with dependencies

*Then Selected Main class, or the entry class

*Copy the output directory and link via manifest(I made the mistake here)

*Don't forget to select that directory as in the picture


text:
Q: How can I set :hover to false for elements in an iframe What I am trying to do is set the hover effect on the tumblr follow and dashboard button on the themes I make to false.
If you don't know, they have some sort of iframe with the id #tumblr_controls that they have automatically on your page with their own properties.
How would I be able to turn off the individual hover effects of those links in the iframe while preserving the click abilities and all?

A: You cannot change CSS (or JS) within an iframe from a different domain unfortunately. What you see is what you get. It was likely done like this for security reasons, for example Twitter doesn't want your site injecting dodgy code into their tweet iframe as it would reflect wrongly on them.
See this for more details 'Can I apply CSS to the elements within an iframe?'


text:
Q: Bash Shell - Change text inside tag AND remove all content inside tag I need to remove/change some content from an html file
From this one i need to remove everything , from the beggining of the div tag till the end of /div

Document generated by Confluence on 2017/03/27 09:41

                Atlassian

And here i need to change the Author and Editor names

Created by John Smith, last modified by  John Smith on 2017/03/24

I know i need to use sed , but i have no idea how to create said expressions

A: Regarding to the 1st challenge please be more specific.
This is the sed script for the 2nd challenge:
source="Created by John Smith, last modified by  John Smith on 2017/03/24"
author="new author"
editor="new editor"
result=`echo "$source" | sed "s/\(.*author'>\).*\(<\/span>,.*editor'>\).*\(<\/span.*\)/\1$author\2$editor\3/"`

echo $result


text:
Q: Euler characteristic for non-convex polyhedra. I read a little introductory book to topology.
It basically said that for any two-dimensional manifold (well maybe just the closed ones, as I think about it) its topology can be unambiguously defined by the Euler's characteristic and orientability.
Consequently it is very nice that any convex polyhedron has its Euler characteristic $\chi=2$ which means that the global topology is the same as for the sphere.
What about the examples below? In fact $\chi>2$ which occurs in these cases do not correspond to any global topologies I know.

A: If you have a space made up of triangles (a 2 dimensional simplicial complex, if you will, although this generalizes to higher dimensions as well) the Euler characteristic is just #vertices - #edges + #triangles.  The main theorem is that this number is only dependent on the underlying topological space (up to homotopy) and not on how you go about triangulating it, this is a corollary of the fact that simplicial and singular homology theories agree.  In both of these examples the underlying space is homotopy equivalent to two spheres connected at a point, so as expected they have the same Euler characteristic (3).