text:
Q: question about maven dependency i loaded the maven project in eclipse then found sth wrong with pom.xml file, when i clicked the 'overview' tab(m2eclipse), it said:
Failed to read artifact descriptor for commons-logging:commons-logging:jar:1.1.2-SNAPSHOT

when i clicked the dependency hierarchy tab, it showed 'Project read error',  however i have no problem to  run 'mvn dependency:tree' from command line and can see there is a dependency on commons-logging:
commons-logging:commons-logging:jar:1.1.1:compile

just don't understand where the commons-logging 1.1.2-SNAPSHOT comes from. any idea ?  Thanks.

A: In order to determine where the dependency commons-logging comes from (even without the .pom editor and its dependency editor) open the console and execute the following command:
mvn dependency:tree -Dverbose -Dincludes=commons-logging

This will show all dependencies of commons-logging.
I looked through the dependency tree, but did not find any reference to 1.1.2-SNAPSHOT.
Finally, adding the following dependency to my pom.xml solved the problem:
    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.1.2-SNAPSHOT</version>
    </dependency>

A: It's most likely coming into your project transitively. You can check the "Dependency Hierarchy" section of your pom editor in eclipse and see where it's coming from (search for commons-logging in the right top box). Also, I cannot see a 1.1.2-SNAPSHOT version of commons-logging on central so most likely someone has made a mistake in a dependency pom.

A: eclipse by default does not use the same maven installation as your command line. Depending on your m2eclipse version it might use an embedded maven snaphsot (with strange behaviour). Check
eclipse -> Window -> Preferences -> Maven -> Installations

and add your external maven installation (prefer current version 3.0.3) to the list and use this as default.


text:
Q: Vert.x Java Webclient Timeout for Null headers holds connection? Vert.x - 3.5.0
I have single vert.x vertical using single web client consuming 2 different API's on same destination host.
I have connection maxPoolSize=100, keepAlive=true, connectionTimeout=9000 and request timeout =10000.
My http call is failing because of null header parameter is being passed in my code  but problem is when vert.x throws null pointer while doing POST (because of one of the null header parameter) my http connection's are getting exhausted after sometime and never released and if I do make a call after sometime it's still timing out.

*

*Please suggest what am I missing here and if vert.x is doing something internally to manage connection's that is causing this issue.

*How should we come up with number for maxPoolSize, connect timeout value provided I know my requestTimeout is 10000 and keep alive is true

*I can fix my null header parameter issue but I am more interested what is happening to the connection pool for timeout in such scenario's - is it like not releasing the connection ?

*How can I monitor my current connection pool utilization.

redpajama_set_name: RedPajamaStackExchange


text:
Q: nodejs and setting up a server I have followed the exact same method as listed in the below link, but I can only can a blank page when I type "localhost://8080" in my broswer.
why is that. can anyone advice please?
setStatic function in httpdispatcher

A: Try http://localhost:8080
Localhost is the address, not the protocol. "http" is the protocol. Roughly, it goes like this: "protocol://address:port".


text:
Q: Show template loaded Is there any way to see what .php files are being loaded for a particular page?
So say I have a page - www.example.com/page - and on it is loading the header.php, sidebar.php, footer.php, and the page.php, and any other php from plugins. Is there anyway to get a list of these for a certain page?

A: The following will show the current template file to logged in admins only.  If you add to the top of your functions file, you should see this info as the first line.
add_action('wp_head', 'show_template');

function show_template() {
  global $template;
  global $current_user;
  get_currentuserinfo();
  if ($current_user->user_level == 10 ) print_r($template);
}

You will still need to follow the logic of the page template to determine which header, sidebar and footer are loaded, however.

A: get_currentuserinfo is deprecated since 4.5.0! Use wp_get_current_user() instead.
add_action('wp_head', 'show_template');

function show_template() {
  global $template;
  global $current_user;
  wp_get_current_user();
  if ($current_user->user_level == 10 ) print_r($template);
}


text:
Q: What's causing this error? A pc I am working on ran great till 20 minutes ago, when the following happened:
I insterted a usb flash drive with a file and tried to search something on the internet when I noticed the mouse cursor was moving with lag spikes. My first thought was that either the CPU was overworking or the ram was getting full. So I restarted the PC.
Instead of the PC opening, it played a rapid sound (faster than when there is no ram on) and I started checking all the things connected to it, only to find out that when the usb keyboard gets connected this sound starts. If I connect a keyboard with no usb gate but the original circle purple one it makes no sound.
BSOD also appeared with a BAD POOL HEADER error.
What do you think is the cause?
P.s. there were 4 or 5 current shortcuts today, but I don't know if these are connected to it.
Update: A friend of mine accidentaly fixed it when he inserted 2 keyboards. Now the issue happens only when you put the old keyboard or another one that propably does not work. Still don't know why.


text:
Q: How does camshift tracking work compared to meanshift I know, how meanshift works for tracking objects:

*

*Histogram of region of interest

*Backprojection image

*calculating center of mass

*iterativ adaption of the ROI's center to the center of mass

But how can the camshift algorithm solve the problem of changing the objects size (e.g. if it moves towards the camera)?
I tried to find some help on Wikipedia, but its written in french and there is no other language available.


text:
Q: Time Zone Calculation Am developing website like online travel portal. The issue is displaying GMT time for various regions at flight booking and list out the timing. Any one gives idea to calculate and show the time for different countries?
Thanks

A: Although it is pretty hard to answer your question without a reference to particular technology, I will try.
End user Time Zone detection
Definitely, all time-related information should be presented both in local format and local time zone. By local I mean the one used by end user.
I am guessing that your application will not require creating user profiles. I am also assuming that flight schedules will not be visible on front page and user would need to perform search. In that case you have three choices:

*

*Let user specify time zone from drop down box. I have no way to show you how it should be done without referring to concrete technology. The only thing I must point out is, it should present UTC offset, time zone name and list of cities, for example: UTC+01:00 Central European Time (Paris, Berlin, Warsaw).

*You could read current time zone offset with JavaScript and send it out to server
In that case you can use following code snippet to detect offset:
var now = new Date();
var offset = now.getTimezoneOffset();

This will give you current GMT offset in minutes. The problem with that solution is, this offset might be different on the target date.

*

*Obviously you could as well send GMT based dates in invariant form to the browser (for example using ISO8601 format: 2011-05-25T11:07Z) and format this date on the client using JavaScript. I never heard of for example JQuery plugin which would do that correctly (respecting local formats), though. It seems that you would be forced to write your own.

Date and time formatting as well as time zone conversion
Ha, it depends on solution you want to implement as well as technology you want to use. For now, I can't write much here.


text:
Q: Solve $x\sqrt{10} = \prod\limits_{k = 1}^{90} \sin(k), x\in \mathbb Q$. Can someone help me with this question? I've found a solution but it's not a very nice one. I used 6 times the relation $\sin(2\theta) = 2\sin(\theta)\cos(\theta)$. There's got to be a better way.
$x\sqrt{10} = \prod\limits_{k = 1}^{90} \sin(k)$, k in degrees.

A: We use this, which is somewhat complicated.
Let $S$ be the product $\prod_{k=1}^{90} \sin k^\circ $. Then $S^2 = \prod_{k=1}^{179} \sin k^\circ  = \frac{ 180} { 2^{179}}$
Hence $S = \sqrt{ 10} \frac{3}{2^{89} }$.

I believe your method of using $\sin 2\theta$ repeatedly is better, in part because the proof of the quoted theorem is complicated.


text:
Q: Gmap missing XMLHttpRequest header I am using symfony framework to develop web site. Symfony recognize ajax call by  XMLHttpRequest header.
I have integrated Gmap on my page. Gmap making ajax request without XMLHttpRequest header.So symfony doesn't recognize ajax request.
Normal jquery ajax call have this header.
X-Requested-With XMLHttpRequest

