text:
Q: TensorFlow Keras SavedModel throws a TypeError after being saved and loaded twice When I create a Keras model with one or more custom layers, I can use the model.save() method to persist the Keras model using the TensorFlow SavedModel format.
I can load this model from the filesystem using tf.keras.models.load_model() function and save it to the filesystem again.
But when I load the SavedModel from the filesystem a second time, it fails with this exception:
TypeError: f(inputs, training, training, training, training, *, training, training) missing 1 required argument: training

You can try replicating this issue with the following code:
import tensorflow as tf

class CustomLayer(tf.keras.layers.Layer):
    def call(self, inputs, *args, **kwargs):
        return inputs

model1 = tf.keras.Sequential([
    CustomLayer()
])
model1.build((None, 1))
model1.compile()
model1.save("model1")

model2 = tf.keras.models.load_model("model1")
model2.save("model2")

# This line should raise a TypeError.
model3 = tf.keras.models.load_model("model2")

A: Why the problem exists
The problem is that the TensorFlow SavedModel format does not actually serialize custom Python code. It only saves the TensorFlow graph generated by custom Keras layers and other Python objects.
The tf.keras.models.load_model() function--by default--does not return the Python layer. Instead, it returns a placeholder layer containing the same part of the TensorFlow computation graph. We can see this in the example in my question:
>>> model1.layers
[<__main__.CustomLayer at 0x7ff04c14ee20>]

>>> model2.layers
[<keras.saving.saved_model.load.CustomLayer at 0x7ff114fd7be0>]

When model2 is saved and loaded from the filesystem, TensorFlow cannot correctly parse the *args and **kwargs arguments in CustomLayer.call().
I don't know whether the actual bug is within the saving code, the loading code, or both.
The real fix needs to happen within TensorFlow/Keras, but in the meantime, there are
Workarounds
You can choose any ONE of the below workarounds to avoid serialization errors with custom Keras layers.
Change the signature on Layer.call()
Currently, the official method signature on Layer.call() is def call(self, inputs, *args, **kwargs):
But TensorFlow will throw a TypeError when trying to load a model with a custom layer with this signature. To fix the error, write all of your custom layers with a signature of def call(self, inputs):. If your layer behaves differently during training or inference, then you can use the method signature def call(self, inputs, training=None):
This makes it easier for TensorFlow to generate placeholder layers generated in the keras.saving.saved_model.load module. But this placeholder layer is still not exactly the same as the original Python code.
Use the custom_objects parameter on tf.keras.models.load_model()
It is possible to load a model with its original Python layers instead of the placeholder layers. Just pass a dictionary mapping layer names to Python layer class objects. This requires your code to be able to import the original Python layer. The example in my question can be fixed as follows:
model3 = tf.keras.models.load_model(
    "model2",
    custom_objects=dict(
        CustomLayer=CustomLayer,
    ),
)

Make sure that your layer implements Layer.get_config() and returns a dictionary with all of the parameters needed to recreate the layer from scratch. The layer must be able to be recreated with Layer.from_config().
Import the Python layer and add it to Keras's global registry
Keras maintains a global registry of custom Python classes and other objects to refer to when loading SavedModels. You can register your custom Keras layer with the @tf.keras.utils.register_keras_serializable() decorator. For example:
@tf.keras.utils.register_keras_serializable(
   package="my_python_package"
)
class CustomLayer(tf.keras.layers.Layer):
    def call(self, inputs, *args, **kwargs):
        return inputs

This method also requires that your layer properly implement Layer.get_config().
Install the Python layer object with tf.keras.utils.custom_object_scope()
Much like the above two solutions, the tf.keras.utils.custom_object_scope() context manager can specify which custom layers to use when deserialization.


text:
Q: VS Code is now asking if I want to run the file normally or to run it in terminal The thing is that, it never asked me this before, is there a way to fix this? Because clicking 2 times the start button to run the program is a little annoying. Thanks!

A: In VS Code, the green run button provided by the "Python" extension is to execute the command "Run Python File in Terminal". It only requires us to click once to run python files in the Terminal of VS Code:

If you also use other extensions, such as: "Code Runner", the run button ("Run Code") provided by it defaults to output results in "OUTPUT". In the previous use, this button will cover the green button provided by the "python" extension, but now that they are integrated, we can choose the execution method.
You could use F5 to debug the code or try to close the "Code Runner" extension. (Click "Enable" to restore the use of the extension.)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Removing whitespace between HTML elements when using line breaks I have a page with a row of about 10 imgs. For readability of the HTML, I want to put a linebreak in between each img tag, but doing so renders whitespace between the images, which I do not want. Is there anything I can do other than break in the middle of the tags rather than between them?
Edit: Here is a screenshot of what I have so far. I would like the book spine images to display in random combinations, using PHP. This is why I need separate img tags.

A: You could use comments.

I'd worry about the semantics of having a series of images side by side though.

A: You could use CSS. Setting display:block, or float:left on the images will let you have define your own spacing and format the HTML however you want but will affect the layout in ways that might or might not be appropriate.
Otherwise you are dealing with inline content so the HTML formatting is important - as the images will effectively act like words.

A: Use CSS stylesheet for solving this problem like the following code.
[divContainer_Id] img
{
    display:block;
    float:left;
    border:0;
}

alt text http://rabu4g.bay.livefilestore.com/y1pWoAOBMiLumd2iQTAreYjQCDIkHImh2g_b2g9k4AnxtDNrCjvzL6bK7skG8QKMRNWkMG7N8e5Xm7pgle3tdRJd2y08CnnoPLy/Capture.PNG
Testing on Firefox 3.5 Final!
PS. your html should like this.

A: Flexbox can easily fix this old problem:
.image-wrapper {
  display: flex;
}

More information about flexbox:
https://css-tricks.com/snippets/css/a-guide-to-flexbox/

A: You have two options without doing approximate stuff with CSS. The first option is to use javascript to remove whitespace-only children from tags. A nicer option though is to use the fact that whitespace can exist inside tags without it having a meaning. Like so:

A:
Is there anything I can do other than break in the middle of the tags rather than between them?

Not really. Since s are inline elements, spaces between these elements are considered by the HTML renderer as true spaces in text – redundant spaces (and line breaks) will be truncated but single spaces will be inserted into the character data of the text element.
Positioning the  tags absolutely can prevent this but I'd advise against this since this would mean positioning each of the images manually to some pixel measure which can be a lot of work.

A: Another solution would be to use unconventional line breaks in places of spaces. This is similar to the first couple answers, and is an alternative way of lining up elements. It also is a super-edge-optimization technique because it replaces spaces in your markup with carriage returns.

Note that there are no spaces in any of that code. Places where spaces are normally used in HTML are replaced with carriage returns. It's less verbose than both using comments and using whitespace like Paul de Vrieze recommended.
Credit to tech.co for this approach.

A: white-space: initial; Works for me.

A: Sorry if this is old but I just found a solution.
Try setting the font-size to 0. Thus the white-spaces in between the images will be 0 in width, and the images won't be affected.
Don't know if this works in all browsers, but I tried it with Chromium and some
 elements with display: inline-block;.

A: After way too much research, trial and error I found a way that seems to works fine and doesn't require to manually re-set the font size  manually on the children elements, allowing me to have a standardized em font size across the whole doc.
In Firefox this is fairly simple, just set word-spacing: -1em on the parent element. For some reason, Chrome ignore this (and as far as I tested, it ignores the word spacing regardless of the value). So besides this I add letter-spacing: -.31em to the parent and letter-spacing: normal to the children. This fraction of an em is the size of the space ONLY IF your em size is standardized. Firefox, in turn, ignores negative values for letter-spacing, so it won't add it to the word spacing.
I tested this on Firefox 13 (win/ubuntu, 14 on android), Google Chrome 20 (win/ubuntu), Android Browser on ICS 4.0.4 and IE 9. And I'm tempted to say this may also work on Safari, but I don't really know...
Here's a demo http://jsbin.com/acucam

A: I'm too late (i just asked a question and find thin in related section) but i think display:table-cell; is a better solution

the only problem is it will not work on IE 7 and Earlier versions but thats fixable with a hack

A: Inspired by Quentin's answer, you can also place the closing > next to the start of the next tag.

A: The whitespace between the elements is only put there by the HTML editor for visual formatting purposes.  You can use jQuery to remove the whitespace:
$("div#MyImages").each(function () {

    var div = $(this);
    var children= div.children();
    children.detach();
    div.empty();
    div.append(children);

});

This detaches the child elements, clears any whitespace that remains before adding the child elements back again.
Unlike the other answers to this question, using this method ensures that the inherited css display and font-size values are maintained.  There's also no need to use float and the cumbersome clear that is then required.  Of course, you will need to be using jQuery.

