text:
Q: KafkaProducer cannot be created due to missing java.security.auth.login.config I am attempting to create a KafkaProducer using the akka-stream-kafka library.
INFRASTRUCTURE
Uses docker-compose, showing the kafka and zookeeper instances only.
version: '2'
services:
  zookeeper:
    image: confluentinc/cp-zookeeper:5.1.0
    hostname: zookeeper
    container_name: zookeeper
    ports:
      - "2181:2181"
    environment:
      ZOOKEEPER_CLIENT_PORT: 2181
      ZOOKEEPER_TICK_TIME: 2000

  broker:
    image: confluentinc/cp-enterprise-kafka:5.1.0
    hostname: broker
    container_name: broker
    depends_on:
      - zookeeper
    ports:
      - "9092:9092"
      - "29092:29092"
    environment:
      KAFKA_BROKER_ID: 1
      KAFKA_ZOOKEEPER_CONNECT: 'zookeeper:2181'
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://broker:9092,PLAINTEXT_HOST://localhost:29092
      KAFKA_METRIC_REPORTERS: io.confluent.metrics.reporter.ConfluentMetricsReporter
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0
      CONFLUENT_METRICS_REPORTER_BOOTSTRAP_SERVERS: broker:9092
      CONFLUENT_METRICS_REPORTER_ZOOKEEPER_CONNECT: zookeeper:2181
      CONFLUENT_METRICS_REPORTER_TOPIC_REPLICAS: 1
      CONFLUENT_METRICS_ENABLE: 'true'
      CONFLUENT_SUPPORT_CUSTOMER_ID: 'anonymous'

I can report that I have been able to connect to the cluster using a kafka-console-consumer, kafka-console-producer on the CLI and the REST API with no issues.
CONFIG
This is my typesafe config, I attempt to use a plaintext connection to connect to the client. I am trying to connect to the kafka broker without any authentication.
bootstrap.servers="localhost:29092"
acks = "all"
retries = 2
batch.size = 16384
linger.ms = 1
buffer.memory = 33554432
max.block.ms = 5000

CODE
val config = ConfigFactory.load().getConfig("akka.kafka.producer")
val stringSerializer = new StringSerializer()
ProducerSettings[String, String](config, stringSerializer, stringSerializer)
// some code has been omitted here.
Producer.plainSink(producerSettings)

EXCEPTION
This is the stacktrace that I receive, it tells me that there is no jaas config:
org.apache.kafka.common.KafkaException: Failed to construct kafka producer
    at org.apache.kafka.clients.producer.KafkaProducer.<init>(KafkaProducer.java:456)
    at org.apache.kafka.clients.producer.KafkaProducer.<init>(KafkaProducer.java:318)
    at akka.kafka.ProducerSettings.createKafkaProducer(ProducerSettings.scala:226)
    at akka.kafka.scaladsl.Producer$.$anonfun$flexiFlow$1(Producer.scala:155)
    at akka.kafka.internal.ProducerStage$DefaultProducerStage.createLogic(ProducerStage.scala:41)
    at akka.kafka.internal.ProducerStage$DefaultProducerStage.createLogic(ProducerStage.scala:33)
    at akka.stream.stage.GraphStage.createLogicAndMaterializedValue(GraphStage.scala:93)
    at akka.stream.impl.GraphStageIsland.materializeAtomic(PhasedFusingActorMaterializer.scala:630)
    at akka.stream.impl.PhasedFusingActorMaterializer.materialize(PhasedFusingActorMaterializer.scala:450)
    at akka.stream.impl.PhasedFusingActorMaterializer.materialize(PhasedFusingActorMaterializer.scala:415)
Caused by: java.lang.IllegalArgumentException: Could not find a 'KafkaClient' entry in the JAAS configuration. System property 'java.security.auth.login.config' is not set
    at org.apache.kafka.common.security.JaasContext.defaultContext(JaasContext.java:133)
    at org.apache.kafka.common.security.JaasContext.load(JaasContext.java:98)
    at org.apache.kafka.common.security.JaasContext.loadClientContext(JaasContext.java:84)
    at org.apache.kafka.common.network.ChannelBuilders.create(ChannelBuilders.java:119)
    at org.apache.kafka.common.network.ChannelBuilders.clientChannelBuilder(ChannelBuilders.java:65)
    at org.apache.kafka.clients.ClientUtils.createChannelBuilder(ClientUtils.java:88)
    at org.apache.kafka.clients.producer.KafkaProducer.<init>(KafkaProducer.java:413)
    at org.apache.kafka.clients.producer.KafkaProducer.<init>(KafkaProducer.java:318)
    at akka.kafka.ProducerSettings.createKafkaProducer(ProducerSettings.scala:226)
    at akka.kafka.scaladsl.Producer$.$anonfun$flexiFlow$1(Producer.scala:155)

How can I connect to the Kafka Cluster using no auth as required to run locally?

I have tried adding KAFKA_OPTS as an environment variable to the kafka service in docker-compose as well as adding it to the application.conf.
sasl.jaas.config="org.apache.kafka.common.security.plain.PlainLoginModule required username='confluent' password='confluent-secret';"

In the former case, some associated services such as the  kafka-rest API failed. In the latter case, I get the following exception:
org.apache.kafka.common.KafkaException: Failed to construct kafka producer
    at org.apache.kafka.clients.producer.KafkaProducer.<init>(KafkaProducer.java:456)
    at org.apache.kafka.clients.producer.KafkaProducer.<init>(KafkaProducer.java:318)
    at akka.kafka.ProducerSettings.createKafkaProducer(ProducerSettings.scala:226)
    at akka.kafka.scaladsl.Producer$.$anonfun$flexiFlow$1(Producer.scala:155)
    at akka.kafka.internal.ProducerStage$DefaultProducerStage.createLogic(ProducerStage.scala:41)
    at akka.kafka.internal.ProducerStage$DefaultProducerStage.createLogic(ProducerStage.scala:33)
    at akka.stream.stage.GraphStage.createLogicAndMaterializedValue(GraphStage.scala:93)
    at akka.stream.impl.GraphStageIsland.materializeAtomic(PhasedFusingActorMaterializer.scala:630)
    at akka.stream.impl.PhasedFusingActorMaterializer.materialize(PhasedFusingActorMaterializer.scala:450)
    at akka.stream.impl.PhasedFusingActorMaterializer.materialize(PhasedFusingActorMaterializer.scala:415)
Caused by: org.apache.kafka.common.KafkaException: java.lang.IllegalArgumentException: No serviceName defined in either JAAS or Kafka config
    at org.apache.kafka.common.network.SaslChannelBuilder.configure(SaslChannelBuilder.java:125)
    at org.apache.kafka.common.network.ChannelBuilders.create(ChannelBuilders.java:140)
    at org.apache.kafka.common.network.ChannelBuilders.clientChannelBuilder(ChannelBuilders.java:65)
    at org.apache.kafka.clients.ClientUtils.createChannelBuilder(ClientUtils.java:88)
    at org.apache.kafka.clients.producer.KafkaProducer.<init>(KafkaProducer.java:413)
    at org.apache.kafka.clients.producer.KafkaProducer.<init>(KafkaProducer.java:318)
    at akka.kafka.ProducerSettings.createKafkaProducer(ProducerSettings.scala:226)
    at akka.kafka.scaladsl.Producer$.$anonfun$flexiFlow$1(Producer.scala:155)
    at akka.kafka.internal.ProducerStage$DefaultProducerStage.createLogic(ProducerStage.scala:41)
    at akka.kafka.internal.ProducerStage$DefaultProducerStage.createLogic(ProducerStage.scala:33)
Caused by: java.lang.IllegalArgumentException: No serviceName defined in either JAAS or Kafka config
    at org.apache.kafka.common.security.kerberos.KerberosLogin.getServiceName(KerberosLogin.java:297)
    at org.apache.kafka.common.security.kerberos.KerberosLogin.configure(KerberosLogin.java:87)
    at org.apache.kafka.common.security.authenticator.LoginManager.<init>(LoginManager.java:52)
    at org.apache.kafka.common.security.authenticator.LoginManager.acquireLoginManager(LoginManager.java:89)
    at org.apache.kafka.common.network.SaslChannelBuilder.configure(SaslChannelBuilder.java:114)
    at org.apache.kafka.common.network.ChannelBuilders.create(ChannelBuilders.java:140)
    at org.apache.kafka.common.network.ChannelBuilders.clientChannelBuilder(ChannelBuilders.java:65)
    at org.apache.kafka.clients.ClientUtils.createChannelBuilder(ClientUtils.java:88)
    at org.apache.kafka.clients.producer.KafkaProducer.<init>(KafkaProducer.java:413)
    at org.apache.kafka.clients.producer.KafkaProducer.<init>(KafkaProducer.java:318)


text:
Q: Multiline Label On UIButton Swift I've been trying to get a sync button to display Last Sync at (time&date). But All I get is one line with shortened text.
// Sync Button

syncBtn.frame = CGRectMake(15, height-60, 120, 40)

syncBtn.addTarget(self, action: "syncBtnPressed", forControlEvents: UIControlEvents.TouchUpInside)

syncBtn.setTitle("Last Sync: Never", forState: UIControlState.Normal)

syncBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)

syncBtn.layer.borderColor = UIColor.whiteColor().CGColor

syncBtn.layer.borderWidth = 1

syncBtn.layer.cornerRadius = 5

syncBtn.titleLabel?.font = UIFont(name: "Avenir", size: 10)

syncBtn.alpha = 0.5

syncBtn.titleLabel?.sizeToFit()

syncBtn.titleLabel?.textAlignment = NSTextAlignment.Center

syncBtn.titleLabel?.numberOfLines = 2

self.view.addSubview(syncBtn)

This is the function to get and set the date on the label
func printTimestamp(){
    var timestamp = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .ShortStyle, timeStyle: .ShortStyle)
    self.syncBtn.titleLabel?.text = ("Last Sync at: " + timestamp)
}

Anyone able to solve this problem?

A: create a UIButton with Multiple lines of text

Possible  programtically

  override func viewDidAppear(animated: Bool){
    super.viewDidAppear(animated)
      btnTwoLine.setTitle("Mulitple line", forState:     UIControlState.Normal)
      btnTwoLine.titleLabel!.lineBreakMode = NSLineBreakMode.ByWordWrapping;

    }

A: Use SetTitle method instead of .text , when you use .text it sets the title text but the constraints are not updated accordingly hence you need to use SetTitle method and set the adjustsFontSizeToFitWidth to true
self.syncBtn.setTitle(timeStamp, forState: UIControlState.Normal)
self.syncBtn.titleLabel?.adjustsFontSizeToFitWidth = true

redpajama_set_name: RedPajamaStackExchange


text:
Q: Keyup input not getting value I'm trying to write a small script so whenever the user inputs some text on the webpage it will get me the value instantly. Unfortunately the Keyup() JQUERY function is returning no value when I try to test it.
$(document).ready(function() {
    $(document).keyup(function() {
        var command = $(this).val();
        alert(command);
    });
});

The alert shows no text what-so-ever and i'm unsure why?

A: Your selector is $(document) which has no value.
You can get value only if your selector is any input.
If you want to get character type by user then try it as follow
$(document).keyup(function(e) {
    var command = String.fromCharCode(e.which);
    alert(command);
});