But Gmap doesn't add this.
GDownloadUrl(searchUrl, function(data) {
  var xml = GXml.parse(data);
  ...
}

The GDownloadUrl makes this ajax call. How can i add this header with it.

A: I solved my problem by replacing GDownloadUrl function by jquery.get function.
jQuery.get('searchUrl',function(data) {
  var xml = GXml.parse(data);
  ...
}

This function attaches XMLHttpRequest header


text:
Q: designing data layer for a .net app I am developing a small app in .net. This app basically calls 6 to7 stored proc and 3 tables and then updates data to another table. I thought using entity framework with repository pattern was an overkill for this. A data layer class with static methods looks too simple.
Any thoughts on how to design data layer ?

A: First of all, Entity Framework works well with or without Repositories!
One of the Repository Pattern's goal is to add an abstraction layer between Doamin and Data layers.
If you're creating a simple application, where you're the only developper involved, keep in mind KISS and YAGNI principles!
Just create a Presentation layer, that will call Services in a Business layer, that will be responsible to call EF like this:
public void InsertThings(Entity1 entity1)
{
  using (var context = new MyContext())
  {
    var entity1 = new Entity1 { Name = "My first Entity" };
    context.Entity1.Add(entity1);
    context.SaveChanges();
  }
}

public IEnumerable<Customer> GetCustomers()
{
  var customers = db.customers

  return customers.ToList();
}


text:
Q: Uniform convergence of the action of a Feller semigroup in one variable. Assume we have two subsets of the some euclidean spaces $X\subset \mathbb{R}^m$ and $Y\subset\mathbb{R}^n$ and a a Feller semigroup $(Q_t)_{t\geq 0}$ on $Y$. Suppose also that we have a continuous function $f:X\times Y\to\mathbb{R}$ such that for each $x\in X$, the function $f_x:=f(x,\cdot)$ is in $C_0(Y)$, the space of continuous functions on $Y$ vanishing at the infinity, and there exists a bounded open neighbourhood $U(x)$ of $x$ such that $f$ is (uniformly) bounded on $U(x)\times Y$. I'm trying to show that if we define $\varepsilon(t,x,y)$ by
$$
\varepsilon(t,x',y)=\frac{1}{t}\int_0^t((Q_sf_{x'})(y)-f_{x'}(y))ds
$$
then $\varepsilon$ converges to $0$ as $t$ goes to $0$ uniformly on $x'\in U(x)$ (we may let $y$ fixed). Since $(Q_t)_{t\geq 0}$ is a Feller semigroup, we have pointwise convergence if we fix $x'$ and $y$, but I don't see how to use the exta hypothesis on $f$ to show the uniform convergence. By the estimate
$$
|\varepsilon(t,x',y)|\leq \frac{1}{t}\int_0^t|(Q_sf_{x'})(y)-f_{x'}(y)|ds\leq \frac{1}{t}\int_0^t\sup_{x'\in U(x)}|(Q_sf_{x'})(y)-f_{x'}(y)|ds
$$
I tried to show that the function $g(s,y)=\sup_{x'\in U(x)}|(Q_sf_{x'})(y)-f_{x'}(y)|$ is continuous in $s$ at $0$, but I couldn't get anything from this.
I think it may be solved by using the uniform continuity of $f$ in $U(x)\times\{y\}$, but still I don't see how to proceed.
Thanks in advance for any help.


text:
Q: validation against xsd and route invalid xml to rabbitmq in mule I am trying to validate xml again xsd and route invalid one to rabbitmq in mule.
I found schema validation component in mule but it seems like it only filter invalid one and pass valid one to the next flow.
Does anyone know how capture invalid one and route to rabbitmq queue in mule?
Thank you in advance.

A: You can wrap the schema validation inside a message filter.
This will pass the messages on to a flow named DeadLetterQueueFlow:
<message-filter onUnaccepted="DeadLetterQueueFlow" throwOnUnaccepted="false">
    <xml:schema-validation-filter/>
</message-filter>


text:
Q: x86 NASM Indirect Far Jump In Real Mode I have been messing around with a multi-stage bootloader and I have got all of my code to work, except for the last part: The Jump. I have gotten this code to work out before now but I wanted to make it more modular by replacing this line:
jmp 0x7E0:0

With this one:
jmp far [Stage2Read + SectorReadParam.bufoff]

Instead of hard coding where the code will load in, I wanted to do an indirect jump to it. Here's the rest of my code:
; This is stage 1 of a multi-stage bootloader

bits 16
org 0x7C00

jmp 0:boot_main

%include "io16.inc"

boot_main:
    ; setup the new stack
    cli
    mov ax, 0x100
    mov ss, ax
    mov bp, 0x4000
    mov sp, bp
    sti

    ; Setup data segment
    xor ax, ax
    mov ds, ax

    ; Save which drive we booted from
    mov [Stage2Read + SectorReadParam.drive], dl

    ; Home-made BIOS wrapper to read sectors into memory
    mov si, Stage2Read
    call ReadSectors

    ; Change to new data segment
    mov ax, [Stage2Read + SectorReadParam.bufseg]
    mov ds, ax

    ;jmp 0x7E0:0                                    ; THIS WORKS
    jmp far [Stage2Read + SectorReadParam.bufoff]   ; BUT THIS DOES NOT

; Used as the parameters for ReadSectors
Stage2Read: ISTRUC SectorReadParam
    AT SectorReadParam.bufoff,  dd 0
    AT SectorReadParam.bufseg,  dw 0x07E0
    AT SectorReadParam.numsecs, db 1
    AT SectorReadParam.track,   db 0
    AT SectorReadParam.sector,  db 2
    AT SectorReadParam.head,    db 0
    AT SectorReadParam.drive,   db 0        ; needs to be initialized!
IEND

; Ending
times 510-($-$$) db 0
dw 0xAA55

Remember all this code has been tested and works except for the indirect far jump to work. That's all I need to get this to work. I was wondering if maybe the indirect far jump implicitly is using for example ds so that the address Stage2Read + SectorReadParam.bufoff would be incorrect. This is really bugging me because it is so seemingly simple. I would like help!

A: You had a couple of bugs in your original code. The first was the fact that you had the offset using a DD (32-bit DWORD) instead of a 16-bit WORD. This line:
AT SectorReadParam.bufoff, dd 0

Should have been:
AT SectorReadParam.bufoff, dw 0

When you specify the memory operand for the FAR JMP by default (in your case) it is relative to the DS (data segment). Before the FAR JMP you set DS to a new value, so the JMP memory operand will read the memory address from the wrong segment (0x07e0 instead of 0x0000).
You can either set DS after you JMP or you can change the memory operand to be relative to CS (which is still the segment with the data) using an override. It could look like this:
jmp far [CS:Stage2Read + SectorReadParam.bufoff]

A: You're expecting jmp far to read its destination address from Stage2Read + SectorReadParam.bufoff, which is essentially 0x0000:Stage2Read + SectorReadParam.bufoff (ds = 0x0000).
However, just before the jump, ds is set to 0x07e0, so it seems to me that your code is reading its destination address from 0x07e0:Stage2Read + SectorReadParam.bufoff.


text:
Q: Не работает функция header Есть 2 файла
C:\WebServers\home\my_shop1\www\admin\login.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Вход в административную зону</title>

<form action="login_save.php" method="post">
Введите логин

<input name="users_login" type="text" />

Введите пароль

<input name="users_password" type="password" />

<input name="submit" type="submit" value="вход в админ зону" />
</form>

и C:\WebServers\home\my_shop1\www\admin\login.php
<?php
    include_once('blocks/bd.php');
    session_start();
    if ($_POST)
    {
        $users_login=$_POST['users_login'];
        $users_password=$_POST['users_password'];

        $users_login=mysql_real_escape_string(trim(strip_tags($users_login)));
        $users_password=mysql_real_escape_string(trim(strip_tags($users_password)));

        $sql_user = "SELECT count(*) FROM users WHERE users_login='$users_login' AND users_password='$users_password'";
        $query_user=mysql_query($sql_user) or die(mysql_error());
        $num_rows=mysql_num_rows($query_user);
    }
        header('Location: ../index.php');

?>

и есть также файл C:\WebServers\home\my_shop1\www\index.php, на который не перебрасывает функция header после успешного ввода пароля и перехода со страницы login на login_save.php. В чем причина?
A: *

*Сохранить файлы в UTF-8 без BOM

*Возможно вот тут include_once('blocks/bd.php'); есть какой-то вывод.

*Еще вариант: $query_user=mysql_query($sql_user) or die(mysql_error());  тут происходит ошибка


text:
Q: Attempting to run Kafka Connect in distributed mode locally, problem with internal topics I am continuing to run Kafka Connect locally using this repo and specific folder path: https://github.com/entechlog/kafka-examples/tree/master/kafka-connect-standalone
I have added AWS MSK IAM authentication to this repo, as well as a few other small changes which allow it to run in distributed mode (in the launch shell script, I added this line exec connect-distributed /etc/"${COMPONENT}"/"${COMPONENT}".properties).
When I run the build, this is the error I get:
[2021-12-08 11:19:48,497] ERROR [Worker clientId=connect-1, groupId=connect-kafka-connect-group] Uncaught exception in herder work thread, exiting:  (org.apache.kafka.connect.runtime.distributed.DistributedHerder:324)

org.apache.kafka.common.errors.TopicAuthorizationException: Not authorized to access topics: [connect-offsets]
And the kafka-connect container stops/exits. Earlier in the logs, I noticed this:
[2021-12-08 11:19:47,279] INFO Unable to use admin client to verify the cleanup policy of 'connect-offsets' topic is 'compact', either because the broker is an older version or because the Kafka principal used for Connect internal topics does not have the required permission to describe topic configurations. (org.apache.kafka.connect.util.TopicAdmin:506)

And I have made sure in my docker-compose.yml file, I have changed the kafka-connect image to image: confluentinc/cp-kafka${CONFLUENT_VERSION_TAG} and I have added ${CONFLUENT_VERSION_TAG} to all four images (and ${CONFLUENT_VERSION_TAG}=:latest).
I have also tried to create the three required internal topics manually in the launch shell script, before running the connect-distributed command which I added (I mentioned this earlier):
kafka-topics --create --bootstrap-server broker:9092 --topic connect-configs --replication-factor 1 --partitions 1 --config cleanup.policy=compact
kafka-topics --create --bootstrap-server broker:9092 --topic connect-offsets --replication-factor 1 --partitions 50 --config cleanup.policy=compact
kafka-topics --create --bootstrap-server broker:9092 --topic connect-status --replication-factor 1 --partitions 10 --config cleanup.policy=compact
and when I bash into the broker container I see:
__consumer_offsets
_schemas
along with the 3 topics I created above.
I did see this solution about the __consumer_offsets topic being corrupt: kafka connect failed to start with 'Uncaught exception in herder work thread.... position could be determined'' but I don't know how to check if that topic is corrupt or even how to create a new Kafka cluster (I have been rebuilding this image constantly anyways.
I also saw this solution: Kafka + Zookeeper: Connection to node -1 could not be established. Broker may not be available and attempted changing localhost/broker at multiple lines in the docker-compose.yml file. When I do this, I continue seeing the same error in the kafka-connect container about not being authorized for those internal topics. When I check the broker for topics, I see nothing when I try to list them.
In that same solution, I saw we can try adding this to the active listeners: KAFKA_ADVERTISED_LISTENERS=PLAINTEXT://localhost:9092 --link zookeeper:zookeeper confluent/kafka and so I tried that, and the broker container just exist saying it can't parse that line in the docker-compose.yml file.
So at this point I'm thinking there is an issue with the broker communicating with kafka connect, or something doesn't have the right permissions to create these three internal topics in the broker? Or, it can create them, but can't later access them? Not likely but is there a problem with the broker's version being too old? That wouldn't make sense since I used :latest.
One of the answers to my other question here Running Kafka connect in standalone mode, having issues with offsets is saying that the offset topics are for Source connectors. Well this certainly isn't a source connector and I couldn't tell you why kafka thinks my connector is a source connector (it's a sink connector). The answer also says that sink connectors use consumer groups. I have no idea what that means insofar as my problem is concerned.
All I know is that I must specify my offset topic (which I did manually as above, as well as in my docker-compose file), and that I don't know where this topic was created, if it was created at all, and where it is supposed to actually exist. Lastly, I have no idea why I am not authorized to access this topic if my kafka cluster created it locally.
I have tried everything I can imagine and I keep coming up on empty. Some assistance is greatly appreciated


text:
Q: How Flash Bios Nokia booklet 3g I would like to know how to flash a bios mod that have extension .rom
This guys, of "bios mod forum" made this modded bios
Link to download the modded bios: here
I searched but nobody says how to flash a .rom bios. My USB is FAT32 formatted, 8GB.
I tried to put the file in the USB and boot from the USB, but it says:

System found not found

I have no OS installed in the HDD.
How to flash using .rom BIOS?


text:
Q: How can I take my PHP script name out of URLs? htaccess rule isn't working. I have a PHP script which accepts some query string parameters. However, I want the user to call it without including the script name e.g. example.com/?foo=bar.
I've tried writing a mod_rewrite rule, but it redirects the user, which isn't what I want.

A: If you rename the script to index.php, accessing example.com/?p=asd&p2=dsa should work.
For the RewriteRule, make sure you don't have [R] after it.


text:
Q: Does dconf remove/rewrite the configuration files placed in ~/.config/[program] when using 'reset' command? As much as I know the files that keep the various programs' settings are placed in ~/config/[program].
Today I've encountered to question 1035307.
The answer mentioned dconf reset -f /org/gnome/gedit/ command, and when I entered that command in my terminal all of my settings in gedit have been reverted to default.
Now I'm wondering how dconf has reset my settings! Did it just rewrite all of the configurations with the default one?

A: The best method to determine what was changed is to place parts of your home folder under source code version control system such as Git.
While using such method you can determine that one binary file was changed - it is named ~/.config/dconf/user. So the short answer is yes - the file was changed.
Personally I'm using the following method to determine what was changed after editing settings of some application (from GUI, with dconf/dconf-editor or by gsettings):

*

*I save current settings to the files
dconf dump / > /tmp/dconf_before
gsettings list-recursively | sort --unique > /tmp/gsettings_before

*Then I change some settings.

*Afterwards I save new settings to the files
dconf dump / > /tmp/dconf_after
gsettings list-recursively | sort --unique > /tmp/gsettings_after

*Compare obtained files with meld (visual diff tool):
meld /tmp/dconf_before /tmp/dconf_after
meld /tmp/gsettings_before /tmp/gsettings_after

Free bonus: you can create small dconf- or gsettings-based dumps to apply the settings from terminal and get settings that you like with one long command:
* using dconf:
dconf load / << EOF
[org/gnome/gedit/preferences/editor]
display-right-margin=true
highlight-current-line=true
display-overview-map=true
bracket-matching=true
auto-save=true
create-backup-copy=true
display-line-numbers=true
insert-spaces=true
background-pattern='grid'
wrap-last-split-mode='word'
auto-indent=true

[org/gnome/gedit/preferences/ui]
show-tabs-mode='auto'

[org/gnome/gedit/plugins]
active-plugins=['time', 'quickopen', 'filebrowser', 'spell', 'pythonconsole', 'sort', 'externaltools', 'modelines', 'snippets', 'docinfo']

EOF

* using gsettings:
org.gnome.gedit.preferences.editor auto-indent true
org.gnome.gedit.preferences.editor auto-save true
org.gnome.gedit.preferences.editor background-pattern 'grid'
org.gnome.gedit.preferences.editor bracket-matching true
org.gnome.gedit.preferences.editor create-backup-copy true
org.gnome.gedit.preferences.editor display-line-numbers true
org.gnome.gedit.preferences.editor display-overview-map true
org.gnome.gedit.preferences.editor display-right-margin true
org.gnome.gedit.preferences.editor highlight-current-line true
org.gnome.gedit.preferences.editor insert-spaces true
org.gnome.gedit.preferences.ui show-tabs-mode 'auto'
org.gnome.gedit.plugins active-plugins ['time', 'quickopen', 'filebrowser', 'spell', 'pythonconsole', 'sort', 'externaltools', 'modelines', 'snippets', 'docinfo']


text:
Q: Put the author's name on maps? I've been informed by my employer of a new policy where I am not to put my name on maps. I've always put my name on my maps in the past and have never run across this policy. Is it uncommon in the industry to add the map author's name to maps?

A: I just took over as the sole GIS analyst where I work.  The GIS guy before me put his name on all the maps he made, but I decided to leave my name off all the maps I design from now on.
I think putting your name on a map (if you work for an organization) is a little bit tacky, and cheapens the map for your employer.  I think this is especially true if your publishing authoritative data (vs. some unique design).
Just my take on it.

A: OK, it's a fictional example, but what about Slartibartfast who had a penchant for signing his name in glaciers?!
Seems there are some hidden signatures in Google Earth too.

A: It is not uncommon, as the map can be considered company property (both intellectual and artistic property) as opposed to an individual's work. Some cartographers circumvent this by hiding their name/initials/signature in a feature on the map. This is accomplished by using a slightly different color, and/or stylizing the signature to look like part of the symbology. There are probably other methods as well. It's very easy to do the slightly different color "trick" with GIS.


text:
Q: McFadden's R2 > 1? I calculated a McFadden's R2 = 1.94094. Repeatedly. What have I done wrong? Is it inappropriate to use McFadden's R2 for conditional maximum likelihood?

A: So we will still need to that log-likelihood function, but it is possible that the Mcfadden r-squared is larger than 1. But it is not something that will happen often. Suppose for example that:
$$
R^2_{MC} = 1 - \frac{LogLik_{unrestricted }}{LogLik_{restricted}}= 1 - \frac{1}{-3} = 1.33
$$
Or you could reverse the sign in the fraction. In any case, the button line is that you need one of the log-likelihood functions to actually be positive in order for this to happen. Otherwise you made some mistake.
Now a positive log-likelihood function can happen, and does not automatically mean that you made some mistake.


text:
Q: Owl Carousel 2 - Turn off functionality for desktop I'm building a website where I need to have touch enabled swipe functionality for mobile but then fall back to the default styling for larger screensizes.
I've tried using the code below to remove the class which is passed to the OWL function but unfortunately it doesn't work in the way I need it to. It simply creates a larger version of the slider for desktop when I need to to completely ignore the OWL function completely unless it is on mobile.
Below is all the code I am using. Let me know if there is a solution to this that someone else has come across or if you need more info my end.
HTML
<div class="row bookRow row-single is_scrollable col-sm-12" style="background-color: <?php echo $bg_color; ?>;">
    <?php foreach($products as $product){ ?>

            <a href="<?php echo $product['href']; ?>">
                <img src="<?php echo $product['thumb']; ?>" />

                <?php echo $product['cart_link']; ?>

                <a href="<?php echo $product['href']; ?>" class="title-link"><?php echo $product['name']; ?>

                <?php echo $product['author']; ?>

    <?php } ?>

CSS
/* PRODUCT LISTINGS */
.product-list-box {
    margin: 10px;
    -webkit-box-shadow: 0 3px 7px -1px #E3E2E2;
    -moz-box-shadow: 0 3px 7px -1px #E3E2E2;
    box-shadow: 0 3px 7px -1px #E3E2E2;
    background-color: #F5F3E7;
    float: left;
}
.product-list-box img {
    /*margin: 0px;
    padding: 0px;
    width: 100%;
    max-width: 200px;*/
}
.product-list-box .caption {
    display: none;
}
.product-list-box img:hover, .author-list-box img:hover {
    opacity: 0.8;
}

JS
$(document).ready(function() {

$(window).resize(function() {
 if($(window).width() < 767){
    $('.row-single').addClass('is_scrollable owl-carousel owl-theme owl-loaded owl-text-select-on');
 } else {
    $('.row-single').removeClass('is_scrollable owl-carousel owl-theme owl-loaded owl-text-select-on');
 }
});

$('.is_scrollable').owlCarousel({
    loop:true,
    margin:0,
    nav:false,
    mouseDrag: false,
    touchDrag: true,
    responsive:{
        0:{
            items:2
        },
        600:{
            items:3
        }
    }
})

});

A: Try adding the verification in your document ready state. Try this
$(document).ready(function() {
    if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ){
        $('.row-single').addClass('is_scrollable owl-carousel owl-theme owl-loaded owl-text-select-on');
     } else {
        $('.row-single').removeClass('is_scrollable owl-carousel owl-theme owl-loaded owl-text-select-on');
     }
}

$('.is_scrollable').owlCarousel({
    loop:true,
    margin:0,
    nav:false,
    mouseDrag: false,
    touchDrag: true,
    responsive:{
        0:{
            items:2
        },
        600:{
            items:3
        }
    }
})

});

A: Working perfect Simple solution no need js
Just add CSS.
.owl-carousel .owl-stage{
width:100% !important;
transition:inherit !important;
transform:inherit !important;
}
.owl-carousel.owl-drag .owl-item{
    width:50% !important;
}


text:
Q: AngularJS : ng-switch is not triggering when i was clicking second time? I have a left nav in my one of the view of the application  whiich is build using ng-repeat and ng-switch. every link's action associate to a directive in the right hand side. some time, the particular directive will include other directive when user click on the dropdown items from the current directive and page gets extended long and long , so if user want to go to the original state then he can click on the nav item from the left nav to refresh the page to the initial state of the directive. But whenever user clicks on the left nav second time when the left nav already selected, it is not get triggered.I want this get tirggered to bring my initial page of the RHS.
My highlevel code as follows
about.html

         {{link.title}}

aboutController.js
  $scope.links = [{ title="About Us", value="about"},
                    { title="Board Directors",value="board"},
                    { title="Our Impacts", value="impact"} ];
    var myParam =$root.current.params;
    $scope.param = myParam.sec;
   //sec has been configured in the route and get
   // the values from user's input
    $scope.fetchLink() = function() {
      var retVal='';
      var retVals = $.grep($scope.links, function(item,ind){
                          return item.value=$scope.param
                        });
        if(retVals.length>0){
            retVal = retVals[0].title;
         }

         return retVal;

         };
        };

On the router code of app.js
$routeProvider
.when('/about/:sec', {
   templateUrl : 'app/view/about.html',
   controller: 'aboutController.js'
});

}
When i click the second time, nothing get triggered and fetchLink() method is not triggered.