A: Personally I like the accepted answer stating there is no exact way of doing this, not with out using a trick of some form.
To me, it is an annoying issue with at times can make you waste an hour wondering why a row of check boxes for example are not all aligned correctly.. Hence i had to have a quick google and myself check if there was a css rule that i have not remembered... but seems no :(
As for the next best answer, of using font-size... to me this is a nasty hack that will bite you later on wondering why your text is not showing.
I generally develop a lot with PHP and in the case of where i am generating a grid of check boxes, the PHP generated content removes this problem as it does not insert any spacing/breaks.
Simply, i would suggest either having to deal with the images all being on a single line together or using a server side script to generate the content/images.

A: Instead of using  to remove a CR/LF between elements, I use the SGML processing instruction  because minifiers often remove the comments, but not the XML PI. When the PHP PI is processed by PHP, it has the additional benefit of removing the PI completely along with the CR/LF in between, thus saving at least 8 bytes. You can use any arbitrary valid instruction name such as  and save two bytes in X(HT)ML.

A: Semantically speaking, wouldn't it be best to use an ordered or unordered list and then style it appropriately using CSS?

Using CSS, you'll be able to style this whatever way you want and remove the whitespace imbetween the books.


text:
Q: building empty filter driver with vs 2015 and wdk 10 fails I couldn't imagine, just how hard it can be for me to start building a sample minifilter driver using vs 2015 and wdk 10!
I've had 2013 running on my pc, then received a swapbuffer sample configured for 8.1. I simply installed WDK 8.1 from Microsoft and that's all. it compiled.
But when I tried to build a minifilter driver using wdk10 everything got hard as hell.
everything is done as this guy said in here and I am on a virtual machine running windows 10.
after installation and that and that and repairing this and that ... when I create an empty fsfilter driver project using vs sample project, build fails with this error:
"An SDK corresponding to WDK version '8.1' was not found. Please install the SDK before building."
This error refers to the file windowsDriver.common.targets in tis line:
<Error Text="An SDK corresponding to WDK version '$(TargetPlatformVersion)' was not found. Please install the SDK before building."
       Condition="'$(MatchingSdkPresent)' != 'true'" />

can somebody give me a hint on how to solve this issue?!
thanks.

A: Windows 10 WDK requires matching SDK version to be installed. Looks like the default for the project you created is falling back to 8.1.
In the project properties, look for Configuration Properties -> General -> "Target Platform version" drop down and select the 10.0.10XXX.0 and try to build it.
If you have installed the latest version of WDK(10.0.105860.0) then make sure the corresponding SDK is installed too. You can check this in the VS installer to see if "Tools (1.2) and Windows 10 SDK (10.0.10586)" under "Universal Windows App Development Tools" is selected.

A: UPDATE
After much mucking about it turns out that the WDK is not enough; you also need to install the latest Windows 10 SDK which does not by default get installed or updated with Visual Studio. I thought it did, (I've got VS2015, Update 3) but clearly it doesn't. I got the latest version from https://developer.microsoft.com/en-us/windows/downloads/windows-10-sdk
, retargeted my project to the latest version (at the time of writing that is 10.0.14393.0), and both the 10 year old sample and the VS wizzard generated projects now work (at least the small sample I've tried.)


text:
Q: Laravel mail localhost it's working fine on godaddy server it giving Connection could not be established with host smtp.gmail.com error I am trying to make a contact form using laravel mail. It works fine on localhost but, when I host it on godaddy share hosting I returns me an error: Swift_TransportException Connection could not be established with host smtp.gmail.com [Connection refused #111],am tried all the methods which are available in stackoverflow but their is no luck.

A: You have to configure your google account to accept connexions from your host :
In your Google Email Account > Google Account .
On My Account Page click on Security and scroll down to the bottom you will find Less secure app access settings .
Click on the radio button to set it ON.

A: Though you tagged this question with PHPMailer, you're not using it. The problem you have is very well known - GoDaddy blocks outbound SMTP. There is nothing you can do to your script or server to make it talk to gmail. I recommend switching to a proper hosting provider that does not block essential services.


text:
Q: Spring cloud stream kafka and Feign client result in consume message repeat In my project, I use spring-cloud-stream-kafka, and @StreamListener received Message, When  processing this message I used FeignClient to call another service.
but I didn't call that service without exception, and I received the same message again.


text:
Q: Dropdown going off to the out of the Header for RTL I have used below jQuery code for stop dropdown going off to the out of the Header. and It is working fine in normal LTR version.
but, I want to solution for RTL version. How can i do it?
jQuery
$('.primary-menu .dropdown-menu').each(function() {
        var menu = $('#header .header-row').offset();
        var dropdown = $(this).parent().offset();

        var i = (dropdown.left + $(this).outerWidth()) - (menu.left + $('#header .header-row').outerWidth());

        if (i > 0) {
            $(this).css('margin-left', '-' + (i) + 'px');
        }
    });

HTML

 .....

Link

Link 2

 Pages

                    ........

I have try below something But, This is not working
$('.primary-menu .dropdown-menu').each(function() {
        var menu = $('#header .header-row').offset();
        var dropdown = $(this).parent().offset();

        var i = (dropdown.right + $(this).outerWidth()) - (menu.right + $('#header .header-row').outerWidth());

        if (i > 0) {
            $(this).css('margin-right', '-' + (i) + 'px');
        }
    });

A: The right offset is: window's width - ( element left offset + element outer width)
So, I have find final solution:
$('.primary-menu .dropdown-menu').each(function() {
    var menu = $('#header .header-row').offset();
    var dropdown = $(this).parent().offset();

    var rightMenu = ($(window).width() - (menu.left + $('#header .header-row').outerWidth()));
    var rightDropdown = ($(window).width() - (dropdown.left + $(this).parent().outerWidth()));

    var i = (rightDropdown + $(this).outerWidth()) - (rightMenu + $('#header .header-row').outerWidth());

    if (i > 0) {
        $(this).css('margin-right', '-' + (i) + 'px');
    }
});


text:
Q: On the degree of irrationality of two irrational numbers and their rational (in)dependence Let $x$ and $y$ be some irrational numbers. If the degree of irrationality of $x$ is the same as that of $y$, is it necessarily the case that $x$ and $y$ are rationally dependent ?
ADDENDUM: What if $x$ and $y$ are transcendental, specifically logarithms of some rational numbers ?


text:
Q: 5 random numbers. How does if(arr.indexOf(randnum) > -1) continue; prevent duplication? I am creating an array with 5 random numbers that do not duplicate for the power-ball. I understand most of this block but I am still a noob and I don't fully understand how the if(arr.indexOf(randnum) > -1) continue;  prevents duplication.
Any explanation would be much appreciated.
let arr = [];
while(arr.length < 5){
    let randnum = Math.floor(Math.random() * 69) + 1;
    if(arr.indexOf(randnum)> -1) continue;
    arr[arr.length] = randnum;
}
console.log(arr);

A: arr.indexOf(randnum) finds the index of the number "randnum" in the array "arr":
For example [2,5,7,11,6].indexOf(7) == 2 because the number 7 is in the second position.
it returns -1 when the number is not found: [2,5,7,11,6].indexOf(8) == -1
Checking if it is greater than -1 is actually a check whether "randnum" is in the array "arr".

A: so, basically
array.indexOf --> if the element exists, it will return it's index, if not it will return -1.
continue means, ignore the rest of the code inside the loop and start another iteration in the loop.
if(arr.indexOf(randnum)> -1) continue;  means, if index of element is greater that -1, which means element has been found, then continue, means don't execute that line
arr[arr.length] = randnum;

A: A good way to break apart the function to better understand how it works is to set a lower range of possible values. In the example below, the values 1-5 are possible. If you run the snippet below, you will be able to see when duplicate values are detected.
arr.indexOf(randnum) > -1 detects if the value for randnum exists within the array. When a value exists in the array, a value greater than -1 is returned by the function. Otherwise, -1 is returned to indicate that it does not exist in the array.
If the above evaluates to true, continue will execute, which skips arr[arr.length] = randnum;, which is responsible for adding the new number to the array.

let arr = [];
while (arr.length < 5) {
  let randnum = Math.floor(Math.random() * 5) + 1;
  if (arr.indexOf(randnum) > -1) {
    console.log("Duplicate detected: " + randnum);
    console.log("Current array values: " + arr);
    continue;
  }
  arr[arr.length] = randnum;
}
console.log(arr);


text:
Q: one column value cannot be greater than another column value in Jtable of java swing I have 4 columns JTable using Default table model, i am populating two column's from DB, and user have to fill the purchase price and sale price in jTable , i wanna make sale Price cannot be greater than Mrp Please Help me..

A: In what problem? Can you show any relative code? Any way I recomend you write your custom table model extends DefaultTableModel (http://docs.oracle.com/javase/1.5.0/docs/api/javax/swing/table/DefaultTableModel.html), it's more flexible.


text:
Q: My web page doesn't resize for small devices properly http://codepen.io/IrvingG/pen/adqaXg
The URL above is my portfolio which I'm working with through FreeCodeCamp there you can see my code for HTML and CSS. I am having difficulties with how the page is viewed through small devices. The pages get smaller but the contents disappear underneath. When I view the page on a desktop it looks how I want for now but not on a mobile. I'm not sure what to do with contact section but it's not my main concern. I would like some help or ideas on how to fix my page or what I did wrong for it to behave that way. Thank you so much in advanced.

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
          Toggle navigation

        </button>
        Irving Gonzalez

Home

About

Projects

Contact

Portfolio

Projects

About

            Hi there! My name is Irving Gonzalez and I am a Computer Science student at John Jay College of Criminal Justice. Currently, I am working towards becoming a Full Stack Web Developer with the help of the curriculum from freeCodeCamp            as well as other self-taught web services. I have a passion for innovation, deviation, technology, and languages.

 Below are some of the projects I've completed.

Works

Random Quotes

Basic Calculator

Future Project

Future Project

Future Project

Future Project

GET IN TOUCH

Do you have any questions, comments, or simply want to say Hello?

Send me a message through the social media above.

I'll be more than happy to help you!

          <address>
  Irving Gonzalez

 1234 MadeUp place

  New York, NY 10040

   (123) 456-7890

   Irv.jgonz@gmail.com
</address>

@ 2016 Irving Gonzalez

#about{
  color: #404040;
}

#aboutimage{
  box-shadow: 5px 5px 20px grey;
}

#aboutMe{
  background-color: #f2f2f2;
  padding:15px;
  border:rounded;
}

#workThumbnails{
    box-shadow: 5px 5px 20px grey;
}

#slide2 .container{
  position: relative;
  right: 50px;
  font-weight:bold;
}

#slide4 .row a{
  /*This changes the color of the links do not delete*/
  color: inherit;
  text-decoration: none;
}

/* this is for the navbar links on the bottom in case i want to switch it.
.navbar .container a{
  color: inherit;
  text-decoration: none;
  padding-left: 20px;
}
*/

.jumbotron {
  background: url("http://i64.tinypic.com/33nvoft.jpg") 50% 0 no-repeat fixed;
  color: #fff;
  height: 670px;
  padding: 200px 0 260px 0;
  background-size: cover;
}

#slide2 {
  background-color: #fff;
  color: #333333;
  height: 600px;
  margin: 20px;
  overflow: hidden;
  padding: 0px;
}

#slide3 {
  background-color: #fff;
  color: #333333;
  height: 700px;
  padding: 20px;
    overflow: hidden;
}

#slide4 {
  background: url("http://i66.tinypic.com/x6eyw.jpg") 50% 0 no-repeat fixed;
  height: 550px;
  margin: 0 auto;
  padding-top:25px;
  color: #fff;
  background-size: cover;
}

A: Use this CSS
#slide3 {
  background-color: #fff;
  color: #333333;
  height: 100%;
  padding: 20px;
    overflow: hidden;
}

This will extend your main content slide to the height of the available window.

A: When you gradually reduce the width of the window I can see part of the text in the "About" section is being overlapped. Try adding this to your CSS.
#slide2 div.container div.row
{
  margin-left:50px;
}

A: Your content is dissapearing because you set the slides to have a height and then set the overflow to hidden.  So the contents are not dissapearing beneath anything they are being cut off at the height that you set your slides.

A: You have used too many column grid classes that are really unnecessary here mate. All you need is to use .col-md-6 on both sections below the projects slide i.e, in #slide2. Also, remove the padding-right and padding-left properties from the .container class in #slide2. Use similar edits for the rest of the page. Hope this helps.


text:
Q: creating hidden files using .NET How can I create or mark a file as hidden using .NET?

A: I assume you are referring to setting the file attribute to hidden in the file system.
Please take a look at this link

A: If it's an existing file, i.e. not one you've just created, don't just:
File.SetAttributes(path, FileAttributes.Hidden);

or certain other attributes it may have will be lost, so rather you should:
File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.Hidden);

A: Use File.SetAttributes.  "Hidden" is just one of many available attributes.

A: You set the hidden attribute of the file.
There are several ways of doing so - with File.SetAttributes or FileInfo.Attributes, you simply set the FileAttributes enumeration flag to hidden:
string path = @"c:\myfile.txt";
File.SetAttributes(path, FileAttributes.Hidden);


text:
Q: Google APIs - removing auth scope I'm changing scopes in an app for Google Classroom. I remove from courses .readonly and added student listing
var SCOPES = "https://www.googleapis.com/auth/classroom.courses https://www.googleapis.com/auth/classroom.coursework.students";

I get this error when requesting students even after logging out and attempting to re-authenticate:

Request had insufficient authentication scopes

It seems the token has been cached somewhere.
This Github issue, although for Google Sheets, says the token is in Documents/.credentials/ folder. I don't have this folder though on my Macbook Pro Sierra 10.12.6.
Where can I find that folder and remove the saved scopes so it reauthenticates and accepts my new scopes?