A: Try this code.
<!DOCTYPE html>
    <html>
    <head>
        <title></title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    </head>
    <body>
    <script type="text/javascript">
    $(document).ready(function() {
        $("input").keyup(function() {
            var command = $(this).val();
            alert(command);
        });
    });
    </script>
    <input type="text">
    </body>
    </html>

A: I have modified the snippet
$(document).ready(function() {
$(document).keyup(function(e) {
    var command = $(e.target).val()
    alert(command);
});
});

$(this) always remain where you are binding the event which is document in your case but e.target provides current element where you are using your event.

A: *

*There are various ways to fix it. It is like two way binding.

*You can play with keyup/keydown events of jquery

*Other wise you can prefer AngularJS which has built in functionality of two way binding.


text:
Q: Question Regarding Usage of Verb "Expect' People often say things like 'It only expects to get worse.' I just want to be on the safe side. You can place an inanimate subject or pronoun like 'it' or 'the rain' before the verb 'expects,' right?

A: Your sentence should be written as: "It is only expected to get worse." Or, "It is expected to rain."


text:
Q: styling a menulist in xul Is there a way to style a menulist in XUL?
I'm using this code but the image is appearing inside the dropdownlist and keeping the original style of the arrow.
menulist,menupopup{
    -moz-appearance: none !important;
    list-style-image: url("chrome://myExt/skin/images/lang.png") !important;

}
Thanks in advance,

A: What you are apparently attempting to style isn't the <menulist> tag itself but the anonymous <dropmarker> tag inside it. This will work:
menulist > dropmarker {
  -moz-appearance: none;
  border-style: none;
  list-style-image: url("chrome://myExt/skin/images/lang.png");
}

For more information on anonymous nodes see XUL implicit elements.


text:
Q: Simplest way to add a bibliography using a .bib file I have written a little essay and tried to add a bibliography. I get all kinds of errors and searched the last 5 hours for solutions, only to find out how little I know about latex...
I am using Miktex and Texmaker. I made a simple version of my .tex file to post here:
\documentclass[]{article}
\usepackage[autostyle]{csquotes}
\usepackage[ngerman]{babel}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{biblatex}
\addbibresource{referenzen}

\begin{document}
\section{Introduction}
Lorem ipsum \cite{dirac}
\printbibliography
\end{document}

Bib file:
@article{valueSensitiveDesign,
    author = {Friedman, Kahn et al},
    title = {Value Sensitive Design},
    year = "2008"
}

@book{dirac,
    title = {The Principles of Quantum Mechanics},
    author = {Paul Adrien Maurice Dirac},
    isbn = {9780198520115},
    series = {International series of monographs on physics},
    year = {1981},
    publisher = {Clarendon Press},
    keywords = {physics}
}