text:
Q: Why does the exception is thrown if we declare both read and write resources? I'm experimenting with Serialization and wrote the following class:
public static void main(String[] args) throws ClassNotFoundException{
    File file = new File("D:/serializable.txt");
    try(FileOutputStream fos = new FileOutputStream(file);
            ObjectOutputStream ous = new ObjectOutputStream(fos);
          FileInputStream fis = new FileInputStream(file);
          ObjectInputStream ois = new ObjectInputStream(fis)){
//      SerialTest st = new SerialTest();
//      ous.writeObject(st);
        SerialTest st = (SerialTest) ois.readObject();
        System.out.println(st);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Serialized class:
public static class SerialTest implements Serializable{

    private int count;

    private Object object;

    public int count(){
        return count;
    }

    public Object object(){
        return object;
    }

    private void readObject(ObjectOutputStream ous) throws IOException{
        ous.writeObject(object);
        ous.writeInt(count);
    }

    private void writeObject(ObjectInputStream ois) throws IOException, ClassNotFoundException{
        ois.readInt();
        ois.readObject();
    }
}

After serializing the object as in the commeted code, I tried to desirialize it as specified here. I got
java.io.EOFException
    at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2598)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1318)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370)

Moroever, the content of the file containing the serialized object is chaged.
But when I remove the resource-declarations
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream ous = new ObjectOutputStream(fos);

from the try-with-resources clasuse it works completely fine. Why? Why the resource declarations affects the deserialization?

A: Well without the write calls, you're currently creating an empty file to start with, because that's what the FileOutputStream constructor you're calling does. If the file already exists, it is truncated to be 0 bytes long. So when you then try to read an object from it, there's nothing to read.
Even with the writing part uncommented, there's still the possibility of buffering issues, where the data hasn't actually been written to the file yet.
I would strongly urge you to write the file and close the output stream, and then separately open it for input. Having the same file open for read and write at the same time seems like a recipe for confusing results to me.
So the code would look something like this:
// Exception handling omitted as this is just test code
public static void main(String[] args) throws Exception {
    File file = new File("D:/serializable.txt");
    try (FileOutputStream fos = new FileOutputStream(file);
         ObjectOutputStream ous = new ObjectOutputStream(fos)) {
        SerialTest st = new SerialTest();
        ous.writeObject(st);
    }
    try (FileInputStream fis = new FileInputStream(file);
         ObjectInputStream ois = new ObjectInputStream(fis)) {
        SerialTest st = (SerialTest) ois.readObject();
        System.out.println(st);
    }
}

A: Leaving aside the fact that you obviously have the content of readObject() and writeObject() back to front:
private void readObject(ObjectOutputStream ous) throws IOException{
    ous.writeObject(object);
    ous.writeInt(count);
}

Here you are writing first the object then the integer.
private void writeObject(ObjectInputStream ois) throws IOException, ClassNotFoundException{
    ois.readInt();
    ois.readObject();
}

Here you are reading first the integer then the object.
Ain't gonna work.
BUT ... You don't need either of these methods. Remove them. Or, if you want to serialize data of the parent class, fix them to (a) call defaultReadObject() and defaultWriteObject() respectively, and get rid of what you already have in there, which will already happen by default, or at least when you read the object and the integer in the same order as you wrote them, store them into the respective instance members.
NB serialized data isn't text and shouldn't be stored in files named .txt.