A: If you change the scopes needed in your application then the user will need to authenticate your application. especially if you go from a read-only scope to a read write scope.  This is because you need additional permissions then what you had originally requested.  List of google classroom scopes
Assuming that you are using the Google .net client library then you can find the user credentials in the %appdata% folder on your machine.  By deleting that fine you can force a authentication.  I am guessing that you are since this is the github project you have linked to.
Note: there should be a way of forcing reauth via code but i cant remember the command right now i will have to look it up.


text:
Q: TrippleBuffering disables laptop monitor I've got Asus Rog Strix Scar 15 with i912900h and rtx 3070ti. I installed Fedora Silverblue 36 along with asus linux. I was trying to fix the tearing issue. The Force Composition Pipeline trick doesn't work for me since the mouse lag is unbearable for me. Though I found another solution which proposes to enable TrippleBuffer. It seems to me that it is working fine. But there is a small issue: system doesn't see the laptop monitor as if it doesn't exist.
I use 510.68.02 nvidia driver.
Xorg configs:
$ ls -la /etc/X11/xorg.conf.d
total 12
drwxr-xr-x. 1 root root 120 тра 10 22:51 .
drwxr-xr-x. 1 root root 118 тра 10 22:49 ..
-rw-r--r--. 1 root root 311 тра  3 22:25 00-keyboard.conf
-rw-r--r--. 1 root root 264 тра 10 23:28 90-nvidia-primary.conf
-rw-r--r--. 1 root root 105 тра 10 23:33 95-tripple-buffer.conf

90-nvidia-primary.conf:
# Automatically generated by supergfxd
Section "OutputClass"
    Identifier "nvidia"
    MatchDriver "nvidia-drm"
    Driver "nvidia"
    Option "AllowEmptyInitialConfiguration" "true"
    Option "AllowExternalGpus" "true"
    Option "PrimaryGPU" "true"
EndSection

95-tripple-buffer.conf (created by me):
Section "Device"
    Identifier "nvidia"
    Driver "nvidia"
    Option "TripleBuffer" "True"
EndSection

How can I restore the laptop monitor?


text:
Q: After re-compiling the kernel, my grub stop after the bios After recompiling my kernel, I copied the corresponding files to /boot, and my /boot directory looks like:

Then, I inserted a new item in grub, and /boot/grub/menu.lst now looks like:

After searching a lot, I found that someone mentions that maybe ACPI settings matter. So, I set ACPI to off. But it still does not work.
When I reboot my OS, it still stops, like this:

As you can see, I have another grub item, grub-ide. And if I choose it, I can successfully log into it.
How can I get my system to boot with my new kernel?

A: The problem was nothing with the setting, but was about my own design of the kernel. After revising some of the bug, the kernel can be booted successfully:


text:
Q: How to give a point when answer is correct with javascript I have a (small) problem, I tried looking on the internet, but can't find the answer. I'm new with javascript.
HTML:
    <form name="examen">
     <input type="radio" id="1a" name="1" value="">Answer 1
</input>
     <input type="radio" id="1b" name="1" value="">Answer 2
</input>
     <input type="radio" id="1c" name="1" value="">Answer 3
</input>
     <input type="radio" id="1d" name="1" value="">Answer 4
</input>
     <input type="button" name="knop" value="Bereken" onClick="calculatie()">
    </form>

JAVASCRIPT:
 function calculatie() {
  var calc = "Aantal vragen goed: ";
  var totaal = parseInt(0);
     if(document.examen.1c.checked){totaal += parseInt(1);}
  calc += Math.round(totaal);
   alert(calc);
  }

Now, when a user is clicking on answer 3, the total points need to be one. But it is saying NaN, I can't get it right. The code needs to be in JAVASCRIPT/HTML. I can't use PHP.

A: try this function ...
function calculatie() {
  var calc = "Aantal vragen goed: ";
  var totaal = 0;
     if(document.getElementById('1c').checked == true){
         totaal += 1;}
       calc += Math.round(totaal);
       console.log(calc); //see console log for output or use it as u want
  }

HERE is the fiddle

A: Here is your js code:
function calculatie() {

   var calc = "Aantal vragen goed: ";
   var totaal = 0;
   if(document.getElementById("1c").checked){totaal += 1;}
   alert(totaal);
  };

document.getElementById("1c") returns true or false,weather "Answer 3" is checked or not and in case it is checked adds 1 to "totaal" variable.


text:
Q: Taking a git branch from one repo into another repo I have 2 repos: repoA and repoB.
repoA contains scripts that are required by project under repoB.
I created a branch under repoA called repoA_usedinB.
I would like to pull repoA_usedinB to be under repoB- develop it while repoB project is active and then merge it back to repoA/repoA_usedinB for future use.

A: First, make sure repoA_usedinB is an actual branch (git switch -c), and not a subfolder.
You could add repoA as a submodule of repoB, with repoA_usedinB branch, with git submodule add -b
cd /path/to/repo/B
git submodule add -b repoA_usedinB /url/of/repoA

Any subsequent git submodule update --remote in repoB will update the repoA subfolder with the latest of that branch.
From the repoA subfolder, you can add, commit and push (to repoA in repoA_usedinB branch)
Don't forget to also add, commit and push in the parent repo repoB.


text:
Q: How to recognize a left to right swipe motion? If I am trying to recognize a swipe motion of of left then right or left to right. Would I need to use a UISwipeGestureRecognizer with a UISwipeGestureRecognizerDirectionLeft direction then dynamically add another UISwipeGestureRecognizer with a UISwipeGestureRecognizerDirectionRight direction?
Then when the user lifts their fingers I remove the gesture recognizer with UISwipeGestureRecognizerDirectionRight direction?

A: If I'm understanding you correctly and you just want to detect a left to right gesture you only have to use UISwipeGestureRecognizerDirectionRight. Here's an example:
UISwipeGestureRecognizer *swipeLeftToRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(myMethod:)];
[swipeLeftToRight setDirection:UISwipeGestureRecognizerDirectionRight];
[swipeLeftToRight setDelegate:self];
[someView addGestureRecognizer:swipeLeftToRight];


text:
Q: problem in authenticated rooms in socket.io I want to create rooms for all private chats between two connected users. I'm not getting the point how do users join the room securely.
// client side code
var socket = io.connect();
socket
    .emit('Join-Room',"{\"username\": \"myusername\", \"password\" : \"mypassword\"}");

// server side code
io.sockets.on('connection', function(socket) {
  socket.on('Join-Room', function(userdata) {
   connection.auth(userdata,function(success){
     if(success){
       socket.join(username);
     }
   })
  });
});

The problem is when the client emits a request even to join a room the credential data is received by everyone in the namespace?
What should I change to make this secure?


text:
Q: find word in not commented code vb.net using regex in notepad++ how can I use search for a word but not in commented text, for example i need to find lines contains datatable but not proceeded by single quote
property xxx as datatable
proptery xxx as object 'datatable adasdasdas
'dim x as datatable
dim x as datatable = new xxxx

the search result should highlight these lines, as they contains word datatable and its not proceeded by single quote
property xxx as datatable
dim x as datatable = new xxxx
thanks