@article{Lee2009a,
author = {Lee, Geun},
journal = {The Korean Journal of Defense Analysis},
number = {2},
pages = {205--218},
title = {{A Theory of Soft Power and Korea's Soft Power Strategy}},
volume = {21},
year = {2009}
}

I've setup Texmaker to do 'pdflatex > show pdf'. But then the bibliography is not printed. I researched this and people say that you need to 'latex > biblatex > latex 2x > show pdf', but I don't have that. I have similar options, but the I get the error:

This is BibTeX, Version 0.99d (MiKTeX 20.6.29) The top-level auxiliary
file: prototype.aux I found no \citation commands---while reading file
prototype.aux I found no \bibdata command---while reading file
prototype.aux I found no \bibstyle command---while reading file
prototype.aux (There were 3 error messages)

Texmaker doesn't seem to give me an option to do it the correct way (and this gets way to complicated for me). Here is a screenshot of my configuration options (sorry it's in German):

My problem seems to be so simple, but I feel like a need to do a full latex tutorial to get any idea what I m doing. I feel like there might be some conflicting packages. Can anyone please explain whats going on here?

A: You need to define biblatex backend either bibtex or biber as displayed below and it works well. I advice you to give Texstudio a try. Good Luck.
\documentclass[]{article}
\usepackage[autostyle]{csquotes}
\usepackage[ngerman]{babel}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[backend=bibtex]{biblatex}
\addbibresource{referenzen.bib}

\begin{document}
\section{Introduction}
Lorem ipsum \cite{dirac}

\printbibliography
\end{document}


text:
Q: erro ao aplicação no homolog Bom dia,
Eu estou passando um problema na versão homolog do projeto
The index 'IX_ReqCompraId_Id' is dependent on column 'ReqCompraId'.
The object 'FK_dbo.Pedidos_dbo.ReqCompra_ReqCompraId' is dependent on column 'ReqCompraId'.
The object 'FK_dbo.Pedidos_dbo.ItemRC_ReqCompraId_Id' is dependent on column 'ReqCompraId'.
ALTER TABLE DROP COLUMN ReqCompraId failed because one or more objects access this column.

Ja tentei fazer os seguintes comandos para mudar o nome de Id2 para id mas continua sem sucesso
ALTER TABLE [dbo].[Pedidos] DROP CONSTRAINT [PK_dbo.Pedidos]
GO

EXECUTE sp_rename @objname = N'dbo.Pedidos.Id2', @newname = N'Id', @objtype = N'COLUMN'

ALTER TABLE [dbo].[Pedidos] ADD  CONSTRAINT [PK_dbo.Pedidos] PRIMARY KEY CLUSTERED
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO

CREATE NONCLUSTERED INDEX [IX_ReqCompraId_Id] ON [dbo].[Pedidos]
(
    [ReqCompraId] ASC,
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO


text:
Q: how to store document in filnet in specific path based on properties? is it doable to save a document  in specific folder in filenet without providing the path or folder id from the client application by configuring the document class to be saved in the specific path based on properties or metadata ?

A: If I understand your question, you want documents to be automatically saved in a folder, but the specific folder depends on what properties the created document has. If that's the case, I suggest you use an EventActionHandler and an asynchronous Subscription that listens to the document's Creation Event. It requires a bit of coding, but a few lines of code should be enough.
Check out the API documentation here:
https://www.ibm.com/support/knowledgecenter/en/SSNW2F_5.5.0/com.ibm.p8.ce.dev.java.doc/com/filenet/api/engine/EventActionHandler.html

A: Once you create your java class and add it as a code module, you can create an Event Action to invoke that action on document check-in. You probably want to invoke it on any check-in so if they change the controlling property, it will change the filed folder(s).


text:
Q: alter "required" property of the form element in drupal 7 I have some require fields in some form,I want them  be required in somewhere and in another place not be required (I want exactly them , maybe you suggest me use existance field in cck but this  fields not in cck.)
I used profile2 module with some profile type, I want in profile type edit page as example name field be required and in user registration name field not be required.
I try to alter #require property of name field in form alter, it's changed correctly  but in validation tell me the name field is required.
in
      function mymodule_form_alter(&$form,&$form_state) {
            if ($form_id == 'user_register_form') {
              $form['profile_detailp']['field_name']['und']['#required']=0;
              ...
              }

      }

any idea ?

A: Your method is ok, and have to works but maybe in another module  it require again.
     function mymodule_form_alter(&$form,&$form_state) {
        if ($form_id == 'user_register_form') {
          $form['profile_detailp']['field_name']['und']['#required']=0;
          ...
          }

  }

A: Text field need do it like this
function mymodule_form_alter(&$form,&$form_state) {
  if ($form_id == 'user_register_form') {
    $form['profile_detailp']['field_name']['und'][0]['value']['#required']=0;
  }
}


text:
Q: MySQL python normalization of tuple fails in query When I try to pass a tuple to the IN argument of a WHERE clause, it gets double-quoted so my query fails.  For example, if I do this,
# Connect to DB
import MySQLdb
cnxn = MySQLdb.connect(connectString)
curs = cnxn.cursor()
# Setup query
accounts = ('Hyvaco','TLC')
truck_type = 'fullsize'
query_args = (truck_type, accounts)
sql ='SELECT * FROM archive.incoming WHERE LastCapacity=%s AND Account IN %s'
# Run query and print
curs.execute(sql, query_args)
print(curs._executed)

then I get zero rows back, and the query prints out as
SELECT * FROM archive.incoming WHERE LastCapacity='fullsize'
   AND Account IN ("'Hyvaco'", "'TLC'")

Switching accounts from a tuple to a list does not affect the result.  How should I be passing these arguments?

A: How about you create the accounts as a string and then do this:
accounts = "('Hyvaco','TLC')"

sql ='SELECT * FROM archive.incoming WHERE LastCapacity=%s AND Account IN '+ accounts


text:
Q: Why am I receiving Oracle error-ORA-01790 when trying to join to tables? I have two tables I am using to join together to produce a new table that contains the sum of two fields called "forecast" and "closed", along with its metadata.
The issue I am having
is that since in I have a condition where if the value is 'Green' then insert a '-' sign. Intuitively, when I do a sum on that column, it gives me an error of "expression must have same datatype as corresponding expression". Is there a way to write a case
statement within my script to circumvent that or a different solution?
Table1:
chart_date | FLAG | MESSAGING | FORECAST  | CLOSED
21-JUL-20     NULL   BLUE           10       10
22-JUL-20     NULL   BLUE           10       20
23-JUL-20     NULL   BLUE           10       106
21-JUL-20     NULL   GREEN          -        356
22-JUL-20     NULL   GREEN          -        457
23-JUL-20     NULL   GREEN          -        65
21-JUL-20     NULL   RED            5        13
22-JUL-20     NULL   RED            5        223
23-JUL-20     NULL   RED            5        11

Table2- which holds our static data:
chart_date | FLAG | HEADER     | METRIC  | FORECAST
20-JUL-20     1      TYPE        BLUE        0
20-JUL-20      8      TYPE       GREEN       0
20-JUL-20      9      TYPE       RED         0

Here is the code I am using:
with t2
as (
select
b.flag,
b.metric messaging,
NVL(a.INCOMING,0)   INCOMING,
case when b.metric in
('GREEN'
) then  '-'
else to_char((NVL(round(a.Forecast,0),0))) end as Forecast
from
DB1.TABLE2 b
inner join
DB1.TABLE1 a
on (a.messaging=b.metric)
where b.header='MESSAGING'
and a.messaging in ('RED','GREEN','BLUE' )
)
select flag,messaging, SUM(NVL(INCOMING,0)) AS CLOSED_SUM, SUM(NVL(FORECAST,0)) as FORECAST_SUM
from t2  group by flag, messaging, FORECAST
union
select
a.flag,a.metric,0,'0'
from DB1.TABLE2 a
left join
t2
on (t2.messaging=a.metric)
where t2.messaging is null
and a.header like 'MESSAGING'
and a.metric  in ('RED','GREEN','BLUE' )

This is the error message I get:
ORA-01790: expression must have same datatype as corresponding expression
01790. 00000 -  "expression must have same datatype as corresponding expression"
*Cause:
*Action:
Error at Line: 24 Column: 57

As you can see, it outputs each type by its date but it doesn't group then together to create a sum column.
This is the Desired Output I want:
FLAG | MESSAGING | FORECAST_SUM  | CLOSED_SUM
1      RED           15                247
8      BLUE          30                136
9      GREEN         -                 878

No duplicates, just each type and its sum of the forecast field and closed_sum field This seems like a somewhat easy fix but I have been debugging for hours but to no avail, so any ideas or suggestions will help!

A: I think the data types in the union need to be matching. I see in the code the following:
a.flag,a.metric,0,'0'

Can you try this below to see if it works?
a.flag,a.metric,0,0

A: I simply joined two tables with inner join then calculate the sum of forecast and closed columns of Table1 then grouped by chart_date ,flag,header,metric columns from Table2. Please check.
Query:
select b.chart_date ,b.flag,b.header,b.metric,sum(a.forecast)forcast_sum,sum(a.closed)closed_sum
from Table1 a inner join Table2 b on a.messaging=b.metric
group by b.chart_date ,b.flag,b.header,b.metric

Output:

CHART_DATE
FLAG
HEADER
METRIC
FORCAST_SUM
CLOSED_SUM

20-JUL-20
1
TYPE
BLUE
30
136

20-JUL-20
8
TYPE
GREEN
-
878

20-JUL-20
9
TYPE
RED
15
247


text:
Q: flutter NoSuchMethodError: The getter 'lat' was called on null When searching through Google Maps, a function that returns a location is used, and null is called.
The placeDetail class is initialized and used, but I don't know what the problem is.
void _moveCamera() async {
try{
  GoogleMapController controller = await _mapController.future;
  controller.animateCamera(
    CameraUpdate.newLatLng(
        LatLng(
            placeDetail.lat,
            placeDetail.lng)),
  );
} catch(e) {
  print("error?? -$e");

}

print("noo - ${placeDetail.lat}");
print("noo - ${placeDetail.lng}");

setState(() {
  _markers.add(
      Marker(
    markerId: MarkerId(placeDetail.name),
    position: LatLng(placeDetail?.lat, placeDetail.lng),
    infoWindow: InfoWindow(
        title: placeDetail.name,
        snippet: placeDetail.formattedAddress),
  ));
});
}

json을 받아온 부분은 문제가 없는 걸로 생각됩니다.
formatted_address: 대한민국 서울특별시 은평구 응암동, geometry: {location: {lat: 37.5942526, lng: 126.9185857}, 이렇게 출력이됩니다.
I initialized it here.
void getCurrentPosition() async {
LocationData pos = await location.getLocation();
setState(() {
  currentPos = LatLng(
    pos.latitude,
    pos.longitude,
  );
});

placeDetail = PlaceDetail(lng: pos.longitude, lat: pos.latitude);
print('google mapff - ${currentPos.latitude}');

GoogleMapController mapCtrl = await _mapController.future;
mapCtrl.animateCamera(
  CameraUpdate.newCameraPosition(
    CameraPosition(
        target: LatLng(
            currentPos.latitude,
            currentPos.longitude),
        zoom: zoomLevel),
  ),
);

}

A: Where have you defined placeDetail ? You have to make sure placeDetail is within the scope of the code being executed.


text:
Q: Junit Test return status code 200, expected 400 I integrated validation with RestControllerAdvice in RestController.
When I request invalid parameter to this controller using postman, it returns reponse code 400.
But in junit test code, it returns 400.
If you let me know what should I do, I'll appreciate.
Here are my codes.
My junit version is 5.8.2
Controller
package com.example.applyhome.api.home.controller;

import com.example.applyhome.api.common.domain.ApiResponse;
import com.example.applyhome.api.common.service.ApiService;
import com.example.applyhome.api.home.service.HomeService;
import com.example.applyhome.module.annotation.Api;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

@RestController
@RequiredArgsConstructor
@Slf4j
@Validated
@Api
public class HomeController {
  private final HomeService homeService;
  private final ApiService apiService;

  @GetMapping("/homes/{month}")
  public ResponseEntity<ApiResponse> getHome(
          @PathVariable("month")
          @Size(min = 6, max = 6)
          @NotNull
          @Pattern(regexp = "^\\d{4}(0[1-9]|1[0-2])$")
          String month) {

    return apiService.okResponse(homeService.getHomeList(month));
  }
}

RestControllerAdvice
package com.example.applyhome.api.common.advice;

import com.example.applyhome.api.common.domain.ApiResponse;
import com.example.applyhome.api.common.service.ApiService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ValidationException;

@RestControllerAdvice
@RequiredArgsConstructor
@Slf4j
public class ExceptionControllerAdvice {
  private final ApiService apiService;

  @ExceptionHandler(ValidationException.class)
  public ResponseEntity<ApiResponse> validationExceptionHandler(ValidationException ve) {
    log.error(ve.getMessage());
    return apiService.badRequest(ve.getMessage().split(","));
  }

}

ControllerTest
package com.example.applyhome.api.home.controller;

import com.example.applyhome.api.common.advice.ExceptionControllerAdvice;
import com.example.applyhome.api.common.service.ApiService;
import com.example.applyhome.api.home.service.HomeService;
import org.junit.jupiter.api.*;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.validation.Validator;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

import static org.hamcrest.Matchers.*;
import static org.mockito.Mockito.mock;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = HomeController.class)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class HomeControllerTest {
  private MockMvc mockMvc;
  @MockBean
  private HomeService homeService;
  @MockBean
  private ApiService apiService;

  @BeforeEach
  public void setUp() {
    mockMvc = MockMvcBuilders.standaloneSetup(new HomeController(homeService, apiService))
            .setValidator(mock(Validator.class))
            .setControllerAdvice(new ExceptionControllerAdvice(apiService))
            .build();
  }

  @Test
  @Order(1)
  void pathVariableTest1() throws Exception{
    mockMvc.perform(MockMvcRequestBuilders.get("/api/homes/" + todayMonth().substring(0, 1))
                    .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isBadRequest())
            .andDo(MockMvcResultHandlers.print());
  }
  @Test
  @Order(2)
  void pathVariableTest2() throws Exception{
    mockMvc.perform(MockMvcRequestBuilders.get("/api/homes/" + todayMonth().substring(0, 2))
                    .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isBadRequest())
            .andDo(MockMvcResultHandlers.print());
  }
  @Test
  @Order(3)
  void pathVariableTest3() throws Exception{
    mockMvc.perform(MockMvcRequestBuilders.get("/api/homes/" + todayMonth().substring(0, 3))
                    .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isBadRequest())
            .andDo(MockMvcResultHandlers.print());
  }
  @Test
  @Order(4)
  void pathVariableTest4() throws Exception{
    mockMvc.perform(MockMvcRequestBuilders.get("/api/homes/" + todayMonth().substring(0, 4))
                    .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isBadRequest())
            .andDo(MockMvcResultHandlers.print());
  }

  @Test
  @Order(5)
  void pathVariableTest5() throws Exception{
    mockMvc.perform(MockMvcRequestBuilders.get("/api/homes/2022" + todayMonth().substring(0, 5))
                    .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isBadRequest())
            .andDo(MockMvcResultHandlers.print());
  }

  @Test
  @Order(6)
  void pathVariableTest6() throws Exception{
    mockMvc.perform(MockMvcRequestBuilders.get("/api/homes/" + todayMonth())
                    .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andDo(MockMvcResultHandlers.print());
  }
  @Test
  @Order(7)
  void pathVariableTest7() throws Exception{
    mockMvc.perform(MockMvcRequestBuilders.get("/api/homes/" + todayMonth() + "0")
                    .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isBadRequest())
            .andDo(MockMvcResultHandlers.print());
  }

  @Test
  @Order(8)
  void pathVariableTest8() throws Exception{
    mockMvc.perform(MockMvcRequestBuilders.get("/api/homes/" + todayMonth() + "01")
                    .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isBadRequest())
            .andDo(MockMvcResultHandlers.print());
  }

  @Test
  @Order(9)
  void regexpTest1() throws Exception{
    mockMvc.perform(MockMvcRequestBuilders.get("/api/homes/202213")
                    .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isBadRequest())
            .andDo(MockMvcResultHandlers.print());
  }

  @Test
  @Order(10)
  void regexpTest2() throws Exception{
    mockMvc.perform(MockMvcRequestBuilders.get("/api/homes/abc")
                    .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isBadRequest())
            .andDo(MockMvcResultHandlers.print());
  }
  private String todayMonth() {
    return LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMM"));
  }
}

Thank you.


text:
Q: Calculation of angles in regular polyhedrons For any regular polyhedron (tetrahedron, cube, octahedron, dodecahedron, icosahedron, ...), how do I calculate an angle from the center of the regular polyhedron to the center of each face? Obviously, the angle decreases with the increasing number of faces. What is the formula, when the number of faces n is the variable?

For cube, n= 6, the angle is 90 degrees:

A: Théophile's answer is probably the more practical one, but here is a nice technique that works for all regular polytopes in all dimension:
If $P$ is a regular polytope, let $G^\circ$ be the edge-graph of its polar dual (e.g., if $P$ is the cube, then $G^\circ$ is the edge-graph of the octahedron).
Alternatively, $G^\circ$ is the graph in which the vertices are the facets of $P$, and two are adjacent in $G^\circ$ if they are incident.
Let $\theta_2$ be the second-largest eigenvalue of the adjacency matrix of $G^\circ$, then the desired angle $\alpha$ is
$$\alpha=\cos^{-1}\!\Big(\frac{\theta_2}{\mathrm{deg}(G^\circ)}\Big),$$
where $\mathrm{deg}(G^\circ)$ is the vertex-degree of $G^\circ$.

A: What you're describing is the supplementary angle of the dihedral angle of the solid. This latter angle $\theta$ is the interior angle between two connected faces, with
$$\sin\frac\theta2 = \frac{\cos\frac\pi q}{\sin\frac\pi p}$$
for a solid with Schläfli symbol $\{p,q\}$. See the full chart in the Wikipedia article on Platonic solids.
Therefore, taking the supplement, you're looking for
$$2\pi - \theta.$$

A: A full outline on corner angles of polygons, dihedral angles of polyhedra, and dihedral angles of polychora can be found here: https://bendwavy.org/klitzing/explain/dihedral.htm
It also includes the asked for supplements as well as an explicite listing of all relevant cases, even the acrons.
--- rk


text:
Q: converting oracle trigger to sql server trigger I'm little confused converting the oracle trigger to sql server. Any pointers is highly appreciated. I'm not sure how to replace "if inserting then" and "if updating then" in sql server ?
  create or replace trigger tg_ap
  before insert or update of strno, strfac, strfacstreet, strfacstreet2
  on AP
  for each row
  begin
  if inserting then
  :new.I_stat_ind:= 'Insert';
  end if;
   if updating then
      :new.I_stat_ind:= 'Update';
   end if;
   END;

A: SQLServer makes it a bit tricky when it comes to detecting if the operation is an Update, Insert or Delete.
I will not write your Trigger, but here is some code that should help you to find out the current operation:
Create Trigger [name] on [table] Before Insert, Update As
Begin
declare @actionId int

select @actionId = case
                       when i.id is not null and d.id is     null then 1 -- insert
                       when i.id is not null and d.id is not null then 2 -- update
                       when i.id is     null and d.id is not null then 3 -- delete
                     end
  from      inserted i full join deleted  d on d.id = i.id

Your Code goes here


text:
Q: Object reference undefined in code, but not in console when I put this in my app.js:
var titres = document.querySelectorAll('header ul li a')

console.log(titres)

It send me back this: []
if I put this in the console on the browser :
var titres = document.querySelectorAll('header ul li a')

titres send me back this: [a,a,a,a,a]
Someone knows why please ?

A: When you type those statements into the console, the page has already been fully parsed, so the elements are found and your are returned an "array-like" object containing references to those elements.
But, most likely, when you try it with the code in app.js, your app.js file is being executed before the entire HTML page has been parsed into memory, like this:
<!DOCTYPE html>
<html>
  <head>
    <title></title>
    <!-- At this point, the rest of the HTML hasn't been parsed yet, so
         if app.js tries to query for those elements, they won't be found! -->
    <script src="app.js"></script>
  </head>
  <body>

  .  .  .

Try either putting the <script src="app.js"></script> code just before the closing of the body element (so that it runs after the HTML is already parsed) like this:
    .  .  .
    <script src="app.js"></script>
  </body>
</html>

or leave the script tag at the top of the page, but inside the app.js file, wrap your code in an event handler like this:
window.addEventListener("DOMContentLoaded", function(){
    var titres = document.querySelectorAll('header ul li a')
    console.log(titres)
});

which will defer the execution of the code until after the HTML is loaded.


text:
Q: protobuf-net faulty enum exception (issue 422) need a good workaround I am working in a project that uses ProtoBuf in different languages among them .NET. For .NET we use protobuf-net.
We have extended enums and they work on the other platforms but in .NET we get a exception when trying to de-serialize.
When googling this i found this Issue 422.
Does anyone have a good workaround or know what to download and compile for a local fix. We would prefer not to introduce weird extra enums or other weird stuff that goes against the Protobuf definition.


text:
Q: Conversión de un tipo de datos string a double. C# Cómo convertir un objeto string a double sin perder precision, por ejemplo 12.9 (string) a double.

A: Buenas.
Para convertir un numero desde string a double se usa:
Convert.ToDouble(value);

Esto está documentado en Convert to double.
Cuando la conversión pierda precisión, se lanzará una excepción.
También es importante mencionar que esta función hace una llamada a Double.Parse() con el formato de la cultura en la que el programa esta ejecutándose, esto afecta en la forma en la que se interpreta el valor con referencia a elementos como el . (punto) o la , (coma). Para formatear la entrada sin considerar la configuracion cultural local se usa:
double.Parse(value, CultureInfo.InvariantCulture)

Se pueden ver ejemplos del uso de los distintos formatos en IFormatProvider Interface
Cuando necesites mas precisión, puedes usar el tipo Decimal.
Este tiene un rango de (-7.9 x 1028 hasta 7.9 x 1028) / (100 hasta 28)

A: Puedes hacerlo de esta forma:
string convertirvalor ="12.9";
double valorconvertido = double.Parse(convertirvalor);

A: Necesitas usar el método Convert.ToDouble que lo puedes usar de la siguiente manera
Convert.ToDouble(string);

te dejo la documentacion de Microsoft por si te sirve consultarla.


text:
Q: Type Error in PyCharm Using "Pandas" and "Seaborn" I am currently using Python with the IDE PyCharm to plot a data frame generated in pandas with seaborn. I am appliing the following code:
from matplotlib import pyplot as plt
import pandas as pd
import seaborn as sns

netflix_stocks = pd.read_csv("NFLX.csv")
dowjones_stocks = pd.read_csv("DJI.csv")
netflix_stocks_quarterly = pd.read_csv("NFLX_daily_by_quarter.csv")

# rename columns
netflix_stocks.rename(columns = {'Adj Close': 'Price'}, inplace = True)
dowjones_stocks.rename(columns = {'Adj Close': 'Price'}, inplace = True)
netflix_stocks_quarterly.rename(columns = {'Adj Close': 'Price'}, inplace = True)

# visualizing the netflix quarterly data
ax = plt.subplot()
sns.violinplot(data = netflix_stocks_quarterly, x = "Quarter", y = "Price")
ax.set_title("Distribution of 2017 Netflix Stock Prices by Quarter")
plt.xlabel("Business Quarters in 2017")
plt.ylabel("Closing Stock Price")

plt.savefig("Distribution of 2017 Netflix Stock Prices by Quarter.png")
plt.show()

which leads me to the error message
Traceback (most recent call last):
  File "D:\testproject\venv\lib\site-packages\numpy\core\getlimits.py", line 459, in __new__
    dtype = numeric.dtype(dtype)
TypeError: 'NoneType' object is not callable
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "D:\Program Files (x86)\PyCharm Community Edition 2021.3.1\plugins\python-ce\helpers\pydev\pydevd.py", line 1483, in _exec
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "D:\Program Files (x86)\PyCharm Community Edition 2021.3.1\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "D:/testproject/main.py", line 18, in <module>
    sns.violinplot(data = netflix_stocks_quarterly, x = "Quarter", y = "Price")
  File "D:\testproject\venv\lib\site-packages\seaborn\_decorators.py", line 46, in inner_f
    return f(**kwargs)
  File "D:\testproject\venv\lib\site-packages\seaborn\categorical.py", line 2408, in violinplot
    plotter.plot(ax)
  File "D:\testproject\venv\lib\site-packages\seaborn\categorical.py", line 1043, in plot
    self.draw_violins(ax)
  File "D:\testproject\venv\lib\site-packages\seaborn\categorical.py", line 801, in draw_violins
    self.draw_box_lines(ax, violin_data, support, density, i)
  File "D:\testproject\venv\lib\site-packages\seaborn\categorical.py", line 967, in draw_box_lines
    ax.scatter(center, q50,
  File "D:\testproject\venv\lib\site-packages\matplotlib\__init__.py", line 1412, in inner
    return func(ax, *map(sanitize_sequence, args), **kwargs)
  File "D:\testproject\venv\lib\site-packages\matplotlib\axes\_axes.py", line 4487, in scatter
    self.add_collection(collection)
  File "D:\testproject\venv\lib\site-packages\matplotlib\axes\_base.py", line 2242, in add_collection
    self._unstale_viewLim()
  File "D:\testproject\venv\lib\site-packages\matplotlib\axes\_base.py", line 776, in _unstale_viewLim
    self.autoscale_view(**{f"scale{name}": scale
  File "D:\testproject\venv\lib\site-packages\matplotlib\axes\_base.py", line 2932, in autoscale_view
    handle_single_axis(
  File "D:\testproject\venv\lib\site-packages\matplotlib\axes\_base.py", line 2895, in handle_single_axis
    x0, x1 = locator.nonsingular(x0, x1)
  File "D:\testproject\venv\lib\site-packages\matplotlib\ticker.py", line 1654, in nonsingular
    return mtransforms.nonsingular(v0, v1, expander=.05)
  File "D:\testproject\venv\lib\site-packages\matplotlib\transforms.py", line 2880, in nonsingular
    if maxabsvalue < (1e6 / tiny) * np.finfo(float).tiny:
  File "D:\testproject\venv\lib\site-packages\numpy\core\getlimits.py", line 462, in __new__
    dtype = numeric.dtype(type(dtype))
TypeError: 'NoneType' object is not callable
python-BaseException
Backend TkAgg is interactive backend. Turning interactive mode on.

For some reason, the same code works under jupyter notebook. I am importing pandas, matplotlib and seaborn in the following versions:
versions of pckages imported
Further, I created a project using a virtual environment as follows:
project creation with a virtual environment
Since the dataframes have no "empty" entries or those, for which the data type must be changed I cannot figure the reason out. The dataframe, which should be plotted looks like:
dataframe
I appreciate any advice!
Thanks in advance,
Jonas

A: I had a similar issue and I solved it downgrading the numpy package.
I was using 1.22.3 and changed to 1.22.2.
pip3 uninstall numpy
then
pip3 install numpy==1.22.2


text:
Q: How to iterate list on each user click I have kept the object into a list. I want to iterate them with user click.
Is there any method like list.next()

A: The best option is often to just keep a current index stored in a local variable.  On each "click", just increment your index, and use the value in list[index].
You could, potentially, call list.GetEnumerator() and use IEnumerator.MoveNext(), but this is more likely to cause issues.  In particular, if your collection is modified between clicks, you'll have problems...

A: From another post:
public void ForEach<T>(IEnumerable<T> items, Action<T> action)
{
    foreach (var item in items)
        action(item);
}

Call it like this:
ForEach(myList, i => Console.WriteLine(i));


text:
Q: Continuous calls to WCF service returns "Only one usage of each socket address (protocol/network address/port) is normally permitted 127.0.0.1:10111" I have developed a little mashup site. This site is complete with a community.
So when the user goes to the Community.aspx page he/she will see the members of the community with joined date,number of comments, name, etc.etc. and ofc paging as well. There are like 15 users per page. Now my problem is that i have 2 types of users on my site "Traditional Users" and "Open ID" users. Ofc i have 2 Roles defined in the Asp. Net membership namely "OpenIDUser" and "User".
OK!!!
Now when the user click on Community.aspx A list of users is created and the first 15 are returned. But for this list of users to be created there are a lot of Roles.IsUserInRole("Username","RoleName") checks to see which users are which because now to sort the userlist in alphabetical order. You have to be carefull of all OPEN ID users who all start with
http://identifier.username or whatever. So i make a lot of Asp .Net Membership Service Calls Membership.GetUser Roles and all that...
Now typically this would not be a problem, however i have incorporated the MemberShip service into a WCF. The reason for this is that in this community i am going to have lots of subdomains  (a subdomain for each "site") and i only want to use 1 database for all
this.
So i think normally if you make 500+ Membership.whatever calls thats 100%. But as soon as you bring .NET Membership in WCF and convert every single Membership.Whatever method into a WCF method. you have 500+ WCF calls every time the page is loaded.
I think that is why the error is occurring.

A: This is not a question, so this is not an answer, but a comment.
You should be looking at having each sub domain as a separate membership application. This allows multiple sites to share the same membership database, but not interfere with each other's members. You can set the application name as part of the provider configuration.

A: Are you closing the client? IIRC I had a similar problem.


text:
Q: Urysohn type cut off function I am looking for a cutoff function.
The Urysohn's Lemma says
Let $X$ be a $T_{4}$ space and $A,B \subset X$ be two closed and disjoint subsets of $X$. Then there exists a continuous function $f:X \to \mathbb{R}$ such that $f=0$ on $A$ and $f=1$ on $B$.
In Dirichlet space (for example $W^{1,2}(\mathbb{R}^{d})$, (1,2)-Sobolev space on $\mathbb{R}^{d}$), I am looking for a function as described above.
Can we construct a function $f \in W^{1,2}(\mathbb{R}^{d})$ such that $f=0$ on $dx$-a.e. on $A$ and $f=1$ on $dx$-a.e. on $B$, where $A,B$ are two closed and disjoined subsets of $\mathbb{R}^{d}$ ?
ADD we assume that Lebesgue measure of $B$ is finite.
If you know the related results, please tell me.

A: No. Let B be an infinite union of disjoint closed balls $B_n$, and let the complement of A be the union of open balls $C_n$, where each $C_n$ is slightly larger than $B_n$. If the gap between $C_n$ and $B_n$ shrinks fast enough as $n\to\infty$, this will preclude $f$ from being in $W^{1,2}$.
On the other hand, if you assume $B$ is compact, then a positive answer is well known.


text:
Q: Go to an activity from anywhere I am implementing a login system. The user needs to be redirected to the login activity from any previous activity if the token is no longer valid. I can go to the login activity with this
new Intent(CurrentActivity.this, NextActivity.class);

But this needs the current activity. I just want to go to the login activity no matter where I am. I cannot know where I am because this is inside an entirely different package.

A: you should probably register in the Application class to ActivityLifecycleCallbacks and if the user is not registered send them to the correct Activity.
just be sure to not endlessly send them from the login page to itself
EDIT:
adding some code and explanation.
In order to figure out if an Activity that shouldn't be alive is going through lifecycle events you'll need to implement some sort of a gate keeper. Previously it used to be some sort of static state that is kept in the Application class and holds the current activity and sometime even the stack of current activities.
This was far from a complete solution and had issues due to different tasks and even isolated procesies.
In API 14 Android introduced the Activity lifecycle callbacks which can be passed into the method registerActivityLifecycleCallbacks int the Application class.
What you want to do basically is the following:
class ThepooshApplication extends Application {

    private static sIsRegistered = false;

    public static setIsRegistered(boolean isRegistered) { sIsRegistered = isRegistered; }

    public void onCreate() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks(){
            @Override
            void onActivityCreated(Activity activity, Bundle savedInstanceState){
                if (!sIsRegistered && !(activity instanceof LoginActivity)) {
                    Intent loginIntent = new Intent(this, LoginActivity.class);
                    loginIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                        | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(loginIntent);
                }
            }
            @Override
            void onActivityStarted(Activity activity) { /*empty method*/ }
            @Override
            void onActivityResumed(Activity activity) { /*empty method*/ }
            @Override
            void onActivityPaused(Activity activity) { /*empty method*/ }
            @Override
            void onActivityStopped(Activity activity) { /*empty method*/ }
            @Override
            void onActivitySaveInstanceState(Activity activity, Bundle outState) { /*empty method*/ }
            @Override
            void onActivityDestroyed(Activity activity) { /*empty method*/ }
        });
    }
}

A: You must add  FLAG_ACTIVITY_NEW_TASK flag to your intent
myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

Try some like this
Intent i = new Intent();
i.setClass(this,TestActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);

Replace TestActivity.class for your target activity


text:
Q: How to set navbar and tabbar not transparent and their borders visible I can not find any info in internet about this question. I have tableview in UIViewcontroller and it is embedded in navigation controller. I want that my navbar was always like in scrolling state (borders are visible) and same thing with tabbar. Here is photo what I have(1-st) and what I want (2-nd).

A: In AppDelegate file in didFinishLaunchingWithOptions method added:
        //MARK: - NavBar appearance
        let navBarAppearance = UINavigationBarAppearance()
        navBarAppearance.backgroundColor = UIColor(named: "AccentColor")
        UINavigationBar.appearance().standardAppearance  = navBarAppearance
        UINavigationBar.appearance().scrollEdgeAppearance = navBarAppearance

        //MARK: - TabBar appearance
        let tabBarAppearance = UITabBarAppearance()
        tabBarAppearance.backgroundColor = UIColor(named: "AccentColor")
        UITabBar.appearance().standardAppearance  = tabBarAppearance
        UITabBar.appearance().scrollEdgeAppearance = tabBarAppearance


text:
Q: Is there a Unicode string which gets longer when converted to lowercase? The string 'ß' gets longer (as measured in Unicode codepoints) when converted to uppercase (it becomes 'SS').
Is there a similar string that gets longer when converted to lowercase?

A: http://www.unicode.org/Public/UNIDATA/SpecialCasing.txt
There are some characters in here that have to be handled with multiple bytes. These mostly seem to involve the dotage of the letters I and J.

A: If I've understood correctly, this Java finds when the uppercase version is longer than the original
for (char chr = 0; chr < Character.MAX_VALUE; chr++) {
    String str = String.valueOf(chr);
    String upper = str.toUpperCase();
    if (upper.length() > 1) {
        System.out.println(String.format("%s => %s (%d)", str,
                Arrays.toString(upper.toCharArray()), upper.length()));
    }
}

Which outputs things like your original example
ß => [S, S] (2)
'n => [', N] (2)
ǰ => [J, ̌] (2)
ΐ => [Ι, ̈, ́] (3)

If I change this to toLowerCase() there is only one result
İ => [i, ̇] (2)


text:
Q: multi path Array of objects mutation Wanna mutate a path of array of Obj.
The object should change on-click and it looks like this:
<iron-icon id="id" icon="icons:arrow-downward" on-click="_sortTags"
class$="arrow [[sortData.id.icon]] [[sortData.id.state]]"></iron-icon>

Here i wanna mutate the sortData Obj, this function gets triggered on click on the above icon
_changeSortData(field,order,iconShape,status){ //there is a function calls this function but did not bring it here to make issue simple
        this.set('sortData[field].sort', order);
        this.set('sortData[field].icon', iconShape);
        this.set('sortData[field].state', status);

      }

The object below is the property:
sortData: {
          type: Object,
          value: function () {
            return {
              "id": {
                "icon": "downward",
                "sort": "default",
                "state": "inactive"
              },
              "date": {
                "icon": "downward",
                "sort": "default",
                "state": "inactive"
              }
            }
          },
        },

Now is it possible to escape single qoutes here in order to apply [field] as a pram
this.set('sortData[field].sort', order);

since there is tow fields in sortData Obj (id and data)

A: In this.set(path, value), path can be specified as a string or an Array. Since you have a dynamic path part, you would use an Array path like this:
this.set(['sortData', field, 'sort'], order); // `field` is dynamic

demo


text:
Q: Convert ImageOutputStream to byte[] Have been trying to convert ImageOutputStream to byte[] for a while using JAI. Any inputs are appreciated. Thanks.
Sorry here is the code snippet, I am working on. I had to post it earlier. The problem I am facing is that, I am able to get ByteArrayOutputStream from ImageOutputStream. But it always gives me zero bytes. But if I use a FileOutputStream instead of a ByteArrayOuputStream, I can write into a file which has non zero bytes. :
File file = new File("C:/TIFFImages/tiff-image.tiff");
FileInputStream in = new FileInputStream(file);
long filelength = file.length();
byte[] bytes = new byte[(int)filelength];
int offset = 0;
int numRead = 0;

while (offset < bytes.length && (numRead=in.read(bytes, offset, bytes.length-offset)) >= 0) {
    offset += numRead;
}
if (offset < bytes.length) {
    throw new IOException("Could not completely read file "+file.getName());
}

ByteArrayInputStream bais = new ByteArrayInputStream(bytes);

RenderedImage src = JAI.create("stream", SeekableStream.wrapInputStream(bais, true));
RenderedOp renderedOp = MedianFilterDescriptor.create(src, MedianFilterDescriptor.MEDIAN_MASK_SQUARE , 1, null);
BufferedImage image = renderedOp.getAsBufferedImage();

ByteArrayOutputStream baos = new ByteArrayOutputStream();

ImageOutputStream  ios =  ImageIO.createImageOutputStream(baos);
//Instead of baos if I pass a FileOutputStream to the above function. It writes non zero
//bytes to the output file

TIFFImageWriterSpi tiffspi = new TIFFImageWriterSpi();
ImageWriter writer = tiffspi.createWriterInstance();
RenderedImage renderedImage = PlanarImage.wrapRenderedImage(src);
writer.setOutput(ios);
writer.write(image);
writer.write(null,new IIOImage(image, null, null), param);

System.out.println("After tiff ImageIO operations" + baos.toByteArray().length);

Thanks ,
 Vinay

A: I got the answer for this, which is very close to what Guillaume suggested. Except that no need to write to a temp file in between. The following is the modified code to convert ImageOutputStream to byte[] :
ByteArrayOutputStream baos = new ByteArrayOutputStream(37628);
ImageOutputStream  ios =  ImageIO.createImageOutputStream(baos);

//Instead of baos if I pass a FileOutputStream to the above function. It writes non zero
//bytes to the output file

TIFFImageWriterSpi tiffspi = new TIFFImageWriterSpi();
ImageWriter writer = tiffspi.createWriterInstance();
RenderedImage renderedImage = PlanarImage.wrapRenderedImage(src);
writer.setOutput(ios);
writer.write(image);
writer.write(null,new IIOImage(image, null, null), param);

//Create a ByteArrayInputStream to read that ByteArrayOutputStream and read it from ImageIO

ByteArrayInputStream bai = new ByteArrayInputStream(baos.toByteArray());
RenderedImage out = ImageIO.read(bai);
int size = bos.toByteArray().length;

System.out.println(""+ size);

return bos.toByteArray

A: I'm pretty sure it's because you're not calling ImageOutputStream.flush() at the end of the operation - if the IOS created is a MemoryCacheOutputStream, it seems to require an explicit flush on some ImageIO implementations.

A: Create ImageOutputStream with ByteArrayOutputStream (instead of FileOutputStream)
ByteArrayOutputStream bos = new ByteArrayOutputStream(255);
ImageOutputStream ios = ImageIO.createImageOutputStream(bos);
// use "ios" for image processing

After image processing is done, image bytes would be available in the "ios" object, but the offset would be positioned at the end of the "ios" object. So we need to position the offset to the beginning of the "ios" object and then read the bytes to write to new ByteArrayOutputStream object. Finally return the toByteArray() from the new object. Like below:
        public byte[] getBytes(ImageOutputStream ios) {
            ByteArrayOutputStream bos = new ByteArrayOutputStream(255);
            byte imageByte;
            long counter = 0;
            try {
                    System.out.println("getStreamPosition()[BEFORE]=" + ios.getStreamPosition());
                    ios.seek(0);
                    System.out.println("getStreamPosition()[AFTER]=" + ios.getStreamPosition());
            } catch (IOException e1) {
                    e1.printStackTrace();
            }

            while (true) {
                    try {
                            bos.write(ios.readByte());
                            counter++;
                    } catch (EOFException e) {
                            System.out.println("End of Image Stream");
                            break;
                    } catch (IOException e) {
                            System.out.println("Error processing the Image Stream");
                            break;
                    }
            }
            System.out.println("Total bytes read=" + counter);
            byte[] retValue = bos.toByteArray();
            return retValue;
    }

A: Well, you won't be able to read from an output stream.
You should rather try to get an InputStream from your image object and read the necessary data from there.
However, if you gave more details about what you are actually trying to achieve we could help you more efficiently. :)
For instance if you are only willing to display the size of the images in bytes, there are several other ways.


text:
Q: Dynamic values passing to sparkSQL Basically I am passing the dynamic values in pyspark SQL. My code is detailed below:
set_sql = "".join(["set app_list_0 = 'app_3'"])

    sqlContext.sql(set_sql)

    click_app_join_sql = sqlContext.sql("select click_id, (case when app_new in ${app_list_0} then 1 else 0 END) as  ${app_list_0}, device, os, channel from clickDF ")

    click_app = sqlContext.sql(click_app_join_sql)

    click_app.show(3)

When I ran my code, I end up with the following error. Can you please advise me what went wrong in the above code.
File "/home/saureddi/spark/data_process/hive_data_process.py", line 103, in <module>
    click_app_join_sql = sqlContext.sql("select click_id, (case when app_new in ${app_list_0} then 1 else 0 END) as  ${app_list_0}, device, os, channel from clickDF ")
  File "/usr/hdp/2.6.4.0-91/spark2/python/lib/pyspark.zip/pyspark/sql/context.py", line 384, in sql
  File "/usr/hdp/2.6.4.0-91/spark2/python/lib/pyspark.zip/pyspark/sql/session.py", line 603, in sql
  File "/usr/hdp/2.6.4.0-91/spark2/python/lib/py4j-0.10.4-src.zip/py4j/java_gateway.py", line 1133, in __call__
  File "/usr/hdp/2.6.4.0-91/spark2/python/lib/pyspark.zip/pyspark/sql/utils.py", line 73, in deco
pyspark.sql.utils.ParseException: u"\nno viable alternative at input '(case when app_new in 'app_3''(line 1, pos 39)\n\n== SQL ==\nselect click_id, (case when app_new in 'app_3' then 1 else 0 END) as  'app_3', device, os, channel from clickDF \n---------------------------------------^^^\n"

Code:
app_sql = "".join(["select a.app, CONCAT('app', '_',a.app) as new_app, a.app_count from(select app, count(app) as app_count from dblclk_text.click_data group by app )a order by a.app_count desc limit 5"])
df1 = hiveContext.sql(app_sql)
df1.createOrReplaceTempView('app')
df1_new_app = sqlContext.sql("select new_app from app ")
df1_new_app.printSchema()

app_list = []
app_result = df1_new_app.collect()

print(type(app_result))

for app in app_result:
    app_list.append(app)

click_sql = "select click_id,CONCAT ('app', '_', app) as app_new, device, os, channel from dblclk_text.click_pank_data"
clickDF = hiveContext.sql(click_sql)

clickDF.createOrReplaceTempView('clickDF')

app_list_0 = str(app_list[0])
#app_list_0 = 'app_3'

print (app_list_0)

sample_sql = '''select click_id, (case when app_new in {0} then 1 else 0 END) as  {0}, device, os, channel from clickDF '''.format(app_list_0)
click_app_join_sql = sqlContext.sql(sample_sql)
click_app = sqlContext.sql(click_app_join_sql)
click_app.show(3)

A: sample_sql = '''
select tenant, user_id, event_type,bounce_class from {0}
where {1} and  {2} and  {3} and  {4}
and (event_type in ('list_unsubscribe', 'link_unsubscribe', 'spam_complaint') or bounce_class in ('10','30','90'))
and tenant is not null
and tenant != ''
'''.format(table_name, dateid_start, dateid_end,event_timestamp_start,event_timestamp_end)

HiveContext.sql(sample_sql)

table_name, dateid_start, dateid_end,event_timestamp_start,event_timestamp_end are python values.


text:
Q: Synchronizing nested Maps and Sets (Java) I have a nested set within a map within a map that I am trying to synchronize over two threads.
The map is instantiated as such:
private final Map<Manageable, Map<String, Set<Manageable>>> manageableMap =
        Collections.synchronizedMap(new HashMap<Manageable, Map<String, Set<Manageable>>>());

This is the function I use to add values to the map:
private void put(Manageable key, Manageable value, String valueType) {
    synchronized (manageableMap) {
        Map<String, Set<Manageable>> setMap = manageableMap.get(key);
        if (setMap == null) {
            setMap = new HashMap<String, Set<Manageable>>();
            manageableMap.put(key, Collections.synchronizedMap(setMap));
        }

        synchronized (setMap) {
            Set<Manageable> set = setMap.get(valueType);
            if (set == null) {
                set = new HashSet<Manageable>();
                setMap.put(valueType, Collections.synchronizedSet(set));
            }

            synchronized (set) {
                set.add(value);
            }
        }
    }
}

Intellij IDEA warns me that I am synchronizing on local variables setMap and set.
I am fairly new to synchronization and I was wondering if this is the proper way to
synchronize a nested data structure like this.
Thank you for you help.

A: You only need to synchronize on manageableMap. Only 1 thread at a time can acquire the lock on manageableMap, so if a thread has acquired the lock on manageableMap, further locking on set and setMap is not needed, since only 1 thread (the thread that locked manageableMap) can access set and setMap.

A: synchronization works on particular object instances, not on the fields or variables holding references to them, so you must make sure that the sunchronization occurs on the same object instances, no matter whether they are refenced  by local variables only.
In that particular case IDEA cannot statically check whether the code does what you want, the warning is just some kind of 'code smell' warning you that the effect might not be as expected.
Best bet is you test your code by logging out the instances that you are synchronizing on and check whether they are the ones you expect - IDEA has also the Option to mark object instances during debugging to check whether the objects you synchronize on are the same or different instances.

A: If you always control the synchronization manually you probably don't need to use Collections.synchronizedMap. One section synchronized on the target map will do.


text:
Q: faster way to implement 2 power float number without using divider I have found codes to implement 2 power float number(2^x where x is float), but, all of them are using dividers(/).
below one is one example where they are using divider for calculating it.
http://www.machinedlearnings.com/2011/06/fast-approximate-logarithm-exponential.html
I want to have a code where there are no dividers with as much high accuracy as possible.


text:
Q: Regex: \s is not matching \r\n It says "\s matches any whitespace character (equal to [\r\n\t\f\v ])"
reference: https://www.regular-expressions.info/shorthand.html & https://regex101.com
So, for a given regex:
one statement\s*<\/a>

I expect the following result:
one statement \r\n            <- should match
one statement \r\n  \n        <- should match
one statement                 <- should match
one statement .               <- should not match
one statement {anything else} <- should not match

However, only the following statement matches (\s is matching only spaces)
one statement

Did I understand something wrong? If yes, How can I achieve expected result?
regex playground: https://regex101.com/r/Pgiub4/1

A: I actually had to parse the literal string (\r\n) and also handle new line and spaces, so I used:
one statement(\s|\\r|\\n)*<\/a)

and it worked.
thanks to @jensgram and @MonkeyZeus for pointing it out!


text:
Q: JavaScript localStorage NaN error I am making a game with html and JavaScript. A saving system is included into the game I did this with localStorage. When I open the html file from my computer everything goes fine. Everything saves in localStorage and everything loads perfectly... But when I uploaded the files to my website where the game is located On every value there comes NaN... I know that means Not a Number but I do not get it. Why does this work on my computer but not on my website?
Here is the saving and loading part of the game!
var save_format=1;
function save(){
    localStorage.setItem("game_saved_before", save_format);
    localStorage.setItem("Money", Money);
    localStorage.setItem("DrinksSold", DrinksSold);
    localStorage.setItem("Price", Price);
    localStorage.setItem("Plants", Plants);
    localStorage.setItem("CompetitorBonus", CompetitorBonus);
    localStorage.setItem("Meals", Meals);
    localStorage.setItem("MealsLeft", MealsLeft);
    localStorage.setItem("MealCost", MealCost);
    localStorage.setItem("Werknemers", Werknemers);
    localStorage.setItem("WerknemerCost", WerknemerCost);
    localStorage.setItem("nextCostWerknemer", nextCostWerknemer);
    localStorage.setItem("StreetLicenses", StreetLicenses);
    localStorage.setItem("StreetLicensesHomeTown", StreetLicensesHomeTown);
    localStorage.setItem("StreetLicenseCost", StreetLicenseCost);
    localStorage.setItem("nextCostStreetLicense", nextCostStreetLicense);
    localStorage.setItem("HigherPriceCost", HigherPriceCost);
    localStorage.setItem("nextHigherPriceCost", nextHigherPriceCost);
    localStorage.setItem("PlantCost", PlantCost);
    localStorage.setItem("nextPlantCost", nextPlantCost);
    localStorage.setItem("nextMealCost", nextMealCost);
    localStorage.setItem("DestroyCompetitorCost", DestroyCompetitorCost);
}

function load_game(){
    if(parseInt(localStorage.getItem("game_saved_before") === save_format){
    if(localStorage.getItem("game_saved_before") !== null){
    // or:
    if(localStorage["game_saved_before"] !== undefined){
    // or:
    if(typeof(localStorage.getItem("game_saved_before")) !== "string"){
        Money = parseInt(localStorage.getItem("Money"));
        DrinksSold = parseInt(localStorage.getItem("DrinksSold"));
        Price = parseFloat(localStorage.getItem("Price"));
        Plants = parseInt(localStorage.getItem("Plants"));
        CompetitorBonus = parseInt(localStorage.getItem("CompetitorBonus"));
        Meals = parseInt(localStorage.getItem("Meals"));
        MealsLeft = parseInt(localStorage.getItem("MealsLeft"));
        MealCost = parseInt(localStorage.getItem("MealCost"));
        Werknemers = parseInt(localStorage.getItem("Werknemers"));
        WerknemerCost = parseInt(localStorage.getItem("WerknemerCost"));
        nextCostWerknemer = parseInt(localStorage.getItem("nextCostWerknemer"));
        StreetLicenses = parseInt(localStorage.getItem("StreetLicenses"));
        StreetLicensesHomeTown = parseInt(localStorage.getItem("StreetLicensesHomeTown"));
        StreetLicenseCost = parseInt(localStorage.getItem("StreetLicenseCost"));
        nextCostStreetLicense = parseInt(localStorage.getItem("nextCostStreetLicense"));
        HigherPriceCost = parseInt(localStorage.getItem("HigherPriceCost"));
        nextHigherPriceCost = parseInt(localStorage.getItem("nextHigherPriceCost"));
        PlantCost = parseInt(localStorage.getItem("PlantCost"));
        nextPlantCost = parseInt(localStorage.getItem("nextPlantCost"));
        nextMealCost = parseInt(localStorage.getItem("nextMealCost"));
        DestroyCompetitorCost = parseInt(localStorage.getItem("DestroyCompetitorCost"));
    }
}
}
}
}
load_game();
setInterval(save,1000);

I have been thinking is it because I can't reach there localStorage? Please help me I really need this and I have been trying to find an answer for days.

A: issue
Your check to make sure you have localStorage values is invalid:
if(typeof(localStorage.getItem("game_saved_before")) != undefined){

getItem returns null and typeof(null) is object.
Consequently, all your other calls can evaluate to parseInt(null) which is NaN.
immediate solution
A direct fix would be:
if(localStorage.getItem("game_saved_before") !== null){

or:
if(localStorage["game_saved_before"] !== undefined){

or:
if(typeof(localStorage.getItem("game_saved_before")) === "string"){

But then you have to make sure you localStorage.clear() to get rid of all the properties with values of "NaN".
Adding Versioning
I think you are already running into issues of old configs that you could avoid by versioning:
var save_format=1; // increment on breaking save format changes

save()
   localStorage.setItem("game_saved_before", save_format)
...

load_game()
   if(parseInt(localStorage.getItem("game_saved_before")) === save_format){
...

A drawback of this approach is that you are still saving things piecemeal, so legacy properties from one version may end up coexisting with future versions unless you use removeItem.


text:
Q: When does a zero-time MIDI event trigger? I'm reading a MIDI file and I'm having trouble determining when next events trigger.
Let's say I have a midi file that has a track like this (where T=n is the delta time):
[T=0: Note On, C4] [T=128: Note Off, C4] [T=0: Note On, D4] [T=128: Note Off, D4]
Does the second Note On (D4) take place at the EXACT same time/tick as the previous Note Off (C4)? Or do you trigger it on the next tick?

A: In theory, the two events happen at the same time.
In practice, events need a certain time to be sent over MIDI (about one millisecond for three bytes), but the second event will be sent as soon as possible after the first one.
When no actual MIDI cable is involved, the events actually could take effect at the same time.

A: All events happen on a tick.  However, they're sent out over the MIDI cable one at a time since MIDI is both a serial protocol and serial hardware.  This became a problem with devices that sent out huge numbers of controller change messages, originally like the MIDI guitar controllers.  They simply sent out more MIDI messages per second than the cable could transmit.
On alternate transport, like USB, those events can happen closer together but because they are serial, they must still happen one after the other.  That time frame may be indistiguishable, (we hope), but there will always be a tiny lag.
For them to happen at the "same" time, you must either a) buffer or b) make them happen in different places, as with parallel players, which still leaves you with a delay in syncing.


text:
Q: Could not load file or assembly 'App_Code' or one of its dependencies. Problem: I want to deploy modified code into web server. web server is having IIS version set to V2.0. and now I have developed and published code on my local machine with version 4.0. (there is App_code.dll as part of all dll files).
Now whenever I am deploying all files along with App_code.dll I am getting following error:"
Could not load file or assembly 'App_Code' or one of its dependencies.
This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded"
1) My question is how do I build App_code.dll in older version.
2) I tried changing target framework to V2.0 while publishing but then its not working because AJAX functions from other dll are not compiling..
can anyone please suggest what to do to run the site..
Help is appreciated.
Thanks

A: Sorry about the answers I've given... But try this...
Try adding <codeBase> elements to the application config file to specify the exact location of each dll, and the version of .Net it requires. Apparently this works because <codebase> is checked BEFORE the probing heuristics kick in each time an assembly needs to be loaded.
<runtime>
  <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <dependentAssembly>
      <assemblyIdentity name="sharedlibA" culture="neutral" publicKeyToken="..." />
      <codeBase version="1.0.0.0" href="bin\sharedlibA.dll" />
    </dependentAssembly>
    <dependentAssembly>
      <assemblyIdentity name="sharedlibB" culture="neutral" publicKeyToken="..." />
      <codeBase version="1.0.0.0" href="bin\sharedlibB.dll" />
    </dependentAssembly>
  </assemblyBinding>
</runtime>

If that doesn't work try this.

A: Late answer but, I'm writing this for future viewers.
I had same error after publish the application to the Server.
I figure it out doing like this.
While publish there is configuration in Setting.

In publish section there is option called

Precompile during publishing

you have to check the checkbox and save then Publish. This will takes your code files .vb/.cs and converts them into a compiled DLL files.
In my case it was unchecked.


text:
Q: Load some CSS with style-loader and some CSS with to-string-loader in Webpack 2 I'm working on an Angular 2 app and currently trying to build it with Webpack 2 (this is my first foray into Webpack).
I understand the difference between style-loader and to-string-loader, the former adds CSS to the DOM, the latter creates a string array for Angular 2 to consume via the styles property.
My question is, can I have both? Or put another way, if I have global styles in a file site.css, what is the proper way to bundle those with Webpack without changing the behavior for component styles (to-string-loader, css-loader)?
Just requiring or importing them in main.ts doesn't seem to be enough for Webpack to figure out what to do.

A: Loaders can be overridden for specific module request:
require("!!style!css!./global-styles/site.css");

Or different loaders can be defined for different conditions:
module: {
    loaders: [
        {
            test: /\.css$/,
            include: [path.resolve(__dirname, "global-styles")],
            loaders: ['style', 'css']
        },
        {
            test: /\.css$/,
            exclude: [path.resolve(__dirname, "global-styles")],
            loaders: ['to-string', 'css']
        },
    ...


text:
Q: Is permission stored permanently for geolocation HTML 5? When a user visits the website, we ask for his permission using getCurrentPosition. And, if the user gives the permission, we use the coordinates to get his position. Now, I don't want this prompt to happen every-time user comes on my site. Is there an API call which I can use?

A: The implementation is browser dependent. Most browsers will store the preference for each individual site. You have no control - there is no API you can use to get the browser to remember the user's preference.


text:
Q: Gin handler not executing CRUD operations and not returning anything in the response Header I'm making a CRUD to-do list application but I have an issue with the handler responses. The get and create list operations are working but the delete list and task operations are only returning 200 response neither doing their stuff nor returning a response header. The issue is with the gin handlers because I've done unit tests on the repository part and they are all passing.
These are my structs with the json:
type Task struct {
    ID        int    `json:"taskid"`
    Text      string `json:"text"`
    ListID    int    `json:"list_id"`
    Completed bool   `json:"completed"`
}

type List struct {
    ID   int    `json:"id"`
    Name string `json:"name"`
}

The function interfaces that I'm passing to the handlers:
type TaskOperations interface {
    GetTasks(listID int) ([]Task, error)
    CreateTask(listID int, taskText string) (Task, error)
    ToggleTask(taskID int) (Task, error)
    DeleteTask(taskID int) error
}

type ListOperations interface {
    GetLists() ([]List, error)
    CreateList(listName string) (List, error)
    DeleteList(listID int) error
}

And 2 of the handlers that are not working:
func GetTasks(data model.TaskOperations) gin.HandlerFunc {
    return func(c *gin.Context) {
        listID := c.Request.Header.Get("id")
        id, err := strconv.Atoi(listID)
        if err != nil {
            return
        }

        data.GetTasks(id)
        if err != nil {
            return
        }
        tasks := []model.Task{}
        c.BindJSON(&tasks)
        c.JSON(200, tasks)
    }
}

func CreateTask(data model.TaskOperations) gin.HandlerFunc {
    return func(c *gin.Context) {
        listID := c.Request.Header.Get("id")
        taskText := c.Request.Header.Get("text")
        id, err := strconv.Atoi(listID)
        if err != nil {
            return
        }

        data.CreateTask(id, taskText)
        newTask := model.Task{}
        c.BindJSON(&newTask)
        c.JSON(200, newTask)
    }
}

The whole code is in this repository if you want to check it: https://github.com/nakata7193/testRepo/tree/main/FinalAssignment


text:
Q: How to pass array value in mysql select query With the help of to this question, "Divide numbers into equal parts to create Sitemap from mysql", I got this result:
Array ( [0] => 0,500
        [1] => 500,1000
        [2] => 1000,1500
        [3] => 1500,2000
        [4] => 2000,2500
        [5] => 2500,2990 )

My question is, I want to pass the above Array values to select query limit. like this:
 "SELECT * FROM `table_name` WHERE `rec_id`='1' limit 0 OFFSET 500 "

and so on upto limit 2500, 2990.
How to do this? I am new to development. please help me with the solution.
Thank you in advance.

A: Actually you want a pagination with 500 results begining at an index, right ? So limit should always be 500, only offset value should change.
$queries = [];
$array = Array ( [0] => 0,500
    [1] => 500,1000
    [2] => 1000,1500
    [3] => 1500,2000
    [4] => 2000,2500
    [5] => 2500,2990 );

foreach ( $array as $value ){
    $offsets = explode(',', $value);
    $queries[] = "SELECT * FROM `table_name` WHERE `rec_id`='1' limit 500 OFFSET $offsets[0]";
}

A: Here is the code
foreach($arr as $k => $v){

  list($limit, $offset) = explode(','$v);

   $query_arr[] = "SELECT * FROM `table_name` WHERE `rec_id`='1' limit $limit OFFSET $offset";
}

And then fire $query_arr as you want


text:
Q: Delete post without loading page - symfony4 I am new to Symfony. I want to delete my post using the jquery DELETE method. I have jquery code delete my post when I click on the delete button it reloads the page after confirmation but didn't delete my post. Please check my code and fix the problems.
I copied code from https://www.youtube.com/watch?v=WVeE4SXIOwA
This is the delete button in twig
<button class="delete-btn" data-id="{{ post.id }}" style="font-size:15px; color:red;">
Delete
</button>

post.js
const articles = document.getElementById('post');

if(articles) {
    articles.addEventListener('click', e => {
        if (e.target.className === 'delete-btn' )
        {
          if(confirm('Are you sure?')) {
              const id = e.target.getAttribute('data-id');

              fetch(`/post/delete/${id}`, {
                  method: 'DELETE'
              }).then(res => window.location.reload());
          }
        }
    });
}

Controller

<?php

namespace App\Controller;

use App\Entity\Post;
use App\Entity\User;
use App\Entity\Rating;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Response;

class PostController extends AbstractController
{
   /**
    * @Route("post/delete/{id}")
    * @Method({"DELETE"})
    */
     public function delete(Request $request, $id)
     {

        $post = $this->getDoctrine()->getRepository(Post::class)->find($id);

        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->remove($post);
        $entityManager->flush();

        $response = new Response();
        $response->send();
      }
}

When I click the button it confirms by alert "Are you sure?" after clicking ok and then it doesn't delete my post. Please help me to find the solution

A: You should be using window.location.reload(true) in order to reload the page from the server (with updated data). By default the browser reloads from the cache (where the entity still existed). See here for details: https://developer.mozilla.org/en-US/docs/Web/API/Location/reload#Syntax


text:
Q: How to code an atomic transaction in PL/pgSQL I have multiple select, insert and update statement to complete a transaction, but I don't seem to be able to ensure all statements to be successful before committing the changes to table.
The transaction doesn't seem to be atomic.
I do have begin and end in my function but transaction doesn't seem to be atomic.
CREATE FUNCTION public.testarray(salesid integer, items json) RETURNS         integer
LANGUAGE plpgsql
AS $$
declare
 resu text;
 resu2 text := 'TH';
 ssrow RECORD;
 oserlen int := 0;
 nserlen int := 0;
 counter int := 0;
begin

 select json_array_length(items::json->'oserial') into oserlen;
 while counter < nserlen loop
   select items::json#>>array['oserial',counter::text] into resu;
   select * into strict ssrow from salesserial where fk_salesid=salesid     and serialnum=resu::int;
   insert into stockloct(serialnum,fk_barcode,source,exflag)     values(ssrow.serialnum,ssrow.fk_barcode,ssrow.fk_salesid,true);
   counter := counter + 1;
 end loop;

 counter := 0;
 select json_array_length(items::json->'nserial') into nserlen;
 while counter < nserlen loop
   select items::json#>>array['nserial',counter::text,'serial'] into resu2;
   select * into ssrow from stockloc where serialnum=resu2::int;
   insert into salesserial(fk_salesid,serialnum,fk_barcode)     values(salesid,ssrow.serialnum,ssrow.fk_barcode);
   counter := counter + 1;
 end loop;
 select items::json#>'{nserial,0,serial}' into resu2;
 return resu;
end;
$$;

Even when the first insert fails, the second insert seems to be able to succeed.

A: I see that by "fail" you mean "does not insert any rows".
That is not surprising since the first loop is never executed: both counter and nserlen are always 0.
Perhaps you mean the first WHILE condition to be counter < oserlen?
You also seem to br confused by PL/pgSQL's BEGIN: while it looks like the BEGIN that starts a transaction, it is quite different. It is just the "opening parenthesis" in a PL/pgSQL block.


text:
Q: Convert strings to opening and closing tags (XML) I'm trying to convert a text file (from Dokuwiki) to XML for further processing. For this I need to convert some special formatting strings to opening and closing tags.
E.g.: Headlines are marked by "===" ("=== Headline of article ==="). But I cannot simply replace "===" with "<head>" since I need the second "===" to be "</head>" (closing tag). I hope you got what I mean. I have to replace the same string with two different strings depending on the previous one. The program should be written in Python but I actually only need the algorithm...
Thanks

A: Regular expression time:
To replace the first set of "===", use the "^" anchor: r/^=== /\<head\>/
To replace the second "===", use the "$" anchor: r/ ===$/\<\\head\>/


text:
Q: REQUEST_URL if statements I'm a PHP rookie, I have the following statement:
if(strpos($_SERVER['REQUEST_URI'],'/')!=-1) {
    echo 'Hello World' .$_SERVER['REQUEST_URI']. '';
} else if(strpos($_SERVER['REQUEST_URI'],'/blog')!=-1) {
    echo 'blog World' .$_SERVER['REQUEST_URI']. '';
} else if(strpos($_SERVER['REQUEST_URI'],'/videos')!=-1) {
    echo 'videos World' .$_SERVER['REQUEST_URI']. '';
} else if(strpos($_SERVER['REQUEST_URI'],'/about')!=-1) {
    echo 'about World' .$_SERVER['REQUEST_URI']. '';
} else if(strpos($_SERVER['REQUEST_URI'],'/contact')!=-1) {
    echo 'contact World' .$_SERVER['REQUEST_URI']. '';
}

My issue is that whenever I go elsewhere than http://website.com/ I still get the result Hello World rather than the other results. Any Idea how to solve the issue?

A: strpos doesn't return -1, it returns false if there is no match. Therefore your tests should be:
if(strpos($_SERVER['REQUEST_URI'],'/') !== false)

etc.
(!== and === are stricter comparison operators and means that PHP won't equate 0 to false in the comparison)
You should also realise that the first comparison, against '/' will match all instances, as all strings will start with '/'. Therefore you should have it as the last condition, not the first.
Overall it would be clearer if you used more positive comparisons:
if ( strpos($_SERVER['REQUEST_URI'],'/blog') === 0 ) {
    echo 'blog World' .$_SERVER['REQUEST_URI']. '';
} else if(strpos($_SERVER['REQUEST_URI'],'/videos') === 0) {
    echo 'videos World' .$_SERVER['REQUEST_URI']. '';
} else if(strpos($_SERVER['REQUEST_URI'],'/about') === 0) {
    echo 'about World' .$_SERVER['REQUEST_URI']. '';
} else if(strpos($_SERVER['REQUEST_URI'],'/contact') === 0 ) {
    echo 'contact World' .$_SERVER['REQUEST_URI']. '';
}else if(strpos($_SERVER['REQUEST_URI'],'/') === 0) {
    echo 'Hello World' .$_SERVER['REQUEST_URI']. '';
} else if( $_SERVER['REQUEST_URI' === '/') {
    echo 'Hello World' .$_SERVER['REQUEST_URI']. '';
} else {
    echo 'URL Not matched';
}

If the string matches that URI at the beginning (which it should) then the index returned will be exactly 0, so the exact match will match all occurances. I've changed your last match to match exactly '/' as if there is no match for that you would likely want to return an error, but you could just have a default action in the final else.

A: /blog, /videos, ... also has /. So which url you go, it will always match with /. You can use this;
if($_SERVER['REQUEST_URI'] === '/') {
    echo 'Hello World' .$_SERVER['REQUEST_URI']. '';
} else if(strpos($_SERVER['REQUEST_URI'],'/blog')!=-1) {
    echo 'blog World' .$_SERVER['REQUEST_URI']. '';
} else if(strpos($_SERVER['REQUEST_URI'],'/videos')!=-1) {
    echo 'videos World' .$_SERVER['REQUEST_URI']. '';
} else if(strpos($_SERVER['REQUEST_URI'],'/about')!=-1) {
    echo 'about World' .$_SERVER['REQUEST_URI']. '';
} else if(strpos($_SERVER['REQUEST_URI'],'/contact')!=-1) {
    echo 'contact World' .$_SERVER['REQUEST_URI']. '';
}


text:
Q: Server returns Code: InternalServerError when using CreateUploadSesssion to upload a file My application can upload files into OneDrive, SharePoint normally by Consecutive Upload.
For now, It is broken, and throw InternalServerError when calling
var uploadSession = await graphClient.Drive.Items["01KGPRHTV6Y2GOVW7725BZO354PWSELRRZ"].ItemWithPath("_hamilton.png").CreateUploadSession().Request().PostAsync();

I implement follow:
[https://github.com/microsoftgraph/msgraph-sdk-dotnet/blob/dev/tests/Microsoft.Graph.DotnetCore.Test/Requests/Functional/OneDriveTests.cs][1]
Exception:
Status Code: InternalServerError
Microsoft.Graph.ServiceException: Code: InternalServerError
Message: Object reference not set to an instance of an object.
Inner error:
AdditionalData:
request-id: b3ab4fbb-e3c2-4e07-a353-4e2a73b5bf67
date: 3/10/2020 4:25:56 AM
ClientRequestId: b3ab4fbb-e3c2-4e07-a353-4e2a73b5bf67

at Microsoft.Graph.HttpProvider.SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken)
at Microsoft.Graph.BaseRequest.SendRequestAsync(Object serializableObject, CancellationToken cancellationToken, HttpCompletionOption completionOption)
at Microsoft.Graph.BaseRequest.SendAsync[T](Object serializableObject, CancellationToken cancellationToken, HttpCompletionOption completionOption)

SDK: Microsoft.Graph 1.21.0

A: We also got the same issue, but it seems that it's an issue with the Graph API that (probably) changed today (2020-03-10). Someone has filed a github issue at https://github.com/microsoftgraph/msgraph-sdk-dotnet/issues/646 which you can follow, but if you really have to make this work, you can hack around it by overriding the request url using reflection.
var regex = new Regex(@"/microsoft\.graph\.createUploadSession$");
var reqUrl = uploadSessionReq.RequestUrl;
typeof(DriveItemCreateUploadSessionRequest)
    .GetProperty(nameof(DriveItemCreateUploadSessionRequest.RequestUrl))
    .GetSetMethod(nonPublic: true)
    .Invoke(
        uploadSessionReq,
        new[]
        {
            regex.Replace(reqUrl, "/createUploadSession")
        }
    );


text:
Q: Fixing ugly Greek symbols? When displaying Greek symbols with, for example, π, I get very different results in Chrome and Safari versus Firefox. As some example text, I have:
Chrome:

Firefox:

Is there a way to get Webkit to render the letters closer to Gecko's style, which I much prefer here?
EDIT: Actually, it seems the problem does not have to do with Webkit itself, as it seems to render the way I like it under Chrome in Windows 7: (I was using Snow Leopard and didn't bother to check on my other computers, heh)

Also, a bit offtopic, but does anyone know why the fonts seem to be rendered a bit more boldly on the Mac than on the PC?

A: I would guess that firefox is using the Symbol font, whereas Safari is using whichever unicode font has the right characters.
On my Mac, this works: π. Also, setting the font of the container to Times New Roman seems to work as well.

A: Okay, so the weirdest thing happened. I was looking at my site again and suddenly realized that the Greek was rendering perfectly. Am not sure what happened, since I don't think I ran any updates or anything, but the problem's gone now. Not very helpful of course to others with this problem, but that's just what happened...

A: Your browser will render using whatever fonts it has available. Some fonts may be missing certain characters, in which case the browser will use another font for those characers. If, in your CSS, you tell the browser what the font-family is, it can better pick a matching font.
font: "Times New Roman", serif;

Now the browser will pull in missing characters from a serif font.
Of course, with the @font-face directive, you can force the use of a font which has all the characters you need.


text:
Q: Small Height of Iframe Facebook Comment box has blocked content I am using Facebook comment plugin, due to limited iframe height causing admin box and sometimes comments box could not show completely (Please see the attached).
Any suggestion can do to prevent this kind of error happen?

A: In this case iFrame height is influenced by the height of the parent element. Find the parent and try to increase the height of the parent.


text:
Q: how to dereference a linked list node data that is a pointer? so I am creating a linear linked list and I am not allowed to use static arrays or strings as data members (only dynamic char arrays)
so I have my data struct:
struct artists
{
    char* name;
    char* story;
    char* description;

};

and my node representation:
struct node //Create our node type for LLL of artists
{
    artists* data;
    node* next;
};

I am planning to allocate memory for name,description, story inside a function but my question is how do I actually dereference this?
is there such thing as *(temp->data.name)?
Or does this code make sense at all?
name = new char[strlen(artistitle)+1]
strcpy (*(temp->data.name),artistitle)

or would it still be strcpy(temp->data.name,artistitle), since array names work similar to pointers.
I am a little confused, I might be way off, so any input will be appreciated, thanks.

A: As you are working with dynamic memory, first thing you should have in mind is how do you allocate memory, and free it. Second, how do you access that memory.
As your question, it seems that you want to access it, besides using dereference.
To obtain any value from a "normal allocated" struct/class, you can use . so, working with, eg: the artist name, would be:
artists a;
//Suposse you have allocated char pointer here
strcpy(a.name, artistname);

If you are working with dynamic memory, you must use -> operator as here:
artists *a;
//Dynamic allocate struct and char pointers
strcpy(a->name, artistname);

It is the same when you have nested pointers and "normal allocated":
node n;
//Allocate everything
strcpy(n.data->name, artistname);

//Another way to do it
node *n;
//You have to allocate node too
strcpy(n->data->name, artistname);

When you use a pointer as a variable, it stores the memory direction where it is pointing (ironic, huh). So if you do
node *a;
//Allocate it, and do some operations
node *b=a;

You are copying a's memory pointer, not its content. To access a pointer's content, you can use * operator.


text:
Q: Master List with other lists showing filtered data I'm having troubles with finding a solution (ootb would be best) to have a Master SP List with 3 "sub-lists", i.e. lists showing data from the Master list with a certain value in one of the columns.
The idea is to have one Master list where summary data for 3 different projects is inserted weekly (with attachments) - this list could be accessed only by people entering this data. Moreover, there would be 3 separate lists showing weekly data only for each of these projects.

Is there an easy way of implementing something like this?
I can only think of two ways to do it:

*
1) Creating the Master List and then Site Pages with filtered List Web Parts - but I don't want people to be able to access the Master List, so this is probably not good.
2) A linked Access database with a query to update the 3 lists based on data on the Master list. This would need to be done manually each week. Also not the best option.

Many thanks!

A: I like the answer above. It seems simple enough, but what about when someone updates a field in the Master List? Or what about when someone deletes something from the Master List? Are you expecting to also have to delete it from the Sub List yourself? There's no event to handle that, and as such the sub-list will quickly become outdated. Unless your intention is NOT to update the items at all.
I am currently working through this problem, and am unsure as to how powerful SharePoint Designer and Workflow (or Flow) really is. As such, I am employing Access to run such updates whenever the database is opened. Looks something like this:

*

*Create the 4 lists (1 master, and 3 projects). All lists have the same fields except for the master list which has one more 'choice' field. This drives Access to determine which sub list the item will appear on.

*Link all lists to an access database so that updates between lists are live.

*Add queries to each table: UPDATE (if items already exist then update the fields if any changes have been made), APPEND (adds new items), and a query that will check if the ID of items in the Sub Lists exist in the Master List and delete it if not (handles deletion from master list).
Updates can only be made to the Master List, and changes are propagated over to each of the Sub Lists.
I have about zero experience with Access, so I'm pretty much going to be learning how to do this - unless someone is kind enough to help??? ;)

A: To summarise what you want:

*

*A list named Master List with data for 3 projects.

*Only specific people can access the Master List to enter and view data.

*3 separate lists, each related to one of the 3 projects.

*The data in the 3 project lists is just a copy of the some of the data from the Master List.

*Ideally, when data is added to the Master List, it is also added to the appropriate project list.

Here is a solution that is pretty out-of-the-box and relatively simple:

*

*Create the 3 project lists.

*Make sure the fields in these 3 lists are of the same type as the fields from the Master List. Since you do not copy the entire data from the Master List, then only create the necessary fields.

*Create a workflow on the Master List and set it to start when items are created.

*Presuming that the Master List contains a field that specifies which project each list item is for, then add IF statements in the workflow for each project.

*Inside the IF statements use the Create Item workflow action to create an item in the appropriate project list.

*Optional: Use Impersonation or the App Step in the workflow if for some reason the people who enter data into the Master List do not have access to the project lists.

Let me know if this does not make sense.