text:
Q: Как реализовать прозрачность вокруг указателя? Коллеги подскажите на JS(или на чистом css возможно) при помощи чего можно реализовать подобное решение
https://www.kikk.be/2018/en/home
Прозрачность области, при наведении мыши, определенного радиуса.
Пройдите по ссылке поводите мышкой, чтоб понять о чем я.
Благодарен заранее.

A: По вышеприведенной ссылке все нарисовано на канве. И это не прозрачность.
Нечто подобное можно сделать с svg + mask или clip-path
Верхнее изображение размыто блюром и из него вырезаны круги, а нижнее такое же как верхнее только без блюра и вырезанных кругов.
Таскайте мышкой за круги

let d = [[100,100,70], [300,100,60], [500,100,50]]
         .map(d=>({x: d[0], y: d[1], r: d[2]}));
let mask = circles('mask').call(upd);

circles('g').style('fill','transparent')
  .style('cursor','pointer')
  .call(upd)
  .call(d3.drag().on("drag", function (d) {
    d3.select(this)
      .attr("cx", d.x = d3.event.x)
      .attr("cy", d.y = d3.event.y);
    mask.call(upd)
  }));

function circles(selector) {
  return d3.select(selector)
           .selectAll('circle')
           .data(d)
           .enter()
           .append('circle')
}

function upd(selection) {
   selection.attr("cx", d => d.x)
            .attr("cy", d => d.y)
            .attr('r',  d => d.r);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg viewBox="0 0 600 600">
<defs>
  <filter id="blurfilter" width="110%" height="100%">
   <feGaussianBlur stdDeviation="12" result="blur" />
  </filter>
  <mask id="hole">
    <rect width="100%" height="100%" fill="#fff"/>
  </mask>
</defs>
<image x="-50%" y="-50%" height="200%" width="200%"
       xlink:href="https://i.imgur.com/cdqfoqZ.png"/>
<image mask="url(#hole)" filter="url(#blurfilter)"
       x="-50%" y="-50%" height="200%" width="200%"
       xlink:href="https://i.imgur.com/cdqfoqZ.png" />
<g></g>
</svg>

PS: если же хочется получить эффекты побогаче придется обратиться на темную сторону (WebGL)


text:
Q: How to create a customized page same as the OOTB osssearchresults.aspx? We are using SP2013 on-premise standard edition. There is a small site collection and make use of osssearchresults.aspx. There is one problem for osssearchresults.aspx because we have no option to edit the search result web part. We want to enable "show duplicate" option.
I have tried create a blank page and insert the search webparts. However, I don't know how to make the refinement panel show up at the left. (I want to make it look exactly like osssearchresults.aspx)
Is my only option is create a search center (as a subsite) under the site collection?

A: You can just create a web part page and add the necessary search web parts. Search Box, Refinement and Results are just web parts. The query can be passed on the query string or you can include a link to this page.


text:
Q: Symfony3 Failed to create object I using Sonata Admin bundle. I get error: Failed to create object: PizzaBundle\Entity\Promotion. I did a Promotion entity:
/**
 * @ORM\Entity
 * @ORM\Table(name="promotion")
 */
class Promotion {

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=100)
     */
    private $title;

    /**
     * @ORM\Column(type="string")
     */
    private $description;

    /**
     * @ORM\Column(type="blob")
     */
    private $image;

    /**
     * @ORM\Column(type="date")
     */
    private $dataStart;

    /**
     * @ORM\Column(type="date")
     */
    private $dataEnd;

And PromotionAdmin.php
public function configureFormFields(FormMapper $formMapper) {
        $formMapper
                ->add('title', 'text')
                ->add('description', 'text')
                ->end()
                ->with('Zdjęcie')
                    ->add('image', 'file', ['required' => false])
                    ->add('dataStart', 'date')
                    ->add('dataEnd', 'date')
                ->end();
    }

    protected function configureDatagridFilters(DatagridMapper $datagridMapper)
    {
        $datagridMapper
                ->add('title')
                ->add('description')
                ->add('image')
                ->add('dataStart')
                ->add('dataEnd')
                ;
    }

    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper
                ->addIdentifier('title')
                ->addIdentifier('description')
                ->addIdentifier('image')
                ->addIdentifier('dataStart')
                ->addIdentifier('dataEnd')
                ;
    }

}

My services.yml
admin.promotion:
        class: PizzaBundle\Admin\PromotionAdmin
        arguments: [~, PizzaBundle\Entity\Promotion, ~]
        tags:
            - { name: sonata.admin, manager_type: orm, label: Promotion }

I don't have a problem with my code. I think that this is problem with type variable Image in entity. If this is error in type blob, please help resolve problem.

A: You are trying to insert NULL into the "image" column, which is not nullable it seems, which results in an MySQL error.
/**
 * @ORM\Entity
 * @ORM\Table(name="promotion")
 */
class Promotion
{
     /**
      * @ORM\Column(type="blob", nullable=true)
      */
     private $image;
}


text:
Q: Remove current url path and replace? How do i delete the current url path and return to index.php? I have a link to a page in a subfolder - the generated url could look like this:
http://localhost/site/pages/home.php

How do i erase that url path and return to index.php in root http://localhost/site/index.php
So far i have this which will show index.php in root, but it doesnt delete the original url path containing home-php?
$('#btn').click(function() {
   window.location.href='index.php';
});

The url looks like this http://localhost/site/pages/home.php/site/index.php

A: Just reload the page and redirect the user to the good page :
window.location.href='/index.php';

EDIT :
Or try to rebuild your url :
// If URL is http://www.somedomain.com/account/search?filter=a#top

window.location.pathname // /account/search

// For reference:

window.location.host     // www.somedomain.com (includes port if there is one)
window.location.hostname // www.somedomain.com
window.location.hash     // #top
window.location.href     // http://www.somedomain.com/account/search?filter=a#top
window.location.port     // (empty string)
window.location.protocol // http:
window.location.search   // ?filter=a

And redirect with the full url, not just/index.php


text:
Q: How can I connect to Amazon Elastic Beanstalk through IP and port? I want to connect to my Python app on Elastic Beanstalk via TCP socket by using IP and port. Where can I get those information? I tried using Elastic IPs in EC2 but I can't connect to it. Do I have to set something to make it works?

A: If you are using a Single Instance Environment type then you'll be able to use a IP however if you're using the Load balancing, autoscaling Environment type then you'll need to you CNAMES.
Secondly you'll need to open the port you want to connect to by either manually opening in the EC2 security groups or using .ebextensions because by default only certain ports are open.
Log into your machine and telnet to the localhost and the port of your Phyton application, if you connect then; find the IP of your machine, open the port in the EC2 security group assigned to that instance and try the telnet again which will tell you if you port listening or not.


text:
Q: how to make a div draggable and droppable One thing left in my project was to make the two divs draggable and droppable simultaneously. Now I have the working code of divs that can be dragged and dropped but for example I can drag a div from target area and drop it on users area but I cant seem to figure out a way to drag those divs from users and assign to different users.
$(document).ready(function(){
    $(".dragable").draggable({
        cancel: "a.ui-icon",
        revert: true,
        helper: "clone",
        cursor: "move",
        revertDuration: 0
    });

    $('.droppable').droppable({
        accept: ".dragable",
        activeClass: "ui-state-highlight",
        drop: function( event, ui ) {
            // clone item to retain in original "list"
            var $item = ui.draggable.clone();
            $(this).addClass('has-drop').append($item);
        }
    });
});

http://jsfiddle.net/coder880/TpbZk/31/

A: The issue is because once the item is dragged/dropped it is then cloned. This clone does not have the draggable() plugin instantiated on it. You need to call draggable() on the $item again. Try this:
var draggableOptions = {
    cancel: "a.ui-icon",
    revert: true,
    helper: "clone",
    cursor: "move",
    revertDuration: 0
}

$(".dragable").draggable(draggableOptions);

$('.droppable').droppable({
    accept: ".dragable",
    activeClass: "ui-state-highlight",
    drop: function(event, ui) {
        var $item = ui.draggable.clone();
        $item.draggable(draggableOptions);
        $(this).addClass('has-drop').append($item);
    }
});

Updated fiddle

it should only be cloned when its from target otherwise it should move it.

To achieve this you need to remove the helper: 'clone' option in the cloned draggable element and maintain a flag on the element to determine whether it is a brand new clone or has been dragged previously and moved again. To do this you could use a class, something like this:
$(".dragable").draggable({
    cancel: "a.ui-icon",
    revert: true,
    helper: "clone",
    cursor: "move",
    revertDuration: 0
});

$('.droppable').droppable({
    accept: ".dragable",
    activeClass: "ui-state-highlight",
    drop: function(event, ui) {
        var $item = $(ui.draggable)
        if (!$item.hasClass('clone')) {
            $item = $item.clone().addClass('clone');
            $item.draggable({
                cancel: "a.ui-icon",
                revert: true,
                cursor: "move",
                revertDuration: 0
            });
        }
        $(this).addClass('has-drop').append($item);
    }
});

Example fiddle


text:
Q: How to effectively use Categorical Variables in a regression? I'm trying to understand how to use categorical variables in a linear regression in R. I have some insurance data that has a categorical variable of coverage type (basic, extended and premium). When I run a simple linear regression:
summary(lm(Customer.Lifetime.Value ~ Coverage, data = ins)) #basic sig but might not include

Coefficients:
                 Estimate Std. Error t value Pr(>|t|)
(Intercept)          8498       2829   3.004   0.0198 *
CoverageExtended    -1314       5658  -0.232   0.8230
CoveragePremium      1554       5658   0.275   0.7915
---
Signif. codes:
0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

The intercept is statistically significant, which means the variable not represented "Basic" is significant.
However when I try to isolate that variable with and rerun the model:
ins$isBasic <- ifelse(ins$Coverage == "Basic", 1, 0)

summary(lm(Customer.Lifetime.Value ~ isBasic, data = ins))

            Estimate Std. Error t value Pr(>|t|)
(Intercept)   8617.8     3280.5   2.627   0.0303 *
isBasic       -119.8     4235.1  -0.028   0.9781
---
Signif. codes:
0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Now the basic policy is no longer significant but the new intercept is, meaning the other columns combined are sig.
I'm new to this type of regression and not sure if I'm coding or selecting the features correctly.

A: Your assumptions about what the model means aren't quite right. The intercept's p value only tells you that the intercept is statistically different from 0.
Suppose I take 30 numbers drawn from a normal distribution with a mean of 1:
set.seed(1)
y <- rnorm(30, 1)

Now suppose each of these is associated with a factor level - "A", "B" or "C":
df <- data.frame(x = factor(rep(c("A", "B", "C"), 10)), y = y)