A: ^([^']*datatable.*?)$

Have a look at the DEMO

A: Try this: ((?<!')datatable)
It uses a negative look behind, and should work, as Notepad uses PCRE regex.
See here for the example.
For the entire line, what about this?
.*((?<!')datatable).*
See here for the example

A: To find the line with datatable which is actually a comment and not followed by = new xxx use the following regex.
Regex: (?=.*datatable(?!\s+=\s+new\s+.*))'.*$
Explanation:

*

*(?=.*datatable(?!\s+=\s+new\s+.*)) The nesting of negative lookahead inside positive lookahead is done t avoid = new xxx part followed by datatable.

*'.*$ Matches the rest of comment till end of line.
Regex101 Demo
Notepad++ Demo


text:
Q: Voicemail calling back 20 seconds later I'm trying to set up voicemail for a Twilio # (Not Twilio Cell)...  And it works, for the most part, except I get called back 20 seconds later with nothing there (Step 5 Below).  I think my issues are in TWIML 1/2 from testing, but I don't know.

*

*I'll call in to my Twilo # from my cell.

*I hit the reject on my cell (Even though my time out is 1, it doesn't give up.).

*Leave the message

*Hang up || press button to end

*[~20 seconds after step 4] Get blank call back

*[10-15 secs after step 5] Get my text / email as expected

Am I doing something wrong in TWIML 2?
or
Is using my cell for orig/term causing problems?
Incoming:
TWIML 1:
<?xml version="1.0" encoding="UTF-8"?>
<Response>
  <Dial action="https://-->TWIML 2"
   timeout="1"
   callerId="{{To}}"
  >
    <Number>##CELL##</Number>
  </Dial>
</Response>

TWIML 2:
<?xml version="1.0" encoding="UTF-8"?>
  <Response>
    <Say>
      Please leave a message
    </Say>
      <Record action="https://TWIML 3"
        method="POST"
        maxLength="120"
        playBeep="false"
        trim="do-not-trim"
        transcribe="true"
        transcribeCallback="https://FUNCTION 1"
      />
    <Say>I did not receive a recording.</Say>
</Response>

TWIML 3
<?xml version="1.0" encoding="UTF-8"?>
<Response>
  <Say>Bi</Say>
</Response>

FUNCTION 1
exports.handler = function(context, event, callback) {
var client = context.getTwilioClient();
const mailgun = require('mailgun-js')({apiKey: context.MG_KEY, domain:context.MG_DOMAIN});
var async = require('async');

 var sendSMS = function(callback){
   let dataSMS = {
            to: '##CELL##',
          from: event.To,
          body: 'Voicemail from:\n ' + event.From + '\n\nText:\n' + event.TranscriptionText + '\n\n---MSG Recording---\n' + event.RecordingUrl
   };
   client.messages.create(dataSMS).then(function(response){
     console.log('N [T1]: ' + response.status);
     return callback(null, response);
   }).catch(function(err){
     console.log('T2: ' + err);
   });
 };

 var sendEmail = function(callback){
   let dataMG = {
            to: '@@TO@@',
          from: '@@FROM@@',
       subject: 'Voicemail: ' + event.From,
          text: event.TranscriptionText + '\n\n--- MSG Recording --->\n' + event.RecordingUrl
     };
   console.log('-------- Sending Mail (Mailgun API)---->' + dataMG.to);
   mailgun.messages().send(dataMG, function (error, body) {
     console.log('N [MB] Mailgun Body :' + body);
     return callback(null, body);
   });
 };

 var waitTime = function(callback){
   setTimeout(function() {
     return callback(200);
   }, 1000);
 };

 var asyncTasks = [sendSMS, sendEmail, waitTime];

 async.parallel(asyncTasks, function(err, result){
   console.log('--------------------------DONE--------------------------' + result[0] + result[1]);
   callback(null, 200);
 });
};

Resolved:
So a couple days later and it is working as expected, without being phoned back ~20 seconds later.  I don't think I changed anything, but who knows; now I'm having trouble forcing the unexpected behavior to occur :)
Below is an example of how to set up a voicemail system that will transcribe your message to a MMS including a link to the original voice message.  This also includes an email copy, if you had a mailgun account set up.
There is an extra fee associated with using the transcription service, and you will have to delete the recordings eventually after you no longer want access to the recording.
If you are to try this out, when clean the code for you situation, the timeout variable in Twiml 1 is how many seconds it will ring for.  Function 1 requires async, but you could write it without when tailoring for you situation.


text:
Q: Argument of type 'Element | null' is not assignable to parameter of type 'Element | VirtualElement' Just struggling to understand how to correctly type this as I am getting the following error when trying to use the popper component. The documentation isn't clear and I don't have much Typescript experience.

Argument of type 'Element | null' is not assignable to parameter of type 'Element | VirtualElement'.
Type 'null' is not assignable to type 'Element | VirtualElement'.ts(2345)
const popcorn: Element | null

const popcorn = document.querySelector('#popcorn')
const tooltip = document.querySelector('#tooltip')

createPopper(popcorn, tooltip, {
  placement: 'top',
})

A: The createPopper function wants to make sure popcorn and tooltip are both actually elements. Since querySelector can return null (if no element is present), just check to make sure popcorn and tooltip are not null before calling createPopper on them.
const popcorn = document.querySelector('#popcorn')
const tooltip = document.querySelector('#tooltip')

if (popcorn && tooltip) {
  createPopper(popcorn, tooltip, { placement: 'top' })
}

A: try passing it as
(popcorn as Element)

A: const popcorn = document.querySelector<HTMLDIVElemnt>('#popcorn')
const tooltip = document.querySelector<HTMLDIVElemnt>('#tooltip')

if (popcorn && tooltip) {
  createPopper(popcorn, tooltip, { placement: 'top' })
}

Use <HTMLButtonELement> if the target is a button
This should solve your issue


text:
Q: how appoint a specific windows sdk version for cmake build? I have vs 2017 and   I can set Platform Toolset in IDE:

*

*Visual Studio 2017 - Windows XP (v141_xp)

*Visual Studio 2017 (v141)

*Visual Studio 2015 (v140)

*Visual Studio 2015 - Windows XP (v140_xp)

I want to cmake build many library(opencv,zlib...) ,and want to build two version:

*

*one for xp(Visual Studio 2017 - Windows XP (v141_xp)),

*one for windows 10(Visual Studio 2017 (v141))

of course I can cmake output *.sln and open sln ,set up Platform Toolset,build.... but I want to use cmake --build . automatic build
How can I appoint platform toolset  for cmake?


text:
Q: jquery fadeout div after 5 seconds to end of session Here i need fadeout #not-count div after 5 seconds to end session,
if i fadeout done, after that it will never appear if i reload or move to another, untill the session complete
    jQuery(document).ready(function($){
       $('#notify-comet').on('click', function(e){
            setTimeout(function() {
                $('#not-count').fadeOut('fast');
            }, 1000);
       })
    })

How can i do this using jQuery?

A: You don't need to have two doc ready blocks and you can do this for 5 seconds:
}, 5*1000);

if i fadeout done, after that it will never appear if i reload or move to another, untill the session complete
For this you can make use of cookie or localstorage.


text:
Q: How to split registration and media? I have a SIP project. Where i will have SIP server running.
Server will do following:

*

*will only do routing and receive incoming calls

*But the audio/video will be peer 2 peer

Can this be done with Asterisk? Only the media i have to split but the registration will be with Server.
Tools:
A) server with SIP
B) One PC with SIP client
C) Anoher PC with SIP client

*

*My goal is: B and C gets connected via A and audio/video packets are not via A

A: I believe that is how the SIP protocol works.  The SIP server just sets up the call.  The clients then talk direct to each other.  This Wikipedia article tells you all about it.


text:
Q: Eslint warning due to modules code in source folder After I import a specific module, in this case 'react-select' from http://jedwatson.github.io/react-select/ . My react lint prompts me with a ton of lint warning, for example. The code in the module doesn't pass the lint validation. I made a mistake for having modules code in my source file.
```
Compiled with warnings.
Warning in ./src/~/react-select/lib/index.js
/home/tonyu2/ui/src/node_modules/react-select/lib/index.js
  1:1  warning  'use strict' is unnecessary inside of modules  strict
✖ 1 problem (0 errors, 1 warning)
Warning in ./src/~/react-select/lib/AsyncCreatable.js
/home/tonyu2/ui/src/node_modules/react-select/lib/AsyncCreatable.js
  1:1  warning  'use strict' is unnecessary inside of modules  strict
✖ 1 problem (0 errors, 1 warning)
Warning in ./src/~/react-select/lib/utils/defaultMenuRenderer.js
/home/tonyu2/ui/src/node_modules/react-select/lib/utils/defaultMenuRenderer.js
  1:1  warning  'use strict' is unnecessary inside of modules  strict
✖ 1 problem (0 errors, 1 warning)
You may use special comments to disable some warnings.
Use // eslint-disable-next-line to ignore the next line.
Use /* eslint-disable */ to ignore all warnings in a file.
```
This is annoying because it affect me from catching real important error in my code. I am using the create-react-app library, so that I don't have to deal with the webpack, bundle and httpserver.

A: Have you tried running npm install first and checked your package.json file? That is usually my problem.


text:
Q: automate excel file processing in perl and avoid dialog/UI interactions How can a I guarantee that no pop-up dialogs will appear when I automate Microsoft Excel through OLE? I'm using a Perl module (Win32::OLE). I can avoid most dialog pop-ups using the following code:
use Win32::OLE;
use Win32::OLE::Variant;
use Win32::OLE::Const;

my $excel_symbols = Win32::OLE::Const->Load('Microsoft Excel');
my $excel = Win32::OLE->new('Excel.Application', sub { $_[0]->Quit();} );
$excel->{'Visible'} = 0;
$excel->{'DisplayAlerts'} = 0;
$excel->Workbooks->Open('c:\some_excel_file.xls',
  { 'UpdateLinks' => $excel_symbols->{'xlUpdateLinksNever'},
    'ReadOnly' => 1,
    'IgnoreReadOnlyRecommended' => 1
  });

However for some files, I continue to get a dialog with the following text:

This file is not a recognizable
  format.

*

*If you know the file is from another program which is incompatible with
  Microsoft Excel, click Cancel, then
  open this file in its original
  application. If you want to open the
  file later in Microsoft Excel, save it
  in a format that is compatible, such
  as text format.

*If you suspect the file is damaged, click Help for more information about
  solving the problem.

*If you still want to see what text is contained in the file, Click OK.
  Then click Finish in the Text Import
  Wizard.

  OK Cancel

Sometimes a similar dialog appears that contains 'OK', 'Cancel' and 'Help' buttons.
I cannot control the quality of files that are provided to the scripts.

A: You could consider using Spreadsheet::ParseExcel (albeit it may lack features you need) or Apache POI (albeit it will need some wrapping to use in a Perl script) instead of calling the Excel engine over OLE. That way you won't get any Excel-generated dialogs.

A: I revisited this issue and found a solution.
Copy the file before processing to a temporary location. Then save the file before closing it in Excel:
File::Copy::copy('c:\some_excel_file.xls', 'c:\temp\SFO3jfd.xls');
my $book = $excel->Workbooks->Open('c:\temp\SFO3jfd.xls',
  { 'UpdateLinks' => $excel_symbols->{'xlUpdateLinksNever'},
    'ReadOnly' => 1,
    'IgnoreReadOnlyRecommended' => 1
  });
$book->Save();
$book->Close();

Why this works:
Excel 2003 automatically recalculates the formulas in documents that were created in an older version of Excel. Furthermore, macros could be invoked when the document is opened. All of this means that there could be changes made on a document, even though your script doesn't perform any such operations.
By saving the document before closing, you avoid the dialog requesting that you save the file. Using a temporary file ensures that the original file does not get changed during the validation operation. If you aren't concerned about this, you might consider validating in-place.

A: Here is full documentation for Open method. I wonder if CorruptLoad  parameter is what you need.

A: If you are trying of process all xl files in the tree, some of them may be open by other users and have the ~ prefix.


text:
Q: Estoy intentado validar un usuario y contraseña en jsp de una base de datos y me bota este error?
java.sql.SQLNonTransientConnectionException: Cannot load connection
  class because of underlying exception:
  com.mysql.cj.exceptions.WrongArgumentException: Malformed database
  URL, failed to parse the connection string near '=true&useSSL=false'.

este es el url que uso para crear la conexion:
"jdbc:mysql://localhost:3306/proyecto_jsp?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC?autoReconnect=true&useSSL=false"

A:
jdbc:mysql://localhost:3306/proyecto_jsp?
  useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&
  serverTimezone=UTC?autoReconnect=true&useSSL=false

La URL termina con un interrogante seguido de la lista de parámetros, cada par "nombreParametro=valorParametro" separado por "&"
En tu caso, entre serverTimezone=UTC y autoReconnect=true, no tienes un & sino un ?, que es lo que hace que la URL esté mal formada. Cambia es ? por & y te debería funcionar (o al menos dar otro error no relacionado).


text:
Q: Using Tailwind prose on dark background makes text look too dark Using Tailwind prose on dark background makes text look too dark without manual configuration
TLDR; How do I get prose to work on a dark background?
I have a Site running Sage 10 with Wordpress, where I use TailwindCSS (v3.0.18) for the base styling.
The page is not in dark mode, nor should it be. However I have a Footer, that has a dark background, as is quite common with Websites.
My issue is that the prose class I add to it, will show the text (etc.) quite dark, not really readable. I want to have prose usable on dark backgrounds too. prose-invert doesn't seem to work. I am not sure if it only works with dark:prose-invert?
I could manually change all the elements within the footer, but I would prefer if Tailwind had a way of handling this witout manual labor.
In the image you can see the left part has prose and ends up dark. The right part does not and keeps looking as it should, but is missing the sizes and all the fancy stuff.

My tailwind.conf.js is setup very minimalistic at this point:

const colors = require('tailwindcss/colors')

module.exports = {
  content: [
    // WP default php files
    './index.php',
    './functions.php',
    './author.php',
    './archive.php',
    './home.php',
    './front-page.php',
    './404.php',
    './search.php',
    './category.php',
    './page.php',
    './single.php',
    './taxonomy.php',
    // END WP default php files
    './resources/views/**/*.php',
    './resources/scripts/**/*.js',
  ],
  theme: {
    extend: {
      colors: {
        primary: colors.indigo,
        secondary: colors.yellow,
      },
    },
  },
  plugins: [
    require('@tailwindcss/typography'),
  ],
}

I compile everything with composer into one CSS file, so Tailwind JIT is in use and scans all the correct files as you can see.
Following is a very minimal example of the compiled HTML (removed a lot of stuff, just for demo purposes):

Text

A: In your HTML, where you are declaring the class prose-invert, you need to also use the base class of prose.
So ending up with at least prose prose-invert in your class list.


text:
Q: Installing eqexam package for use with Sublime Text 2 I am looking to utilize the eqexam package, yet even after putting the .sty files in my /usr/local/texlive/2012/texmf-dist/tex/latex directory with the appropriate /eqexam folder . I am still unable to compile the demo file that came with the package. I have included a MWE of the test file below.
I still get the error that eqexam.sty not found. I have searched all over the internet for a solution, but no one seems to be in agreement on the answers.
Running Mac OS X 10.6.8, originally used MacTex distribution with TexLive2012, but am now compiling with ST2 and Skim (which has worked wonders over texshop). I could list my suspicions, but that might be a waste of time. I also understand that this might not be enough information to problematize a solution, but I have hopes.
I suppose that there will not be a solution to this, but might there be better resources than the eqexam documentation and website that can take me through the complexities of the installation?
\documentclass[12pt]{article}
\usepackage{amsmath}
\usepackage{graphicx}
%\usepackage[coverpage,forcolorpaper,pointsonboth,totalsonright]{eqexam}
%\usepackage[forcolorpaper,pointsonleft,nosolutions]{eqexam}
% Note, to use this next line, your exerquiz must be up to date with the eqexam you are using
\usepackage[nosolutions,forcolorpaper,pointsonboth,totalsonright,noparttotals]{eqexam}

\title[T1]{Test 1}
\author{D. P. Story}
\subject[C1]{Calculus I}
\date{Spring \the\year}
\keywords{Test~1, Section 001}

\university
{%
      THE UNIVERSITY OF AKRON\\
    Theoretical and Applied Mathematics
}
\email{dpstory@uakron.edu}

\hfuzz = .7pt

\begin{document}
\maketitle

\begin{exam}[Part I.]{Part1}

\begin{instructions}[Part I.]
Solve each of the problems without error. If you make an error,
points will be subtracted from your total score.
\end{instructions}

\begin{problem}[5]
This is an example of a objective question, the student fills in
his/her response in the space below.

\begin{solution}[.5in]
The solution to the question. This solution will not appear when
the option \texttt{nosolutions} is specified. It will appear
immediately after the question with the \texttt{solutionsafter}
option, and appear at the end of the document if a solutions
option is not specified.
\end{solution}
\end{problem}

\begin{problem}[5]
An example of a fill-in question:
It is well known that \fillin{1in}{Newton} and
\fillin{1in}{Leibniz} are jointly credited as the founders of
modern calculus.

\begin{solution}
It is well known that \underbar{Newton} and \underbar{Leibniz} are
jointly credited as the founders of modern calculus.

\medskip\noindent\textbf{Notes.} Here the optional argument for
the \texttt{solution} environment is not specified, this implies
that no room should be left for the student to answer, seems
reasonable since this is a fill-in.
\end{solution}
\end{problem}

\end{document}


text:
Q: Why does LET not play nice with EVAL in my quine? I was trying to write a Common Lisp quine.  I figured one of the simplest options was as follows:
(let ((program '`(let ((program ',program )
                   (print (eval program)))))
  (print (eval program))))