Now let's do the regression of y on x and examine the model summary:
summary(lm(y ~ x, data = df))
#>
#> Call:
#> lm(formula = y ~ x, data = df)
#>
#> Residuals:
#>     Min      1Q  Median      3Q     Max
#> -2.2814 -0.5159  0.1899  0.6256  1.4716
#>
#> Coefficients:
#>             Estimate Std. Error t value Pr(>|t|)
#> (Intercept)  1.12371    0.30270   3.712 0.000943 ***
#> xB          -0.05706    0.42809  -0.133 0.894958
#> xC          -0.06671    0.42809  -0.156 0.877332
#> ---
#> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#>
#> Residual standard error: 0.9572 on 27 degrees of freedom
#> Multiple R-squared:  0.00105,    Adjusted R-squared:  -0.07295
#> F-statistic: 0.01418 on 2 and 27 DF,  p-value: 0.9859

We can see that the mean of the group of y values associated with the factor level "A" is significantly different from 0 - that's all the intercept's p value tells us. The coefficients for the factor levels "B" and "C" are not significantly different from the intercept, meaning that the y values associated with "B" and "C" are not significantly different from the y values associated with "A". That just means that there is no significant difference between your factor levels. If you want to know whether the groups within x are associated with significantly different values of y overall, you can try anova:
anova(lm(y ~ x, data = df))
#> Analysis of Variance Table
#>
#> Response: y
#>           Df Sum Sq Mean Sq F value Pr(>F)
#> x          2  0.026  0.0130  0.0142 0.9859
#> Residuals 27 24.740  0.9163

where we see that the proportion of the overall variance in y accounted for by the variance between the mean of the three groups in x is tiny, and not statistically significant from the null hypothesis that there is no relationship between x and y - which is what we expect given how this data set was generated.


text:
Q: hot reload needs to be done for app to run I am working on a Flutter app that uses Firebase and a Stream to show a list view if the data in Firebase is != null. If the data is null, I have my code display a loading sign. Whenever I launch my app, to begin with, the loading symbol is the first thing to come up and doesn't go away until I hot reload my app. When I hot restart again, I need to hot reload for the data to show up. If I ever publish my app will this issue come up for users or is it only because I am in Debug mode in my simulator? If this is an issue that may come up when the app is published, does anyone know how to fix this?
code:
  Widget MemoirsList() {
    return SingleChildScrollView(
      child: memoirsStream != null
          ? Column(
              children: <Widget>[
                StreamBuilder(
                  stream: memoirsStream,
                  builder: (context, snapshot) {
                    return ListView.builder(
                        padding: EdgeInsets.symmetric(horizontal: 16),
                        itemCount: snapshot.data.documents.length,
                        shrinkWrap: true,
                        physics: NeverScrollableScrollPhysics(),
                        itemBuilder: (context, index) {
                          return MemoirsCard(
                            authorName: snapshot.data.documents[index].data['authorName'],
                            title: snapshot.data.documents[index].data["title"],
                            description: snapshot.data.documents[index].data['description'],
                            imgUrl: snapshot.data.documents[index].data['imgURL'],
                          );
                        });
                  },
                )
              ],
            )
          : Container(
              alignment: Alignment.center,
              child: CircularProgressIndicator(),
          ),
    );
  }

A: It is definitely related to the Debug mode. I've been facing this issue a lot too. Try to build it in release mode and it should work fine.  The app size of a debug build is large due to the debugging overhead that allows for hot reload and source level debugging.
When building a release version of your app, consider using the --split-debug-info tag. This tag can dramatically reduce code size. For an example of using this tag, see Obfuscating Dart code.
Other things you can do to make your app smaller are:

*

*Remove unused resources

*Minimize resource imported from libraries

*Support a limited number of screen densities

*Compress PNG and JPEG files

To build a release version for Android
To build a release version for IOS


text:
Q: How to start a new activity by clicking on an image using gallery? I want to have a something like a screen with a set of scroll-able images where if i click on each image it should start a new activity (). Can I use the android gallery for this purpose? my idea behind using gallery is because i'm using a set of images. so then if i can have them to be in my res folder.
UPDATE
Gallery Class (stack wouldnt let me comment for some reason :( )
Thanks

A: You can certainly add an onItemClickListner to the gallery view and use that launch on activity.
  gallery.setOnItemClickListener(new OnItemClickListener(){
      public void onItemClick(AdapterView<?> parent, View v, int position, long id){
      if(position == WantedImage){
          StartActivity(new Intent(CurrentActivity.this,ActivityToLaunch.class));
      }
  }


text:
Q: Timeseries : date time averaging and abnormally detection I"m dealing with a dataset with 4 week sales data (data will be refreshed every hour) and need to observer for abnormality
I think I'll go with a basic approach, to compare with average numbers and I'm trying to figure out how to best break this down so I can answer some questions below

*

*On average, how many orders received at 9:00 , 15:00 or 16:00 past 30 days

*On average, how many orders received at 9:00 every Wednesday (past 4 Wednesdays), at 15:00 every Thursday (past 4 Thursdays),
Not sure how do we go about this (after breaking date/time down to Hour and Weekday columns)

date
order ID
order hour
order weekday

10/07/2022  10:26:12 PM
1111
22
6

10/07/2022  10:27:12 PM
2222
22
6

....
....
....
....

19/07/2022  11:34:19 AM
9998
11
1

19/07/2022  11:34:35 AM
9999
11
1

I would love to get your advice please
Thanks

A: I've ended up going with a tedious approach.
#get current hour & weekday
now=datetime.datetime.now()
today=datetime.date.today()
current_hour=now.hour
current_weekday=today.weekday()

#create a DF with orders from the same hour & weekday window
same_hour_weekday_df=order_df[(order_df.order_hour==current_hour ) & (order_df.order_weekday==current_weekday)  ]

#calculate avg orders generated from the past weeks within the same hour and weekyday timeframe
orders_same_hour_weekday=same_hour_weekday_df['order_created_at'].count()
same_hour_weekday_periods=same_hour_weekday_df['order_week'].nunique()
avg_orders_same_hour_weekday=orders_same_hour_weekday/same_hour_weekday_periods


text:
Q: How to summarize SQL search result of column B as sum based on data in column A? I have created an SQL formula to search for the time spent on a signal status for specific machines:
SELECT 'Core' as Core, Z.EventName, ISNULL(DIFF,0) AS DIFF
FROM (select distinct MacID, EventName from dbo.tblMachine a
join (SELECT DISTINCT EVENTNAME FROM dbo.tblEvtDur)
b on b.EventName <> '' and MacID in ('A06','A07', 'A08', 'A09', 'B01','B05','B09', 'B10', 'B11', 'C04', 'C08', 'C09') )
z LEFT JOIN (SELECT A.MacID, A.EventName, SUM(DATEDIFF(SECOND, A.STARTdt, A.eNDdt))
as diff,round(SUM(DATEDIFF(SECOND, A.STARTdt, A.eNDdt)) / cast(aVG(Tdiff)
as decimal(30,8)),4) * 100 AS PER FROM dbo.tblEvtDur  A
LEFT JOIN ( SELECT macid, SUM(DATEDIFF(SECOND, STARTdt, eNDdt)) as Tdiff
FROM  dbo.tblEvtDur  WHERE DayID between '20180401' and '20180430'
GROUP BY MacID ) B ON  A.MacID = B.MacID
WHERE DayID between '20180401' and '20180430'
AND A.MacID in
 ('A06','A07', 'A08', 'A09', 'B01','B05','B09', 'B10', 'B11', 'C04', 'C08', 'C09')
group by A.MacID, A.EventName) a
ON A.EVENTNAME = Z.EVENTNAME  and Z.MacID  = a.MacID order by Z.MacID, Z.EventName

What I got as a result was as seen here:

Now I want to have the SQL show me the sum total of EventName BLK, MDL, MTL, OFF, RPR, and RUN, for these specific machines. Is that possible?
Edit:
If I try adding a sum with group by clause, it doesn't work on the current SQL.
So I had to reconstruct it into so:
select 'Core' as Core, EventName, sum(DATEDIFF(second, startdt, EndDT)) as DIFF
from dbo.tblEvtDur

where MacID in ('A06','A07','A08','A09','B01','B05','B09','B10','B11','C04','C08','C09')

and DayID between '20180531' and '20180531'

group by eventname

But depending on the day, certain signals will not appear so it is not listed in the result table.

What should I add to tell SQL to show me EventName BLK as 0?
Edit 2:
So far tried Dan's suggestion of using right join:
select 'Core' as [Core], a.EventName, isnull((sum(DATEDIFF(second, startdt, EndDT))),0) as DIFF
from dbo.tblEvtDur a
right join (select distinct eventname from dbo.tblEvtDur where EventName in
('BLK', 'MDL', 'MTL', 'OFF', 'RPR', 'RUN')) b
on a.EventName = b.EventName
where MacID in ('A06','A07', 'A08', 'A09', 'B01','B05',
'B09', 'B10', 'B11', 'C04', 'C08', 'C09')
and DayID between '20180531' and '20180531'
group by a.eventname

Again, same results but time taken is significantly longer.

A: Use aggregate function (sum, count, avg...) with group by.
 select count(*) from (output of your query) group by EventName;

A: Your code is a bit hard to read because of the formatting but as @Piyush Ghediya answered you can use sum with a group by clause.
SELECT 'Core' as Core, Z.EventName, Sum(ISNULL(DIFF,0)) AS DIFF
FROM (select distinct MacID, EventName from dbo.tblMachine a
join (SELECT DISTINCT EVENTNAME FROM dbo.tblEvtDur)
b on b.EventName <> '' and MacID in ('A06','A07', 'A08', 'A09', 'B01','B05','B09', 'B10', 'B11', 'C04', 'C08', 'C09') )
z LEFT JOIN (SELECT A.MacID, A.EventName, SUM(DATEDIFF(SECOND, A.STARTdt, A.eNDdt))
as diff,round(SUM(DATEDIFF(SECOND, A.STARTdt, A.eNDdt)) / cast(aVG(Tdiff)
as decimal(30,8)),4) * 100 AS PER FROM dbo.tblEvtDur  A
LEFT JOIN ( SELECT macid, SUM(DATEDIFF(SECOND, STARTdt, eNDdt)) as Tdiff
FROM  dbo.tblEvtDur  WHERE DayID between '20180401' and '20180430'
GROUP BY MacID ) B ON  A.MacID = B.MacID
WHERE DayID between '20180401' and '20180430'
AND A.MacID in
 ('A06','A07', 'A08', 'A09', 'B01','B05','B09', 'B10', 'B11', 'C04', 'C08', 'C09')
group by A.MacID, A.EventName) a
ON A.EVENTNAME = Z.EVENTNAME  and Z.MacID  = a.MacID order by Z.MacID, Z.EventName
Group by Core, Eventname

A: You need something like this, as you need all the required values with sum and condition in single query.

DECLARE @tbl TABLE(name VARCHAR(50), quantity INT, saledate DATE)
INSERT INTO @tbl(name, quantity, saledate)
VALUES('A', 20, '2018-05-31'), ('B', 50, '2018-05-25'), ('c', 40, '2018-05-20'), ('a', 40, '2018-05-10'), ('d', 20, '2018-05-15'), ('c', 20, '2018-05-20')
SELECT a.name, SUM(CASE WHEN a.saledate > '2018-05-15'
  THEN a.quantity ELSE 0 END)
FROM @tbl a
WHERE(a.saledate > '2018-05-15'
  OR a.name in ('a', 'b', 'c', 'd')) GROUP BY a.name

A: Finally found a solution to the issue, all I had to do was remove MacID from the select functions and declare the EventName:
SELECT 'Core' as Core, Z.EventName, ISNULL(DIFF,0) AS DIFF FROM
(select distinct EventName from dbo.tblMachine a

join
(SELECT DISTINCT EVENTNAME FROM dbo.tblEvtDur) b
on b.EventName <> '' and eventname in ('BLK', 'MDL', 'MTL', 'OFF', 'RPR', 'RUN')
and MacID in ('A06','A07', 'A08', 'A09', 'B01','B05','B09', 'B10', 'B11', 'C04', 'C08', 'C09')) Z

LEFT JOIN (SELECT A.EventName, SUM(DATEDIFF(SECOND, A.STARTdt, A.eNDdt)) as diff,
round(SUM(DATEDIFF(SECOND, A.STARTdt, A.eNDdt)) / cast(aVG(Tdiff) as decimal(30,8)),4) * 100 AS PER
FROM dbo.tblEvtDur  A

LEFT JOIN ( SELECT EVENTNAME, SUM(DATEDIFF(SECOND, STARTdt, eNDdt)) as Tdiff
FROM dbo.tblEvtDur  WHERE DayID between '20180401' and '20180430' GROUP BY EVENTNAME ) B
ON  A.EVENTNAME = B.EVENTNAME

WHERE DayID between '20180401' and '20180430'
AND A.MacID in ('A06','A07', 'A08', 'A09', 'B01','B05','B09', 'B10', 'B11', 'C04', 'C08', 'C09')
and A.eventname in ('BLK', 'MDL', 'MTL', 'OFF', 'RPR', 'RUN')
group by A.EventName) a ON A.EVENTNAME = Z.EVENTNAME and Z.EVENTNAME  = a.EVENTNAME order by  Z.EventName


text:
Q: How to record/verify method calls in unit tests without mocks? How can I write expectations in my unit tests ?
Here is an example:
defmodule MyAPIModule do
  @url "http://example.com/path"

  def get_something(http_module \\ HTTPoison) do
    http_module.get!(@url, [], [])
  end
end

Here is my test:
defmodule MyAPIModuleTest do
  use ExUnit.Case

  test "Runs the get! method with no headers and no params" do
    MyAPIModule.get_something(HttpSpy)
    # 1) assert that get! was called
    # 2) assert [] == headers
    # 3) assert [] == params
    # 4) assert "http://example.com/path" == url
  end
end

defmodule HttpSpy do
  def get!(url, headers, params) do
    #
  end
end

My problem is immutability. I can't simply create a list in the HttpSpy module and record method calls with their params into that list.
So I tried to change HttpSpy this way:
defmodule HttpSpy do
  def start(listener) do
    spawn_link(__MODULE__, loop, [listener])
  end

  def loop(listener) do
    receive do

    end
  end

  def get!(url, headers, params) do

  end
end

and I changed the test to:
test "Runs the get! method with no headers and no params"
  spy = HttpSpy.start(self)
  MyAPIModule.get_something(HttpSpy)
  receive do
    {^spy, method_call} -> flunk("wrong method call")
    after 1000 -> flunk("timeout")
  end
end

but I'm stuck. HttpSpy.get! does not know the PID of the HttpSpy process spawned by the test.
Therefore HttpSpy.get! cannot send a message to the process which is waiting in the loop method.
Therefore the loop method will never send to the test (which I call listener) the function called and its params.
I realize that what I want is basically mock and expectations but I'd like to find the idiomatic way (= no mocks) to do it.

A: Patrick gave a great answer and that would be my first approach. However, if you can't directly access the result returned by the spy, you can just send yourself a message:
# In the spy
send self(), :get_was_called

# In the test
assert_received :get_was_called

A: You could just return the desired values from the fake get! function, extract them and then assert the results. You will implicitly know  that the correct function was called, because it returns the expected result.
defmodule FakeHttp do
  def get!(url, headers, params) do
    {:get!, url, headers, params}
  end
end

defmodule MyAPIModuleTest do
  use ExUnit.Case

  test "Runs the get! method with no headers and no params" do
    {:get!, url, headers, params} =
      MyAPIModule.get_something(FakeHttp)

    assert [] == headers
    assert [] == params
    assert "http://example.com/path" == url
  end
end

Anyway, I think it is not the most important thing to assert that a particular function was called. I think it is more useful to just do assertions on the externally visible result. That way, you can swap out the underlying implementations and your tests will still pass, as long as the new implementation produces the same result.


text:
Q: Android : contradiction between 2 HttpUrlConnection im new android developer and i will try the best to explein my problem
 i have 2 activies
they both have listview's that use the same custom Adapter
each acitvity has her own url for server requesting.
This is the class where i send the url and get back the stream data
public class HTTPDataHandler {

    static String stream = null;

    public HTTPDataHandler(){
    }

    public String GetHTTPData(String urlString){

        Log.v("HTTP handler", "Get HTTP DATA" );

        try{
            URL url = new URL(urlString);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            // Check the connection status
            if(urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK)
            {
                // if response code = 200 ok
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());

                // Read the BufferedInputStream
                BufferedReader r = new BufferedReader(new InputStreamReader(in));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = r.readLine()) != null) {
                    sb.append(line);
                }
                stream = sb.toString();
                // End reading...............

                // Disconnect the HttpURLConnection
                urlConnection.disconnect();
            }
            else
            {

                // Do something
                Log.v("HTTP handler", "Not connected or got wrong data" );
            }
        }catch (MalformedURLException e){
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }finally {

        }
        // Return the data from specified url
        return stream;
    }
}