This does not work, SBCL and CLISP both complain that PROGRAM is unbound.  I did, however, find that using DEFPARAMETER, unlike LET, does work:
(progn
  (defparameter program
                '`(progn
                    (defparameter program
                                  ',program)
                    (print (eval program))))
  (print (eval program)))

For the second example the only difference between the code printed and the code written is the whitespace and capitalization, which I can easily fix.  I still, however, do not understand why my first attempt was not working.   As I see it, the only difference is the scoping of the variable, but it really seems like it shouldn't matter since I'm evaluating program within the scope that contains it.

A: (let ((program '`(let ((program ',program )
                   (print (eval program)))))
  (print (eval program))))

The Common Lisp standard says about eval:

Evaluates form in the current dynamic environment and the null lexical environment.

Since program is a lexical variable, it's not visible to eval.


text:
Q: Rails routing with subdirectories I have "standart" mvc... In layout i'm rendering partial from art_lookups
it look's so:
= form_tag :controller => 'art_lookups', :action => 'search' do
  = text_field_tag :search, params[:search], :pattern=>".{4,24}", :class => "search-input", :placeholder => "Введите код детали"
  = submit_tag "Поиск", :name => nil, :class => "search-submit"

and layout part:
= render :partial => 'art_lookups/search'

All is ok.
But now i'm creating admin part... And i have controller and view in subdirectory admin, and if i try to go to some view in admin, i get error like
No route matches {:controller=>"admin/art_lookups", :action=>"search"}

How to solve it?
Also part of route:
namespace :admin do
    resources :orders
  end

If i comment all in partial, all is ok...
Also when i write in admin/orders/index
= link_to "Редактирование", edit_admin_orders(o)

i get routing error to...

A: Change edit_admin_orders(o) to edit_admin_order_path(o), it will not get routing error.
Updated: Add route for search action
namespace :admin do
  resources :orders do
    collection do
      get 'search'
    end
  end
end


text:
Q: Arduino UNO. Variables not being tested against in if statement I have written some code for a project that sets a motor running in one direction for 6 seconds when the temperature is >= 26 degC to open a vent. when its below 26 degC the motor should run the other direction for 6 seconds to close the vent. After the vent has been opened, the motor should not be able to run that direction again to open it, it should only be able to close after it is opened, not open further. Same goes for the closing. The problem I'm having with my code is the opened function is being set in the code to essentially tell the code that the vent is open, do not try open again. However, when I set up some debug lines, I see the motor still spinning and opened is set to either true/false, depending on the temperature, but its always the wrong value, its set to be opened when the motor has closed the vent, and set to be closed when in face the vent is opened.
#include <Thermistor.h> //Taken from http://garagelab.com/profiles/blogs/tutorial-using-ntc-thermistors-with-arduino

 #define M1A 4
 #define M1B 5

bool opened = false;

Thermistor temp(0);
void setup() {
  Serial.begin(9600);
}
void loop() {
  int temperature = temp.getTemp();
  Serial.print(temperature);
  Serial.println("*C");

  // OPENING///////////////
  if (opened != true and temperature >= 26) {
    digitalWrite(M1A, 1);
    analogWrite(M1B, 0);
    delay(6000);
    digitalWrite(M1A, 0);
    analogWrite(M1B, 0);
    opened = true;
  }

  // CLOSING///////////////
  if (!opened and temperature < 26) {
    digitalWrite(M1A, 0);
    analogWrite(M1B, 255);
    delay(6000);
    digitalWrite(M1A, 0);
    analogWrite(M1B, 0);
    opened = false;
  }

  delay(1000);
  Serial.println(opened);
}

Thanks for anything you might have to say, drop a comment or something if you want to know more.
Craig


text:
Q: How to debug breakpoints in multithreaded applications tested with JUnit? Testing a multithreaded application with JUnit5, the automated tests run just fine.
But in manual debugging, the environment misbehaves, and I would like to know how to get it to act as it should.

IntelliJ (using the Java VM + its debugger) has two general options to suspend on breakpoints: either "All" = all threads, or "Thread" = the current thread only.
(Which thread is "the current thread" may be unclear and causing issues, but that's been discussed separately, see other issues here on stackOverflow.)
Wanted behaviour:

*

*a breakpoint to suspend a specific thread, and the JUnit test environment, which is part of the IDE debugging.

Actual behaviour:

*

*either all threads are suspended, even those which should be running

*or only a single thread is suspended, and JUnit @AfterEach/@AfterAll annotations kill the resources currently debugged, terminating the threads that should be running, etc.

How to achieve the Wanted behaviour?

(Environment: AdoptOpenJDK8, AdoptOpenJDK11 in Java 9 mode, IntelliJ 2020.3, JUnit-Jupiter 5.7.0)

A: You can use two breakpoints. The one you're really interested in and another one in your unit test (somewhere between calling the code under test and cleaning up). Set both to only suspend the current thread.


text:
Q: Parsing commas and quotemarks in degenerate CSV files with Regular Expressions I need to parse strings inputs where the columns are separated by columns and any field that contains a comma in the data is wrapped in quotes (commas separated, quoted text identifiers).  For this project I need to remove the quotes and any commas that occur between pairs of quotes.  Basically, I need to remove commas and quotes that are contained in fields while preserving the commas that are used to separate the fields.  Here's a little code I put together that handles the simple scenario:
// Sample input 1: This works and covers 99% of the records that I need to parse.
string str1 = "an_email_address@somewhere.com,2010/03/27 12:2:02,,some_first_name,some_last_name,,\"This Address Works, Suite 200\",Some City,TN,09876-5432,9795551212x123,XYZ";
str1 = Regex.Replace(str1, "\"([^\"^,]*),([^\"^,]*)\"", "$1$2");
Console.WriteLine(str1);
// Outputs: an_email_address@somewhere.com,2010/03/27 12:2:02,,some_first_name,some_last_name,,This Address Works Suite 200,Some City,TN,09876-5432,9795551212x123,XYZ

Although this code works for most of my records, it doesn't work when a field contains more than one comma.  What I would like to do is modify the code so that it remove each instance of a comma contained within the column no matter how many commas there are in the field.  I don't want to hard code only handling 2 commas, or 3 commas, or 25 commas.  The code should just remove all the commas in the field.  Below is an example of what my code doesn't handle properly.
// Sample input 2: This doesn't work since there is more than 1 comma between the quotes.
string str2 = "an_email_address@somewhere.com,2010/03/27 12:2:02,,some_first_name,some_last_name,,\"i,l,k,e, c,o,m,m,a,s, i,n ,m,y, f,i,e,l,d\",Some City,TN,09876-5432,9795551212x123,XYZ";
str2 = Regex.Replace(str2, "\"([^\"^,]*),([^\"^,]*)\"", "$1$2");
Console.WriteLine(str2);
// Desired output: an_email_address@somewhere.com,2010/03/27 12:2:02,,some_first_name,some_last_name,,i like commas in my field,Some City,TN,09876-5432,9795551212x123,XYZ

How can I accomplish this with regular expressions?

A: Matching quotes and regular expression don't go hand in hand, and you are probably better of using a CSV parser, as Michael Madsen suggested.
However, if you know the quotes only occur as you expect, you can do something like the following:
str2 = Regex.Replace(str2, "\"[^\"]*\"",
                     match => match.Value.Trim('\"').Replace(",", ""));

A: Here's a pure regex version:
str2 = Regex.Replace(str0,
          @"""|,(?=(?>[^""]*""[^""]*(?:""[^""]*""[^""]*)*)$)",
          String.Empty);

It matches any quotation mark, or a comma if it's followed by an odd number of quotation marks, and replaces it with nothing.
I would only go this route if I absolutely had to, for example if I were working with a framework that only let me specify the regex and the replacement string.  Otherwise, I would either go with @Kobi's approach (because it's so much more readable) or use a dedicated CSV processor.  They're not hard to find.


text:
Q: Why are objects created in JS the constructors undefined? So I am pretty new to JavaScript, and I recently stumbled upon the fact that JavaScript has a more modern way of creating classes similar to Java and C#. I thought I consider learning some JavaScript because of this. Right now I am realizing that there are subtle differences between JS and Java/C#, and this issue I now have seems to be one.
Below, I defined a class called Game to act as a global object for a game I am trying to create.
    class Game
    {

        constructor(canvas, ctx)
        {
             this.canvas = canvas;
             this.ctx = ctx;

             this.screenManager = new ScreenManager();
             // initialization of more objects
        }

        run()
        {
            setInterval(function(){
                this.screenManager.updateScreen();
                this.screenManager.drawScreen(this.ctx);
            },15);
        }

    }

The issue I seem to be having is that after I call the constructor within my Game class, this.screenManager is left as undefined. I am noticing that the constructor of my Game class doesn't initialize objects declared in that class.
Now I do know that JavaScript runs code asynchronously, but not really sure if that fact plays into effect. With this said, what is the reasoning behind this declaration error, and what can be done to combat this issue.
PS: If you could try to write JS classes without prototyping, that would most definitely be appreciated! Thanks.


text:
Q: Max-sized array with normal STL interface, similar to boost::array Is there a class in boost similar to array which is a POD-like type with an array but provides for a variable number of items in the container.  That is, I want to say the array has at most 10 items, but may contain from 0 to 10 items at any given moment.
boost::array unfortunately fixes size() to the constant N, so it can't work as a drop in replacement for a vector.  In particular I'd like the readers of the structure not to know it is a static array, they can use begin() and end() like any other container.
Obviously push_back() would have to through an exception if it would grow beyond the capacity.
Something already in boost would be preferred.
NOTE: it must be  a POD-like data type. For clarity, the entire array-like object, included the contents (which will themselves by POD-like types) must be POD-like. This is for serialization/copying reasons (and for performance related to that serialization/copying).
By POD-like I mean:

*

*has compile-time constant size

*can be safely memcpy'd

For those who say it can't work or isn't possible. There is nothing ingenious about this. The boost::array is a POD-like type. All it would take is adding one extra field, for the current size, to make that into what I want. I'm looking for an implementation that already exists (and is thus properly tested/maintained).

A: The problem is (probably) initialization.  How do you initialize
the size, if it is a POD?  How do you enforce the invariant
size() <= max_size?
Technically, it would be easy to define something, but whether
it would be useful or safe is another question.  Why don't you
just use boost::array, and maintain your current size as
a separate variable?
--
James Kanze

A: You say "it must be a POD data type". Your collection does not need to be POD?
If the data type is POD then std::vector provides the functionality you need and many implementation will optimise copy/move semantics where the data is POD.
Why do you need to replace vector?
To answer the question directly though: I doubt there is such a class in boost as vector (maintaining a size) already achieves the purpose and therefore they would consider no real need for it. boost::array does not have a concept of a different size and capacity.
You could easily write your own wrapper class around vector or boost::array to throw if it has exceeded the capacity you set.
Now if you were going to implement this the most likely approach would be a class that contains a vector or a boost array or a regular array and then implement all your functions. I would say that is intuitive but there may be a more clever solution to overload the allocator instead to internally hold a boost::array and use it to make your vector's "allocations". If your allocator runs out of capacity (because its internal array is full) you throw (should probably be bad_alloc). Users then simply use the class as vector and can call all its functions but you will throw if they try to grow the vector higher than its size.
Due to the nature of vector your allocator not be expected to work as a heap where you free certain objects. You will simply be maintaining a contiguous buffer.
With regards to the POD or nearly POD issue, the actual data in the vector is guaranteed to be a contiguous buffer, and internally your allocator is using boost::array so it will be contiguous. If you want something for serialization then boost::serialize will already work with vectors properly.

The whole collection, container and
  contents, must be a single block of
  memory of fixed size: determined at
  compile-time

Your allocator could look like this:
typename< typename T, size_t SIZE >
class Allocator
{
    struct Data
    {
        size_t num_used;
        T[SIZE] data;
    } d;

public:
    // implement allocator's methods
};

Implement these

A: The closer thing I know of would be llvm::SmallVector<T,N> however it's slightly more complicated since it uses dynamically allocated storage when the size grows beyond N (it also copies the existing items, since the storage is guaranteed to be contiguous).
I don't think it would be difficult to realize such a container though, especially using boost::array as a backend. A simple wrapper to maintain the size and move the items around (taking inspiration from the code of vector for example) should be sufficient.

A: POD stand for plain old data.  "A Plain Old Data Structure in C++ is an aggregate class that contains only PODS as members, has no user-defined destructor, no user-defined copy assignment operator, and no nonstatic members of pointer-to-member type." Basically by definition anything that can be resized at runtime cannot be POD.

A: One other alternative (if you cannot be bothered to RYO) is to use boost::optional<T> for the array, for example:
boost::array<boost::optional<int>, 10>

The advantage of the above is that you can test each entry to see if it has been set or not rather than using some value state for uninitialized. This should still allow a direct memcopy of the object (whether it's stack or dynamically allocated).

A: I needed something similar, the motivation was performance, as the cache locality is obviously better than in the dynamically allocated vector.
I created very simple custom class to do this for me.
#pragma once
#include <boost/array.hpp>

template<class T, class IndexType, IndexType MaximumSize>
class StaticVector : public boost::array<T, MaximumSize>
{
  IndexType count;
public:
  StaticVector() : count(0) {}
  inline void add(const T& value)
  {
    if (this->full())
      throw std::runtime_error("Can't add (size = %d)\n", MaximumSize);
    (*this)[this->count] = value;
    this->count++;
  }

  inline void addDirty()
  {
    if (this->full())
      throw std::runtime_error("Can't add, container full.");
    this->count++;
  }

  inline void remove(IndexType index)
  {
    if (this->count > 1)
      (*this)[index] = (*this)[count - 1];
    this->count--;
  }

  inline void clear() { this->count = 0; }
  inline IndexType size() const { return this->count; }
  inline bool empty() const { return this->count == 0; }
  inline bool full() const { return this->count == MaximumSize; }
  inline const T& back() const { return (*this)[this->count - 1]; }
  inline T& back() { return (*this)[this->count - 1]; }

  inline typename boost::array<T, MaximumSize>::iterator  end()       { return this->elems + count; }
  inline typename boost::array<T, MaximumSize>::const_iterator  end() const { return this->elems + count; }
  inline typename boost::array<T, MaximumSize>::const_iterator cend() const { return this->elems + count; }
};


text:
Q: Parsing error after copying new policy files to central store A few months ago we upgrade our DCs from 2008 to 2008 R2.
Two weeks ago I saw that I didn't copy the new admx/adml files to the central store.
Because I want to use the new policies, I copied all local files from one of the DC's %windir%\PolicyDefinitions to the central store.
Today I opened rsop.msc on one of the member servers and got a "parsing error":
**ADML**
Administrative Templates
Encountered an error while parsing.
Expected one of the Following possible element(s), < text >,
< decimalTextBox >, < textBox >, < checkBox >, < comboBox >,
< dropdownList >, < listBox >, but Found < multiTextBox > instead.
File
\\contoso.com\sysvol\contoso. . . TerminalServer-Server.adml, line 198, column 60

**ADMX**
Administrative Templates
Encountered an error while parsing.
Encountered an unknown error while parsing (error = 0x87400001): -2025848831 (0x87400001)
File
\\contoso.com\sysvol\conto. . . \Terminalserver-Server.admx, line 9, column 41

After restore of the old admx/adml it worked without problems.Any ideas, whats wrong with the new admx/adml Templates?
Update 16.01.2012
Could it be possible that the old "2008 SP2" Terminal Servers cannot work with the new (Remote Desktop Services) policies implemented with "2008 R2"?

A: See http://blogs.technet.com/b/askds/archive/2009/12/09/windows-7-windows-server-2008-r2-and-the-group-policy-central-store.aspx as it explains the reason. Was the member server Windows Server 2008?

A: I know this question is old but it helped me get to the correct solution. I solved this problem by ensuring i had the corresponding adml language file in the en-us folder. I would make sure you have the terminalserver.admx in your policydefinitions folder.


text:
Q: 100% Reflective box+Photons If a 100% reflective box/sphere could be made, and introduce light inside the box, what would the box do? Photons have mass and if the box were 100% reflective they could not escape, would this thrust the box in a direction, make it 'leavitate' per-say due to equal forces in all directions, or would the photons have so little mass, it won't Move it or something else?

A:
Photons have mass

Wrong. A photon is an elementary particle of mass zero. This mass is the invariant mass, the length of the four vector

The m0 of the photon is zero and so it has energy and momentum only.
When more than one photon four vector is involved, unless they are completely collinear , there will be an invariant mass, because the addition of the four vectors will have a "length".
Light is composed out of an enormous number of photons, and will have an invariant mass when adding the four vectors, because even in lasing there will be some angle between the individual photon directions.

and if the box were 100% reflective they could not escape, would this thrust the box in a direction, make it 'leavitate' per-say due to equal forces in all directions, or would the photons have so little mass, it won't Move it or something else?

The randomness of scatters on the walls precludes a momentum in a given direction, so there will be no effect on the box, as the total momentum is zero.
There cannot be physically such a box, because the individual photons interacting with the wall surfaces will have a probability of loosing some of their energy/momentum with each scatter on the atoms of the surface  and will slowly be totally absorbed , the ones degrading to infrared radiated as heat, and radio waves escaping


text:
Q: Spartacus Single Step Checkout goes in a loop I am trying to convert our spartacus app to use a single step checkout.  I followed the instructions in https://sap.github.io/spartacus-docs/extending-checkout/.
The following is my app.module.ts configuration:
      routing: {
        routes: {
          checkout: {
            paths: ['checkout'],
          },
          // Add a new route for the combined step
          checkoutSinglePageCheckout: {
            paths: ['checkout/single-page-checkout'],
          },
        },
      },
      checkout: {
        steps: [
          {
            id: 'singleStepCheckout',
            name: 'checkoutProgress.singleStepCheckout',
            routeName: 'checkoutSinglePageCheckout',
            type: [CheckoutStepType.SHIPPING_ADDRESS,
                  CheckoutStepType.DELIVERY_MODE,
                  CheckoutStepType.PAYMENT_DETAILS,
                  CheckoutStepType.REVIEW_ORDER]
          },
        ],
      },

I have omitted the cmscomponents mapping, as I believe that may not be causing this issue.
This is my impex for the single-step-checkout route:
$contentCatalog=electronics-spaContentCatalog
$contentCatalogName=Electronics spa Content Catalog
$contentCV=catalogVersion(CatalogVersion.catalog(Catalog.id[default=$contentCatalog]),CatalogVersion.version[default=Online])[default=$contentCatalog:Online]

INSERT_UPDATE ContentPage;$contentCV[unique=true];uid[unique=true];name;masterTemplate(uid,$contentCV);label;defaultPage[default='true'];approvalStatus(code)[default='approved'];homepage[default='false']
                         ;;CheckoutSingleStepCheckout;Checkout Single Step Checkout Page;MultiStepCheckoutSummaryPageTemplate;/checkout/single-step-checkout

INSERT_UPDATE ContentSlot;$contentCV[unique=true];uid[unique=true];name;cmsComponents(uid, $contentCV)
                         ;;BodyContentSlot-CheckoutSingleStepCheckout;Checkout Single Step Checkout;CheckoutProgressComponent,CheckoutProgressMobileTopComponent,CheckoutShippingAddressComponent,CheckoutDeliveryModeComponent,CheckoutPaymentDetailsComponent,CheckoutProgressMobileBottomComponent
                         ;;SideContentSlot-CheckoutSingleStepCheckout;Order Summary Slot;CheckoutOrderSummaryComponent
INSERT_UPDATE ContentSlotForPage;$contentCV[unique=true];uid[unique=true];position[unique=true];page(uid,$contentCV)[unique=true];contentSlot(uid,$contentCV)[unique=true]
                                ;;BodyContent-CheckoutSingleStepCheckout;BodyContent;CheckoutSingleStepCheckout;BodyContentSlot-CheckoutSingleStepCheckout
                                ;;SideContent-CheckoutSingleStepCheckout;SideContent;CheckoutSingleStepCheckout;SideContentSlot-CheckoutSingleStepCheckout

I am not sure why it exhibits this behavior.

A: I was able to achieve this by using an impex as follows:
INSERT_UPDATE ContentPage;$contentCV[unique=true];uid[unique=true];name;masterTemplate(uid,$contentCV);label;defaultPage[default='true'];approvalStatus(code)[default='approved'];homepage[default='false']
                         ;;CheckoutSinglePageCheckoutDetails;Checkout Single Page Checkout Details Page;MultiStepCheckoutSummaryPageTemplate;/checkout/single-step-checkout

INSERT_UPDATE CMSFlexComponent;$contentCV[unique=true];uid[unique=true];name;flexType
                              ;;CheckoutSinglePageCheckoutDetailsComponent;CheckoutSinglePageCheckoutDetailsComponent;CheckoutSinglePageCheckoutDetails

INSERT_UPDATE ContentSlot;$contentCV[unique=true];uid[unique=true];name;cmsComponents(uid, $contentCV)
                         ;;BodyContentSlot-checkoutSinglePageCheckoutDetails;Checkout Single Page Checkout Details Slot;CheckoutProgressComponent,CheckoutProgressMobileTopComponent,CheckoutSinglePageCheckoutDetailsComponent,CheckoutProgressMobileBottomComponent
                         ;;SideContentSlot-checkoutSinglePageCheckoutDetails;Order Summary Slot;CheckoutOrderSummaryComponent
INSERT_UPDATE ContentSlotForPage;$contentCV[unique=true];uid[unique=true];position[unique=true];page(uid,$contentCV)[unique=true];contentSlot(uid,$contentCV)[unique=true]
                                ;;BodyContent-checkoutSinglePageCheckoutDetails;BodyContent;CheckoutSinglePageCheckoutDetails;BodyContentSlot-checkoutSinglePageCheckoutDetails
                                ;;SideContent-checkoutSinglePageCheckoutDetails;SideContent;CheckoutSinglePageCheckoutDetails;SideContentSlot-checkoutSinglePageCheckoutDetails

Here few things have to be noted:

*

*The Content Page uid must be same as flexType in CMSFlexComponent

*The flexType value (same as content page uid) should not be same as
uid and name in CMSFlexComponent

*I think ContentSlot uid, ContentSlotForPage uid also follows some
naming condition.
Now I can do this configuration change in app.module.ts
      routing: {
        routes: {
          // Add a new route for the combined step
          checkoutSinglePageCheckoutDetails: {
            paths: ['checkout/single-step-checkout'],
          },
        },
      },
      checkout: {
        steps: [

          {
            id: 'singlePageCheckoutDetails',
            name: 'checkoutProgress.singlePageCheckoutDetails', // Provide translation for this key
            routeName: 'checkoutSinglePageCheckoutDetails',
            // This step sets both the delivery mode and the payment details, so you have to define both of these types
            type: [
              CheckoutStepType.SHIPPING_ADDRESS,
              CheckoutStepType.DELIVERY_MODE,
              CheckoutStepType.PAYMENT_DETAILS,
              CheckoutStepType.REVIEW_ORDER,
            ],
          },
        ],
      },

Now in my own single-page-checkout.module.ts, I use the following mapping:
export const singleStepCheckoutConfig = {
  cmsComponents: {
    CheckoutSinglePageCheckoutDetails: {
          component: SingleStepCheckoutComponent
    }
  }
};

@NgModule({
  declarations: [SingleStepCheckoutComponent],
  imports: [
    CommonModule,
    ConfigModule.withConfig(singleStepCheckoutConfig),
  ],
  entryComponents: [SingleStepCheckoutComponent]
})

Now my question is do I have to write all the angular components copying/extending from existing ones.  Mapping existing angular and CMS components don't work.


text:
Q: using 'Unstated' with React Js for fetching data from API endpoint I have already developed an app to fetch weather data from openweathermap.org. The app is built using redux and redux-saga.
Now I have to redo it using "Unstated" instead of Redux for the state management.
The WeatherContainer.js class handles the state:
class WeatherContainer extends Container {
  state = { weather: [] };
  setWeatherData = (weather) => {
    this.setState({ ...this.state, weather });
  };
}

The axios request which gets the data from the API endpoing.
axios.get(process.env.REACT_APP_BASE_URL, {
    params: {
      id: cityIds,
      units: "metric",
      appid: process.env.REACT_APP_API_KEY,
    },
  });

I want to store the data received from axios inside the state.weather variable in WeatherContainer, which then can be used when I needed with .

A: I moved to unstated-next for react js. the same library with react hooks and all. It makes easy to manage state with useState hooks and all the react hooks can be applied as well.
Link to github repo of unstated-next
Since it is a wrapper around the React's context API, the library is light weight and does not need much configurations like redux.


text:
Q: Adding legend to ggplot for forecasts I have a ggplot for the different forecasts I used. Can you please help me add labels for the different forecasts? I pasted a copy of the code and a picture of the current graph. Don't mind the title, caption, and subtitle.
ggplot(Forecast_df, aes(date)) +
  geom_tile(aes(alpha = Recession, y = 1),
            fill = "grey", height = Inf) +
  scale_alpha_continuous(range = c(0, 1), breaks = c(0, 1), labels = c("0" = "Expansion", "1" = "Recession"))+
  geom_line(aes(y = ERVOLY), col = "black", size = .8)+
  geom_line(aes(y = ERVOL_vanilla), col = "blue", size = .8)+
  geom_line(aes(y = ERVOL_twofactor), col = "green", size = .8)+
  geom_line(aes(y = ERVOL_threefactor), col = "orange", size = .8)+
  ylab('Compounded Returns Next 12 Months (%)')+
  labs(x = NULL, alpha = "Economic Cylcle", color = "Economic Variable",
   title = "Rising Inflation Expectations in 2021",
   caption = 'Cleveland Fed Model of 10-year Inflation Expectations',
   subtitle = '"Directionality Matters"')+
  theme(plot.background = element_blank(),
    panel.grid.minor = element_blank(),
    panel.grid.major= element_blank(),
    text = element_text( color = "#003366"))

Here is a subset of the data (I hope this helps):
dput(head(Forecast_df, 10))

structure(list(INFEX = c(5.3755618, 5.2721824, 5.5661154, 5.407864,
5.4896902, 5.1106146, 4.5055244, 4.6342849, 4.5102793, 4.6395631
), ERVOLY = c(NA, -1.0061220776063, -3.28324764731475,
-2.69553459574718,
-0.282378595190325, 0.452399878131127, -1.98818474608972,
-2.02453229878801,
-2.93519956175393, -3.3615903958241), date = structure(c(6695,
6726, 6756, 6787, 6818, 6848, 6879, 6909, 6940, 6971), class =
"Date"),
Expansion = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1), Recession = c(0,
0, 0, 0, 0, 0, 0, 0, 0, 0), ERVOLY_lag1 = c(NA, NA, -1.0061220776063,
-3.28324764731475, -2.69553459574718, -0.282378595190325,
0.452399878131127, -1.98818474608972, -2.02453229878801,
-2.93519956175393), ERVOLY_lag2 = c(NA, NA, NA, -1.0061220776063,
-3.28324764731475, -2.69553459574718, -0.282378595190325,
0.452399878131127, -1.98818474608972, -2.02453229878801),
ERVOL_vanilla = c(NA, NA, NA, 0.177969523019507, 1.0226601086044,
2.95027193254105, 2.8634033844251, 0.549544852368316,
0.594205304832909,
-0.162404463789272), ERVOL_twofactor = c(NA, NA, NA,
0.0942849089685699,
0.91074093410051, 2.85616681306392, 2.81947921688057,
0.512592472075962,
0.537863435836189, -0.222954102109839), ERVOL_threefactor = c(NA,
NA, NA, -0.313401798360953, 0.474416484910883, 2.44479892124736,
2.49154716920072, 0.199652448822007, 0.23023289110162,
-0.537285874249354
), ERVOL_AR2 = c(NA, NA, NA, -3.24926540322977, -2.50081867707103,
-0.136146400989865, 0.424591722149989, -2.06171545794125,
-1.92397323156163, -2.82956410641666), fe_vanilla = c(NA,
NA, NA, -2.87350411876669, -1.30503870379473, -2.49787205440993,
-4.85158813051482, -2.57407715115632, -3.52940486658684,
-3.19918593203483), fe_twofactor = c(NA, NA, NA, -2.78981950471575,
-1.19311952929083, -2.4037669349328, -4.80766396297029,
-2.53712477086397,
-3.47306299759012, -3.13863629371426), fe_threefactor = c(NA,
NA, NA, -2.38213279738623, -0.756795080101207, -1.99239904311623,
-4.47973191529044, -2.22418474761001, -3.16543245285555,
-2.82430452157474), fe_AR2 = c(NA, NA, NA, 0.553730807482581,
2.21844008188071, 0.588546279120992, -2.41277646823971,
0.0371831591532463,
-1.0112263301923, -0.532026289407435)), row.names = c(NA,
10L), class = "data.frame")

A: You can get the result you're looking for using the first method I'll outline here, although arguably a better way would be to first use gather() or pivot_longer() or melt() or reshape() to have a structure more resembling Tidy Data.  However, in the interest of space and time, I'll show the direct way here.
The reason why adding scale_color_manual() to your plot doesn't help is because the scale_* functions only recolor/reshape an existing scale.  Your original plot does not have a scale for color created, so you would be trying to recolor a scale that does not exist.  :)
The only scale your plot created was one for alpha=, and the reason is because you specified that within aes().  This is the "secret" to creating a scale with ggplot2, because the plotting is setup to map an aesthetic attribute to a column in your dataframe.  There are positional aesthetics (like x, y, width, etc..) and then there are graphical aesthetics (like color, fill, alpha, size, etc...).  Positional aesthetics map your data to a location in the plot area, while the graphical aesthetics change the way a geom looks depending on your data.  For graphical aesthetics, a legend is also created.  So, to make a legend appear, you need your graphical aesthetics specified within aes().
Specifying a value in aes() will set the name of the aesthetic in the legend.  Colors are then applied using the default scale... or via another scale you set using a scale_* command.  Here's an example without scale_color_manual():
(Note: had to remove scale_alpha_continous(), since your dput() only has one value for the "Recession" column).
p <- ggplot(Forecast_df, aes(date)) +
  geom_tile(aes(alpha = Recession, y = 1),
            fill = "grey", height = Inf) +
  # scale_alpha_continuous(range = c(0, 1), breaks = c(0, 1), labels = c("Expansion", "Recession"))+
  geom_line(aes(y = ERVOLY, col="ERVOLY"), size = .8)+
  geom_line(aes(y = ERVOL_vanilla, col="Vanilla ERVOL"), size = .8)+
  geom_line(aes(y = ERVOL_twofactor, col="Twofactor ERVOL"), size = .8)+
  geom_line(aes(y = ERVOL_threefactor, col="Threefactor ERVOL"), size = .8)+
  ylab('Compounded Returns Next 12 Months (%)')+
  labs(x = NULL, alpha = "Economic Cylcle", color = "Economic Variable",
       title = "Rising Inflation Expectations in 2021",
       caption = 'Cleveland Fed Model of 10-year Inflation Expectations',
       subtitle = '"Directionality Matters"')+
  theme(plot.background = element_blank(),
        panel.grid.minor = element_blank(),
        panel.grid.major= element_blank(),
        text = element_text( color = "#003366"))
p

You see, a legend is created and the keys are labeled accordingly.  You can then add the colors you want with scale_color_manual():
p + scale_color_manual(values=c(
    "ERVOLY" = "black",
    "Vanilla ERVOL" = "blue",
    "Twofactor ERVOL"="green",
    "Threefactor ERVOL"="orange"))


text:
Q: Using 'grep' and other utilities I know this is a seemingly peculiar question, but I want to have a better understanding of using Linux utilities so I'm going to ask for something that seems rather complicated to me to understand the mechanisms at work better .
Considering all header files in our system, how can I display in the terminal a sorted list  of those files based on the number of defined macros in them ?

A: This should do the trick:
for file in $(find /usr/include/ -name '*.h'); do
  echo "$file,$(grep -c '#define' $file)"; done \
  | sort -n -k2 -t, -r

*

*Find list all files matching /usr/include/*.h pattern

*Print the file name, the comma and the number of lines matching '#define' pattern

*Sort numerically, using a comma as a delimiter by the second field (reverse order).

You can append | head -10 to get the top 10 files.


text:
Q: How to consume a click-event in a Toast-Message? I made a powershell code that shows a toast-message with a "yes/no" option. Now I am looking for a way to handle that click-event properly. See below the code I have so far:
cls
Remove-Variable * -ea 0
$ErrorActionPreference = 'stop'

Add-Type -AssemblyName System.Runtime.WindowsRuntime
$null = [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime]
$null = [Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime]

# now lets define a toast-message:
$toastXml = [Windows.Data.Xml.Dom.XmlDocument]::new()
$xmlString = @"
  <toast launch = "Test1" scenario='alarm'>
    <visual>
      <binding template="ToastGeneric">
        <text>Title</text>
        <text>Message</text>
      </binding>
    </visual>
    <audio src="ms-winsoundevent:Notification.Looping.Alarm" />
    <actions>
        <action content="yes" arguments="yes" />
        <action content="no"  arguments="no"  />
    </actions>
  </toast>
"@
$toastXml.LoadXml($XmlString)
$toast = [Windows.UI.Notifications.ToastNotification]::new($toastXml)
$appId = '{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\WindowsPowerShell\v1.0\powershell.exe'
$notify = [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($appId)
$notify.Show($toast)

Here I need a way to wait for the event, when the users clicks the "yes/no" buttons in the toast (or the "x" to close all). It should work without an external DLL, but using e.g. "add_Activated" and an eventHandler like in this c# code:
https://github.com/david-risney/PoshWinRT/blob/master/PoshWinRT/EventWrapper.cs
I thought it should be similar like for the other cs-Wrapper from that PoshWinRT project, which I could finally convert into this:
# replacement for PoshWinRT - AsyncOperationWrapper:
Add-Type -AssemblyName System.Runtime.WindowsRuntime
$asTaskGeneric = foreach($method in [System.WindowsRuntimeSystemExtensions].GetMethods()) {
    if ($method.name -ne 'AsTask') {continue}
    if ($method.GetParameters().Count -ne 1) {continue}
    if ($method.GetParameters().ParameterType.Name -ne 'IAsyncOperation`1') {continue}
    $method
    break
}

function Await($WinRtTask, $ResultType) {
    $asTask  = $asTaskGeneric.MakeGenericMethod($ResultType)
    $netTask = $asTask.Invoke($null, @($WinRtTask))
    $null    = $netTask.Wait(-1)
    $netTask.Result
}

# sample for async operation:
$null = [Windows.Storage.StorageFile, Windows.Storage, ContentType = WindowsRuntime]
$file = 'c:\windows\notepad.exe'
$info = await ([Windows.Storage.StorageFile]::GetFileFromPathAsync($file)) ([Windows.Storage.StorageFile])
$info

Unfortunately, the coding for that eventWrapper seesm to be a bit more tricky. These are the code-snippets that I could not bring to life, but they may point into the right direction:
$method  = [Windows.UI.Notifications.ToastNotification].GetMethod('add_Activated')
$handler = [Windows.Foundation.TypedEventHandler[Windows.UI.Notifications.ToastNotification,System.Object]]::new($toast, $intPtr1)
$handler = [System.EventHandler]::new($toast, $intPtr2)

Especially the second IntPtr-parameter required for creating an eventHandler confuses me totally.
Any input is more than welcome. Many thanks.


text:
Q: How can I create a tab view programmatically on iOS For an iPhone app how can I create a tab view programmatically, preferably in Objective-C?

A: It's quite simple to create a UITabBar via the UITabBarController. The following example should work within your AppDelegate class.
App Delegate Interface
Firstly, within the interface, we'll define our UITabBarController.
UITabBarController *tabBarController;

App Delegate Implementation
Then, within the implementation file's application:didFinishLaunchingWithOptions: method, we'll then initialise our tab bar controller.
// Initialise our tab bar controller
UITabBarController *tabBarController = [[UITabBarController alloc] init];

Next, you need to create the view controllers that you want to add to the tab bar controller. We'll need to add some information into these to set the tab's title/icon, but I'll come back to that at the end.
// Create your various view controllers
UIViewController *testVC = [[TestViewController alloc] init];
UIViewController *otherVC = [[OtherViewController alloc] init];
UIViewController *configVC = [[ConfigViewController alloc] init];

As the setViewControllers:animated: method requires an array of view controllers, we'll add our view controllers to an array and then release them. (As the NSarray will retain them.)
// Put them in an array
NSArray *viewControllers = [NSArray arrayWithObjects:testVC, otherVC, configVC, nil];
[testVC release];
[otherVC release];
[configVC release];

Then simply provide the UITabBarController with the array of view controllers and add it to our window.
// Attach them to the tab bar controller
[tabBarController setViewControllers:viewControllers animated:NO];

// Put the tabBarController's view on the window.
[window addSubview:[tabBarController view]];

Finally, make sure you call [tabBarController release]; within your dealloc method.
View Controller Implementation
Inside each of your view controllers, you'll also want to set the title and icon for the tab within the init method as follows:
// Create our tab bar item
UITabBarItem *tabBarItem = [self tabBarItem];
UIImage *tabBarImage = [UIImage imageNamed:@"YOUR_IMAGE_NAME.png"];
[tabBarItem setImage:tabBarImage];
[tabBarItem setTitle:@"YOUR TITLE"];

A: This is how we have to create tabbar programmatically
UINavigationController *BandNavigationController3;
AudienceSettingsViewController *audienceSettingsViewView =[[AudienceSettingsViewController alloc]initWithNibName:@"AudienceSettingsViewController" bundle:nil];
BandNavigationController3 = [[UINavigationController alloc]initWithRootViewController:audienceSettingsViewView];
BandNavigationController3.tabBarItem.title = @"Settings";
BandNavigationController3.tabBarItem.image = [UIImage imageNamed:@"settings.png"];

[BandNavigationController3.tabBarItem initWithTabBarSystemItem:UITabBarSystemItemFavorites tag:4];
BandNavigationController3.navigationBar.hidden = YES;

[bandTabBarArray addObject:BandNavigationController3];
[BandNavigationController3 release];
[audienceSettingsViewView release];

[tabBarController setViewControllers:bandTabBarArray];
[bandTabBarArray release];


text:
Q: Is it possible a Golang package in subdir not included by default? I am using a golang package, say name pkgfoo; and the author explicitly said if we want to use a package subpkg under pkgfoo, I need to explicitly import subpkg. I don't understand the reason behind it. Isn't the subpkg automatically imported if I import the top pkg in Golang?
package main

import (
    "myownpackage"

    "github.com/usera/pkgfoo"
    "github.com/usera/pkgfoo/subpkg"
)

func main() {
    // Use functions in pkgfoo, and use functions in pkgfoo/subpkg
    // ......
    http.HandleFunc("/login", login)
    err := http.ListenAndServe(":9090", nil) // setting listening port
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

My question is whether I really need import "github.com/usera/pkgfoo/subpkg" statement.

A: Go packages are constructed from one or more source files, which are organized into folders in the file system. Source files of the same package must be in the same folder.
But in Go there is no "package hierarchy", the "subpackage" term simply refers to the folder of a package being a subfolder of another. We often organize packages to be in folders being subfolders of others because there is some connection between those packages (e.g. a package is used only by another being in the parent folder; or a package in a subfolder is a specific or more special implementation of the package in the parent folder; or simply just a logical grouping - see the end of the answer).
So whenever you do
import "github.com/usera/pkgfoo"

It only imports pkgfoo and no other packages sharing the same path as prefix. If you need github.com/usera/pkgfoo/subpkg too, you also need to explicitly import it:
import (
    "github.com/usera/pkgfoo"
    "github.com/usera/pkgfoo/subpkg"
}

The Go Blog: Package names on directories used in the standard library:

Directories. The standard library uses like directories crypto, container, encoding, and image to group packages for related protocols and algorithms. There is no actual relationship among the packages in one of these directories; a directory just provides a way to arrange the files. Any package can import any other package provided the import does not create a cycle.


text:
Q: How to get Firefox to correctly identify file download? The following asp.net code works fine on Chrome & IE, but Firefox shows the file as MyDownload.zip.htm and hence doesn't know what to do with it.
        //ASP.Net file download code
        Response.Clear();
        Response.AddHeader("content-disposition", "attachment;filename=MyDownload.zip");
        Response.TransmitFile(Server.MapPath("~/MyDownload.zip"));
        Response.Flush();

Any ideas how to get Firefox to recognise the attachment correctly?

A: Add MIME type header:
Response.ContentType = "application/zip";


text:
Q: Google API blocked my app ip address and returns CAPTCHA My app uses Google API and it worked well for a long time but recently Google blocked the IP address of my server for about an hour and every response to the API was as follows: Our systems have detected unusual traffic from your computer network.  This page checks to see if it's really you sending the requests, and not a robot... - they attached CAPTCHA form field as html.
My app is also an API so CAPTCHA can not be done because it is in json format (HTML in json cannot be rendered).
Only app users sends requests so I have a little control over it. Of course, I limit the number of requests per user, but it was not the case. Limits at google console are also fine.
I wonder how can I prevent this happening in the future? Is there any way I can ask them directly? Have you experienced this?


text:
Q: Ruby To objective-C explanation I have not worked with Ruby before and I have the following snippet I need to simulate it in objective-c
require 'base64'

# ...

  # Where request is of class Net::HTTP::{Get|Post|Put|Delete}
  #
  def sign(request)

    return unless @secret

    request['x-date'] = Time.now.utc.httpdate

    headers = []
    tosign = []

    tosign << request.class.name.split('::').last.upcase
    tosign << request.path.to_s.match(/(\/api.*)$/)[1]

    request.each_header do |h|
      headers << h
      tosign << "#{h}:#{request[h]}"
    end

    tosign << "\n"
    tosign << request.body || ''

    headers = headers.join(";")
    tosign = tosign.join("\n")

    sig =
      Base64.encode64(
        OpenSSL::HMAC.digest(
          OpenSSL::Digest.new('SHA256'),
          @secret,
          OpenSSL::Digest::SHA256.digest(tosign))).strip

    request['x-authorization'] =
      "My " +
      "Key=#{@key_id}," +
      "Algorithm=HMACSHA256," +
      "SignedH=#{headers}," +
      "Signature=#{sig}"
  end1

All I Know that I need to make a NSDictionary to put inside it the value of 'x-date' and 'x-authorization' then pass it as an header for my Request.
x-date is easy I wrote the following as value for it
 NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
df.dateFormat = @"EEE',' dd MMM yyyy HH':'mm':'ss 'GMT'";

NSString *stringDate = [df stringFromDate:[NSDate date]];

but I need help with 'x-authorization'