My first activity works fine and the listew shows with no problems
but in my second activity i put the right url but it returns me the stream of the first acitvity.
i debbuged that and i saw that in the part of
 if(urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK)

i got else, and it returns me the first acitvity data instead of the data in activity 2 url.
What can cause it?
is it related to my "static String stream"?
im sorry for the bad english
and thank you for the help.

A: edit 2:From your comments, the 505 error reads:

505 HTTP Version Not Supported
The server does not support, or refuses to support, the HTTP protocol version that was used in the request message. The server is indicating that it is unable or unwilling to complete the request using the same major version as the client, as described in section 3.1, other than with this error message. The response SHOULD contain an entity describing why that version is not supported and what other protocols are supported by that server.

edit:You should save the Adapter or any related data yourself locally (I do believe HTTP Urlconnection does this) or some sort of cache, then read repeatedly from that cache, and only update the repository on a pattern, such as a time difference, timeout, cache-control or a default personnal directive.

Note that internet usually costs money. Save it, and your user will be happier.
Original
Please, check code 304 here; that reads:

304 Not Modified
If the client has performed a conditional GET request and access is allowed, but the document has not been modified, the server SHOULD respond with this status code. The 304 response MUST NOT contain a message-body, and thus is always terminated by the first empty line after the header fields.


text:
Q: How to deploy image to kubernetes with jib and maven I have environment where I can simply push images(created with Jib) to local repository. I want to now to be able to deploy this on kubernetes, but from the "safety" of maven.
I know I can spin some Skaffold magic, but I don't like to have it installed separately. Is there some Jib-Skaffold workflow I can use to continuously force Skaffold to redeploy on source change(without running it in command line)
Is there some Skaffold plugin? I really like what they have here, but proposed kubernetes-dev-maven-plugin is probably internal only.

A: Skaffold can monitor your local code and detect changes that will trigger a build and deployment in your cluster. This is built-in on Skaffold using the dev mode so it solves the redeploy on source change part.
As for the workflow, Jib is a supported builder for Skaffold so the same dynamic applies.
Although these features automate the tasks, it is still necessary to run it once with skaffold dev and let it run in the "background".


text:
Q: Put a 4 Byte Integer into the first 4 char elements of vector I have a vector<unsigned char> and want to put a 4 byte Integer into the first 4 elements.
Is there a simpler way in C++ than masking like this:
myVector.at(0) = myInt & 0x000000FF;
myVector.at(1) = myInt & 0x0000FF00;
myVector.at(2) = myInt & 0x00FF0000;
myVector.at(3) = myInt & 0xFF000000;

A: You have to binary shift your values for this to work:
myVector.at(0) = (myInt & 0xFF);
myVector.at(1) = (myInt >> 8) & 0xFF;
myVector.at(2) = (myInt >> 16) & 0xFF;
myVector.at(3) = (myInt >> 24) & 0xFF;

Your code is wrong:
int myInt = 0x12345678;
myVector.at(0) = myInt & 0x000000FF; // puts 0x78
myVector.at(1) = myInt & 0x0000FF00; // tries to put 0x5600 but puts 0x00
myVector.at(2) = myInt & 0x00FF0000; // tries to put 0x340000 but puts 0x00
myVector.at(3) = myInt & 0xFF000000; // tries to put 0x12000000 but puts 0x00

A: you can do something similar to the following:
#include <vector>
#include <cstdio>

void
insert_int(std::vector<unsigned char>* container, int integer)
{
    char* chars = reinterpret_cast<char*>(&integer);
    container->insert(container->end(), chars, chars+sizeof(int));
}

int main(void)
{
    std::vector<unsigned char> test_vector;
    int test_int = 0x01020304;

    insert_int(&test_vector, test_int);

    return 0;
}

just remember to account for endieness. My machine prints the int in reverse order.
4,3,2,1

A: A std::vector is guaranteed to be stored as one contiguous block of data(‡). Hence it is possible to treat a std::vector<unsigned char> in basically the same way as an unsigned char buffer. This means, you can memcpy your data into the vector, provided you are sure it is large enough:
#include <vector>
#include <cstring>
#include <cstdint>

int main()
{
  std::int32_t k = 1294323;
  std::vector<unsigned char> charvec;

  if (charvec.size() < sizeof(k))
    charvec.resize(sizeof(k));

  std::memcpy(charvec.data(), &k, sizeof(k));

  return 0;
}

Note: The data() function of std::vector returns a void* to the internal buffer of the vector. It is available in C++11 – in earlier versions it is possible to use the address of the first element of the vector, &charvec[0], instead.
Of course this is a very unusual way of using a std::vector, and (due to the necessary resize()) slightly dangerous. I trust you have good reasons for wanting to do it.

(‡) Or, as the Standard puts it:

(§23.3.6.1/1) [...] The elements of a vector are stored contiguously, meaning that if v is a vector<T, Allocator> where T is some type other than bool, then it obeys the identity
       &v[n] == &v[0] + n for all 0 <= n < v.size().

A: Your solution is incorrect as you currently have it. Something like:
std::vector<unsigned char> v(sizeof(int));
int myInt = 0x12345678;

for(unsigned i = 0; i < sizeof(int); ++i) {
    v[i] = myInt & 0xFF;
    myInt >>= 8;
}

Should work. It's also more portable (doesn't assume int is 4 bytes).

A: Here is the most compact way:
myVector.at(0) = *((char*)&myInt+0);
myVector.at(1) = *((char*)&myInt+1);
myVector.at(2) = *((char*)&myInt+2);
myVector.at(3) = *((char*)&myInt+3);


text:
Q: EF, AddRange, Collection was modified; enumeration operation may not execute Problem: I'm trying to save a list of objects into the database, using the AddRange.
The Setup: I have a database of two tables:
BookTitles:
- Book_Id
- BookName

BookAuthors:
- Author_Id
- AuthorName
- Book_Id

In the BookAuthors table, the "Book_Id" is the Foreign Key from BookTitles table.
I Use Entity Framework, Database First. EF created the models for me, so the model of BookTitles looks like this:
public partial class BookTitles
{
    public BookTitles()
    { this.BookAuthors = new HashSet<BookAuthors>(); }

    public int Book_Id { get; set; }
    public string BookName { get; set; }

    public virtual ICollection<BookAuthors> BookAuthors { get; set; }
}

THE WAY IT WORKS: If i use this function to add one Book record (which will contain a list of BookAuthors) to the database, it works fine. And the Function below will add one record to the BookTitles table, and thwo record to the BookAuthors table. Here I use the "Add" method:
private static void InsertBook()
{
    using (var db = new BooksContext())
    {
        var authors = new List<BookAuthors>()
        {
            new BookAuthors() {AuthorName = "Author 1"},
            new BookAuthors() {AuthorName = "Author 2"}
        };

        var book = new BookTitles {BookName = "Book1", BookAuthors = authors};

        db.BookTitles.Add(book);
        db.SaveChanges();
     }
 }

THE WAY IT DOESN'T WORK: If i try to add a list of Books to the database, using the AddRange(), it will throw an error "Collection was modified; enumeration operation may not execute":
private static void AddRangeOfBooks()
{
    using (var db = new BooksContext())
    {
        var listOfAuthors = new List<BookAuthors>
        {
            new BookAuthors() {AuthorName = "Author1"},
            new BookAuthors() {AuthorName = "Author2"}
        };

        var listOfBooks = new List<BookTitles>
        {
            new BookTitles() {BookName = "Book 1", BookAuthors = listOfAuthors},
            new BookTitles() {BookName = "Book 2", BookAuthors = listOfAuthors}
        };

        db.BookTitles.AddRange(listOfBooks);
        db.SaveChanges();
    }
}

Why it throws the error? Why does it work with Add() method (adding a single record) and doesn't work with AddRange() (adding a range of records)?

A: You can not use the same collection in different entities, try:
var listOfBooks = new List<BookTitles>
{
    new BookTitles() {BookName = "Book 1", BookAuthors = listOfAuthors},
    new BookTitles() {BookName = "Book 2", BookAuthors = listOfAuthors.ToList()}
};

The important part is the ToList(). I have faced some similar issue and i think this have to solve the problem becouse EF using hashset to keep tracking of every objects as well as collection. If you put the same collection into different entities the framework will not know where it belongs.


text:
Q: Count the number of items with a condition in MongoDB collection I can't figure out what I'm doing wrong with my query. I want to get the number of "alertes" with the field "resolved: false" so my query is :
Alertes.find({resolved: false}).count();

But it returns me 0 despite I have 1 entry in the collection with the field resolved: false
Somone could help me to figure out what I'm doing wrong ?

A: I had forgot to subscribe to the collection in my IronRouter file :
Router.route('/', {
  name: 'home',
  waitOn: function() {
    return [
      Meteor.subscribe('infosContainers'),
      Meteor.subscribe('infosMachines'),
      Meteor.subscribe('alertes'),
    ];
  },
  fastRender: true,
});

Thank you for the help

A: Did you try this?
Alertes.find({resolved: false}).fecth().length

If you are running this code at the client side, make sure you have subscribed to this collection, and that you have documents that satisfy the filter you are looking for.
Try to query all documents (with no filter) to make sure the documents are there with the query above, and check what you get back:
Alertes.find().fecth()

If you don't find any documents with the resolved property set to false, then the query is returning correctly, and the problem is your subscription.


text:
Q: FFmpeg - Split video multiple parts I read the following thread, and the solution works if I want to split a video into pieces every two minutes: Split video file into pieces with ffmpeg
The problem is that I want to split a video into pieces every 15 seconds.
When I use the following command:
for i in {00..49}
 do ffmpeg -i fff.avi -sameq -ss 00:$[ i*2 ]:00 -t 00:00:15 output_$i.avi
done

it will output 15-second video sequences, but not in order. It will skip parts of the video, so I end up with a few 15 second clips, but not all the clips. I want to be able to use ffmpeg to split any video I throw at it into many pieces based on the time I give it.

A: I found the answer. It turns out I was having problems because I didn't have the proper FFmpeg installed, but a fork of ffmpeg.
This code works for me:
ffmpeg -i fff.avi -acodec copy -f segment -segment_time 10 -vcodec copy -reset_timestamps 1 -map 0 fff%d.avi

fff.avi is the name of the source clip. Change -segment_time 10 to the general duration you want for each segment. If you want each clip to be about 40 seconds, then use -segment_time 40. Use -an after -map 0 if you don't want the resulting clips to have sound.


text:
Q: check number of dots in file and append string in the same line after hello guys im trying to figure this out but im completly stuck.
i have a text file. this text file contains as IP's.
file:
host 192.168.12.1 <- missing the subnetmask

now what i want to solve is. that the programm read the lines and detects the combination between characters and numbers and should attach the subnetmask after the ip the "255. 255. 255. 255"
I know you can solve the problem with regex, but I'm so lost I know not at all how to start.
result in txt file should be:
host 192.168.12.1 255.255.255.255

my try:
import re

with open("test.txt","r") as f:
    lines = f.readlines()
with open("test.txt","r") as f:
    for line in lines:
        match = re.match(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}", line)
        if match:
            f.append(" 255.255.255.255") <- should write in same LINE
            print("yey")
        else:
           pass

A: You can concatenate string like this:
a = "Hello"
b = "World"
c = a + " " + b
print(c)

In your case :
if match:
            line  + " " + "255.255.255.255"
            print("yey")
        else:
           pass

A: Use re.findall and rstrip()
import re

with open("test.txt","r") as f:
    lines = f.readlines()
with open("test1.txt","w") as f:
    for line in lines:
        f.write(line.rstrip())
        matches = re.findall(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}", line)
        if len(matches) == 1:
            f.write(" 255.255.255.255")
        f.write("\n")


text:
Q: Can I install OSX 10.11 El Capitan on a 2016 MacBook Pro touch? I can't imagine this would be an issue, but is there any reason why I can't/shoudln't install OSX 10.11 Yosemite on my MacBook Pro 2016? Sierra has always felt very sluggish to me, and it is the first OSX release where apps consistently crash. El Capitan was much more solid in my opinion and I would like to downgrade. Is there any reason why I shouldn't?

A: No you can't install El Capitan.
The firmware won't allow any version of macOS earlier than macOS Sierra 10.12.1 (16B2657) to be installed.
Also, for future reference, if this model ever needs a firmware update, it is possible that the earliest version of macOS you will be able to install in future will be a version later than macOS 10.12.1.


text:
Q: Code not working for dismissing Keyboard I am trying to create code for dismissing the Keyboard when touching outside the keyboard or when pressing the return button. But it is ofcourse not working :D That is why I am asking here. How can I make it work? It doesn't give an error but it is just not responding.
If there are simpler solution, then that is also welcome to provide.
Thank you for your time and answer!
Here is my full code:
import UIKit

class EntryViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var UserEmailAdresInput: UITextField!

    @IBOutlet weak var UserPasswordInput: UITextField!

    @IBOutlet weak var UserPasswordInputRepeated: UITextField!

    @IBOutlet weak var UserSignUp: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.UserEmailAdresInput.delegate = self
        self.UserPasswordInput.delegate = self
        self.UserPasswordInputRepeated.delegate = self

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    @IBAction func SignUp(_ sender: Any) {

        let UserEmail = UserEmailAdresInput.text;
        let UserPassword = UserPasswordInput.text;
        let UserPasswordRepeated = UserPasswordInputRepeated.text;

        //Hide Keyboard upon Touch

        func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?){
            self.view.endEditing(true)
        }

        //Hide Keyboard upon Return Key
        func textFieldShouldReturn(textField: UITextField) -> Bool {
            UserEmailAdresInput.resignFirstResponder()
            return (true)

        }

        //Check if fields are filled in correctly

        if(UserEmail?.isEmpty == true || UserPassword?.isEmpty == true || UserPasswordRepeated?.isEmpty == true){

            displayAlertMessage(userMessage: "Alle velden moeten ingevuld worden");
            return;

        }

        if(UserPassword != UserPasswordRepeated){

            displayAlertMessage(userMessage: "Wachtwoorden zijn niet gelijk");
            return;
        }

        //Store Data
        UserDefaults.standard.set(UserEmail, forKey: "UserEmail");
        UserDefaults.standard.set(UserPassword, forKey: "UserPassword");
        UserDefaults.standard.synchronize();

        //SignUp Succesfull
        var Alert = UIAlertController(title:"Succesvol aangemeld!", message: "Ga naar je email inbox om je aanmelding te voltooien", preferredStyle: UIAlertControllerStyle.alert);

        let OkAction = UIAlertAction(title:"Ok", style: UIAlertActionStyle.default, handler: nil);

        Alert.addAction(OkAction);
        self.present(Alert, animated: true, completion: nil)

    }

    func displayAlertMessage(userMessage:String){

        var Alert = UIAlertController(title:"Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.alert);

        let OkAction = UIAlertAction(title:"Ok", style: UIAlertActionStyle.default, handler: nil);

        Alert.addAction(OkAction);

        self.present(Alert, animated: true, completion: nil)

    }

}

A: Below UITextField Delegate method will use to resign your textfield on press on return button on keyboard.
func textFieldShouldReturn(textField: UITextField) -> Bool {
            if textField == UserEmailAdresInput{
                 UserEmailAdresInput.resignFirstResponder()
            } else if textField == UserPasswordInput{
                 UserPasswordInput.resignFirstResponder()
            } else {
                 UserPasswordInputRepeated.resignFirstResponder()
            }
            return true
   }

and put your touchesBegan and textFieldShouldReturn method outside the signUp Method.


text:
Q: strcat concat a char onto a string? Using GDB, I find I get a segmentation fault when I attempt this operation:
strcat(string,&currentChar);

Given that string is initialized as
char * string = "";

and currentChar is
char currentChar = 'B';

Why does this result in a segmentation fault?
If strcat can't be used for this, how else can I concat a char onto a string?

A: I think the simplest method (not efficient) would be sprintf
sprintf(str, "%s%c", str, chr);

A: strcat() takes two '\0'-terminated strings. When you pass the address of a character, the routine will look at the memory that follows the character, looking for the terminator.
Since you don't know what that memory even refers to, you should expect problems when your code accesses it.
In addition to that, your string argument does not have room to have any characters appended to it. Where is that memory written to? It will attempt to write past the end of the memory associated with this string.

A: As responded by others, &currentChar is a pointer to char or char*, but a string in C is char[] or const char*.
One way to use strcat to concatenate a char to string is creating a minimum string and use it to transform a char into string.
Example:
Making a simple string, with only 1 character and the suffix '\0';
char cToStr[2];
cToStr[1] = '\0';

Applying to your question:
char * string = "";
char currentChar = 'B';

cToStr will assume the string "B":
cToStr[0] = currentChar;

And strcat will work!
strcat ( string, cToStr );

A: Because &currentChar is not a string, it doesn't finish with \0 character. You should define B as char *currentChar = 'B';. Also according to http://www.cplusplus.com/reference/clibrary/cstring/strcat string should have enough space to hold the result string (2 bytes in this case), but it is only 1 byte.
Or if you want to use char then you can do something like (depending of your code):
char string[256];
...

char currentChar = 'B';
size_t cur_len = strlen(string);
if(cur_len < 254) {
    string[cur_len] = currentChar;
    string[cur_len+1] = '\0';
}
else
    printf("Not enough space");

A: Both of the strings must be null-terminated. A single char isn't null terminated, so it's undefined when strcat will stop concatenating characters to the end. Also, string must contain at least enough space for both the original string and resultant string.
This works:
char string[10] = "";
char* currentChar = "B";
strcat(string, currentChar);

A: We know that currentChar = 'B'.
This can be done
strcat(string, "B\0");

If we know currentChar will be hardcoded as 'B', this would be a good approach.
It also removes the need for char currentChar = 'B';

A: The first argument of strcat must have enough space to hold the rest of the string. "" is a constant string and as such GCC does not allocate space.
Make it an array with enough space:
char buf[1024];

strcat(buf, "");
strcat(buf, "B");


text:
Q: Creating and running executable by hand Just for interest sake, I want to compile and run the simplest C program by hand;
//t.c

int main() {
       return 0;
}

So I want to do:

*

*$ cpp t.c : should do nothing in this case, since no preprocessing to be done

*$ cc1 t.c : should compile t.c -> t.s

*$ as -o t.o t.c : should assembe t.s -> t.o

*$ ld t.o : should produce executable a.out (nothing really to be done)

The problem I'm having is with as, since running the final command yields:
ld: warning: cannot find entry symbol _start; defaulting to 00000000000400b0

What's going on? I purposly left out libc to keep this as simple as possible, but I don't understand what's happening. What flags am I missing?

A: There's a bit more to loading and executing a program. As you can guess from the linker output, execution starts not at main, but at _start, which is provided by the CRT (C runtime) library that is bundled with the compiler and gets linked with your code behind the scene.
Here and here are some overviews of what's going on at program startup on Linux.
Do cc -v -Wall on your dummy source to see all the required steps in detail.

A: Since you said simplest program, here is a real hack.
This is for Ubuntu 12.04, running x86_64. If you have something else, then this might give you a hint what to do.
mkdir hack_code
cd hack_code
cp /usr/lib/ldscripts/elf_x86_64.x ldsimple.x

Now modify ldsimple.x to say ENTRY(main) instead of ENTRY(_start) in the beginning.
Create this mymain.c:
int main(void)
{
    __asm__ __volatile__ (
        "movq $60, %rax\n"  /* call sys_exit */
        "movq $2,  %rdi\n"  /* return code   */
        "syscall"           /* call kernel to exit program */
    );
    return 0;
}

And then:
gcc -c mymain.c
ld -o mymain -T./ldsimple.x mymain.o

Voila: You now have got a program which does not use any library etc.


text:
Q: Alterar TextView com evento na ListView Gostaria de alterar o valor total sempre q um item for alterado...
Class que faz a soma:
public class Somar {

    private List<Carrinho_Item> lista;
    private double total = 0;

    public Somar(List<Carrinho_Item> lista) {
        this.lista = lista;

        for (int i = 0; i < lista.size(); i++){

            this.total = total + lista.get(i).getPreco() * lista.get(i).getQuantidade();

        }
    }

    public double getTotal() {
        return total;
    }

}

Activity principal (Funções relevante):
public void AdicionarProduto(final List<Produto> list, Cores cor_final, String tamanho_final, String quantidade, List<Cores> cores, int total_pedido) {
        contador++;
        carrinho_item.add(new Carrinho_Item(list.get(contador).getIdProduto(), list.get(contador).getDescricao(), list.get(contador).getCodigoProduto(), cor_final.getCor(), cor_final.getPreco(), cor_final.getIdVariacao(), tamanho_final, Integer.parseInt(quantidade), contador));
        listView.setAdapter(new ProdutoAdapter(Carrinho.this, R.layout.list_carrinho, carrinho_item, cores));

        SomarTotal();

    }

public void SomarTotal(){
    Somar soma = new Somar(carrinho_item);

    total.setText("R$: "+soma.getTotal());
}

Evento da Lista que deve alterar TextView da Activity:
 public View getView(final int pos, View convertView, ViewGroup parent) {
        final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View rowView2 = inflater.inflate(R.layout.activity_carrinho, parent, false);

        final TextView txtTotal = (TextView) rowView2.findViewById(R.id.total);

        rowView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder alert = new AlertDialog.Builder(getContext());

                alert.setTitle("Edição do pedido")
                        .setCancelable(false)
                        .setIcon(R.drawable.ic_editar)
                        .setView(viewDialog)
                        .setPositiveButton("Editar pedido", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                item.get(pos).setQuantidade(Integer.parseInt(txtQuantidade.getText().toString()));
                                Somar soma = new Somar(item);
                                txtTotal.setText("R$: "+ soma.getTotal());
                                notifyDataSetChanged();
                            }
                        })
                        .setNegativeButton("Voltar", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        })
                        .show();

            }
        });

        return rowView;
    }

A: Declarar
Runnable run;

No seu onCreate
 run = new Runnable() {
     public void run() {

         adapter.notifyDataSetChanged();
         listView.invalidateViews();
         listView.refreshDrawableState();
     }
 };

Após alteração da lista
runOnUiThread(run);

ou, se estiver em um fragmento
getActivity().runOnUiThread(run);

A: Utilize uma interface e faça sua Activity observar a mudança.
public interface Observer {
   void onChange(Soma soma);
}

Depois faça sua Activity implementar a interface Observer e passe uma referência para a ListView via construtor ou método setter.
Tendo uma referência do "observador", emita o evento quando a mudança acontecer chamando onChange()
Observer listener;

/*...*/

public void setObserver(Observer listener) {
   this.listener = listener;
}

/*...*/

public void LocalOndeOcorreAmudanca() {
    listener.onChange(soma); // Emita o evento passando como parâmetro a soma
}

Agora na Activity, sobrescreva o método onChange e atualize o TextView
@Override
public void onChange(Soma soma) {
   tvTotalSoma.setText(String.valueOf(soma.getTotal()));
}

Esse é um pseudo padrão Observer, porém deve funcionar. É o terceiro problema que proponho essa solução. Espero que ajude, abraço!


text:
Q: Core data objects actions from buttons In my app I am showing core data objects, in this case it is a Tasks Manager.
I have included a swip gesture to the rows, when the user swipes from left to right, an UIView is shown at the right side of the screen, like in the following picture:

This is the code for the handleGestureLeftRight method:
-(void)handleGestureLeftRight:(UIGestureRecognizer *)gec
{
    {

        CGPoint p = [gec locationInView:self.tableView];

        NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:p];

        if (gec.state == UIGestureRecognizerStateEnded) {

            NSLog(@"GESTURE LEFT-->RIGHT DONE");

          //BUTTONS AND LABELS DEFINITIONS ARE NOT SHOWN TO AVOID LONG CODE HERE

        }

    }
}

I would need your help on how to implement core data actions when the user taps on the buttons on the right side. As example, if the user taps on the Done button, the selected row object, should change the value of an attribute called isDone. The same should happen tapping to the other buttons, but a different attribute value should be changed.
Thank you.

A: When you add the buttons to your table view in handleGestureLeftRight:, save
the selected index path in a property:
CGPoint p = [gec locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:p];
self.currentIndexPath = indexPath;

Then, in the button action methods, you can access the corresponding Core Data object
with
YourEntity *object = [self.fetchedResultsController objectAtIndexPath:self.currentIndexPath];

and update its properties. When removing the the buttons, set
self.currentIndexPath = nil;


text:
Q: Permission denied in push or clone from cPanel remote After Add Repository in cPanel and add remote with under command :
git remote add origin ssh://user@domain.com:3031/home/user/book
And use :
git push origin master
Enter ssh password
I get error message Permission denied, please try again.

A: These possibilities are there:

*

*Remote repository does not have write permissions.

*You are providing a wrong password or if you are trying ssh with public and private key    combination, they are not matching.

*Please open git bash and do "ssh -vvv user@domain.com:3031" and try to debug the verbose logs.


text:
Q: Custom multivaluefield isn't displayed in empty form I'm trying to build a custom multivaluewidget in my django app.
Widget
class DayInputWidget(MultiWidget):
    def __init__(self, attrs=None):
        widgets = (DayInput(day_name='Mo'), DayInput(day_name='Di'), DayInput(day_name='Mi'), DayInput(day_name='Do'), DayInput(day_name='Fr'))
        super(DayInputWidget, self).__init__(widgets, attrs)

    def decompress(self, value):
        print value
        if value:
            return value
        return None

Input
class DayInput(Input):
    input_type = 'text'
    def __init__(self,attrs=None,day_name=None):
        super(DayInput, self).__init__(attrs)
        self.day_name = day_name

    def render(self, name, value, attrs=None):
        if name is None:
            name = 'Bestellmenge_%s' % self.day_name
        # create day inputs
        return mark_safe(u'<label style="padding-left: 5px">%s</label><input type="text" name="%s" size="5px"  value="0"/> ' % (self.day_name,name))

field
class DayInputField(forms.MultiValueField):
    widget = DayInputWidget

    def __init__(self, *args, **kwargs):
        fields = (forms.CharField(),forms.CharField(),forms.CharField(),forms.CharField(), forms.CharField())
        super(DayInputField, self).__init__(fields, *args, **kwargs)

    def compress(self, data_list):
        print data_list
        if data_list:
            return u'|'.join(data_list)
        return None

form
class OrderForm(forms.Form):
    Produktart = forms.ModelChoiceField(MProductTypes.objects.all())
    Kw = forms.CharField(widget=KwSelect(), required=False)
    Bestellmengen = fields.DayInputField()

Problem: The form is only shown when it is bound to data. If I init the form with empty data, the validation tooks place and it will be displayed. What am doing wrong here?
I initialise my form this way
form = OrderForm()

according documentation the form should be displayed empty.

A: Try the following: in your widget class, rewrite your decompress method, so that it does not return None, but []:
class DayInputWidget(MultiWidget):
def __init__(self, attrs=None):
    widgets = (DayInput(day_name='Mo'), DayInput(day_name='Di'), DayInput(day_name='Mi'), DayInput(day_name='Do'), DayInput(day_name='Fr'))
    super(DayInputWidget, self).__init__(widgets, attrs)

def decompress(self, value):
    print value
    if value:
        return value
    return []

This was suggested in this SO answer and it helped me with a similar case.


text:
Q: How to allow access to ECR repo from multiple companies AWS Accounts to pull from private ECR repo of one company I am unsure if this is possible but I have a request to setup a ECR repository that I would like to setup in my company AWS Account and manage to publish the images and helm chart by myself.
But I have partners who also need to pull images and helm chart from this ECR repo, How can I achieve this, Any IAM Insight would help too.