text:
Q: ASP.net MVC Controller Action - how to prevent redirect I have the following in my Action
[AjaxException]
public ActionResult DoSomething(sring someParam1, string someParam2) {

    //do whatever you need to do here, db etc
    return new EmptyResult();
}

in my html
<form id="search-frm" name="search-frm" action="@Url.Action("DoSomething", "MyActions")" method="post" >

    <input type="button" id="search-btn" value="search" class="btn" onclick="DoSomething();return false;" />
    <input type="text" name="param1" id="param1" />
    <input type="text" name="param2" id="param2" />
</form>

in my JS
function DoSomething() {
   $("#search-frm").submit();
   return false;
}

When I click on the button, and after the controller action DoSomething is done, I get redirected to MyActions/DoSomething. Is there a way to not have that w/o using jquery $.ajax? I simply need to do something and not go away from the existing page.
Thank you.

A: because your code is so. When you click on the button you are calling the DoSomething javascript function and inside that you are submitting the form. So it is same as the normal form submit(clicking on the submit button to submit). that is the reason it is redirecting (actually being posted to DoSomething action.
If you do not want to navigate away from the current page, you may use ajax to do your posting and get result and stay in the same page. So i would make changes to your code like this
1) Get rid of the OnClick event binding from the HTML markup

2) Add this javascript which handles the form submit
$(function(){
  $("#search-frm").submit(e){

   e.preventDefault();  // prevent the default form posting. Let's stay here
   $.post("@Url.Action("DoSomething","MyActions")",$("#search-frm").serialize(), function(data){
          //do something with the response data
   });

  });
});

Not sure why return EmptyResult from the Action method. You may need to return some valid response which indicates the status of the Action you are trying to perform.
[HttpPost]
public ActionResult DoSomething(string param1,string param2)
{
  //do something
   return Json(new
             { Status= true,
               Message="Succesfully saved"
             });
}

You may keep a generic ViewModel to return such results and use that, instead of dynamically typing like above.
public class OperationStatus
{
  public bool Status  { set;get;}
  public string Message { set;get;}
}

and in your action method
[HttpPost]
public ActionResult DoSomething(string param1,string param2)
{
  //do something
  var res=new OperationStatus();
  res.Status=true;
  res.Message="Successfully Added";
   return Json(res);
}


text:
Q: How to delete a file that has a name of type wchar_t in C++ in a portable way? I need to delete a file whose name is defined using wchar_t*. What's the best way to do this?
remove takes a const char* as argument.
Apparently, there is _wremove, but only for windows.
What is considered best practice (portable) to handle this? I could convert the file name to char*, but that misses the point. The file name may have an accent or some other unicode character.
Before somebody says "this is a terrible idea! you should not use wchar_t* for file names!", I did not design the thing. I have been asked to do it that way for whatever reason.

A: Looks like filesystem operations have been added into the standard library since C++17 if you can use it. Otherwise, you can use Boost.Filesystem. Don't know about best practice, but to me this sounds like the way to go.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Inheritance and generics c# I have the following abstract class:
public abstract class PinkBoxMasksDataAbstract
{
    public string PinkBoxText { get; set; }
}

and 2 subclasses:
public class PinkBoxMasksDataNoOverlay : PinkBoxMasksDataAbstract
{
}

public class PinkBoxMasksDataOverlay : PinkBoxMasksDataAbstract
{
    public int PinkBoxLeft { get; set; }
    public int PinkBoxBoxTop { get; set; }
    public int PinkBoxHeight { get; set; }
    public int PinkBoxWidth { get; set; }
}

then I have another class, which has PinkBoxMasksDataAbstract class as parameter:
public class ZonalMatchResult<T> where T : PinkBoxMasksDataAbstract
{
    public decimal Confidence { get; set; }
    public int GreenBoxLeft { get; set; }
    public int GreenBoxTop { get; set; }
    public int GreenBoxHeight { get; set; }
    public int GreenBoxWidth { get; set; }

    public List<T> PinkBoxMasksData { get; set; }
}

public class ZonalResult<T> where T : PinkBoxMasksDataAbstract
{
    public int ExitCode { get; set; }
    public string ErrorMessage { get; set; }
    public int NumberOfGreenBoxMatches { get; set; }
    public int NumberOfPinkBoxExtractFrames { get; set; }
    public int ProcessingTime { get; set; }
    public bool HasOverlay { get; set; }

    public List<ZonalMatchResult<T>> MatchResults { get; set; }
}

now I want to create this class this way:
            ZonalResult<PinkBoxMasksDataAbstract> zonalResult;
            if (isOverlayRequired)
                zonalResult = new ZonalResult<PinkBoxMasksDataOverlay>();
            else
                zonalResult  = new ZonalResult<PinkBoxMasksDataNoOverlay>();

but I get an error:

Cannot implicitly convert type
  'Domain.ZonalResult<Domain.PinkBoxMasksDataOverlay>' to
  'Domain.ZonalResult<Domain.PinkBoxMasksDataAbstract>'

Why it happens if PinkBoxMasksDataOverlay is subclass of PinkBoxMasksDataAbstract? How to fix?

A: ZonalMatchResult does not inherit from PinkBoxMasksDataAbstract, only its type parameter does. That is the reason, you get this error.
You could specificaly set the data this way (of course it may not be abstract in this case):
ZonalMatchResult<PinkBoxMasksDataAbstract> r = new ZonalMatchResult<PinkBoxMasksDataAbstract>;
if (isOverlayRequired)
    r.PinkBoxMasksData = new PinkBoxMasksDataOverlay();
else
    r.PinkBoxMasksData = new PinkBoxMasksDataNoOverlay();

However, why not simple have PinkBoxMasksData class which has a Overlay property. If this property is null, you do not have an Overlay.
public class Overlay
{
    public int PinkBoxLeft { get; set; }
    public int PinkBoxBoxTop { get; set; }
    public int PinkBoxHeight { get; set; }
    public int PinkBoxWidth { get; set; }
}

public class Mask
{
    public string PinkBoxText { get; set; }
    public Overlay Overlay { get; set; }
}

var mask = new Mask();
if (isOverlayRequired)
{
    mask.Overlay = new Overlay();
}

For Interfaces, there is also the option of covariance, but this is not possible for classes. So no, I don't think there is a way.


text:
Q: How does Reflector decompile code? How do tools like the Red Gate Ant Profiler or the Reflector convert IL into C# or VB.NET code?
I recently noticed that the Red Gate Ant Profiler does not generate the same source code that was written originally.
It generated a while loop where I had used a foreach.
That made me think. I opened Reflector.exe itself in Reflector but their code is mostly (not all of it) obfuscated.

A: Decompilers in general work by looking at the IL and constructing source code which is semantically equivalent to the IL. This can't always yield the orignal source code, because IL drops some high-level information (though not as much as machine code) and because there's usually several pieces of code that compile to the same IL. For example, a foreach loop is equivalent to a certain kind of while loop (one that sets up an enumerator first, then loops until the enumerator is exhausted, and advanced the enumerator at each step).

A: A common technique for implementing decompilation is to use something called "Interval Analysis" for identifying the extent of loops.
When combined with idiom recognition, and a pattern know as the "derived sequence of graphs", one can start with a control flow graph containing assembly language (or MSIL) and iteratively simplify it until you have a single AST (abstract syntax tree) node representing a "source level" view of the program (or method). Given the AST it's then trivial to generate source: you just then pretty print the resulting AST.
Here are some links to more information:
http://en.wikipedia.org/wiki/Interval_(graph_theory)
http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.50.8004&rep=rep1&type=pdf
Generally, you'll never have complete fidelity between the original source and the decompiled source.
The control flow graph for a foreach loop looks like the control flow graph for a while loop. This is largely because the following code:
foreach (var x in xs) {
    //body
}

is actually syntactic sugar for:
var enumerator = xs.GetEnumerator()
try {
    while (enumerator.MoveNext()) {
        var x = xs.Current;
        //body
    }
}
finally {
    enumerator.dispose();
}

That is, the foreach loop is basically translated into the while loop, and then the while loop is compiled into MSIL.
In order for a decompiler to produce a for-each loop, it would have to add special support for attempting to guess when a while loop is in fact a foreach loop. Any such logic would not be perfect (both the above while loop and the foreach loop should yield the same (or very similar) MSIL code).
In some cases it would match the source you wrote, and in other cases it wouldn't.
Chances are you would probably have written a for-each loop, so from a usability perspective, erring on the side of for-each loops vs while loops is a good choice.
However, it's extra work. The decompiler writer has to set out to say "I want to add bunch of heuristics for trying to detect for-each loops".
Finally, there are a lot of things that can frustrate decompilation. For example the presence of "break" and "continue" statements can really complicate things. So can certain kinds of nesting (loops inside of switch statements, and vice-versa). They can all lead to CFG loops having more than one entry point and more than one exit point. That increases the difficulty of generating readable source code.
Usually the only way to deal with those cases is to use heuristics. Those heuristics will sometimes "do the wrong thing".
Also, even little things, like the particular expressions that are used for loop bounds can break idiom recognition. Sometimes the compiler will introduce temporary variables (that were not present in source). This may either requires extra idiom checks, or more advance techniques such as data flow analysis (live variable analysis, definition-use chains, etc).
In summary: decompilation is hard, and will never be perfect. Also, I'm sure the implementers had to consider tradeoffs. For example, does it make sense to invest in detecting for-each loops or should time be spent in decompiling lambdas and inferring LINQ queries?


text:
Q: Date operations in Oracle I'm trying to run this queries (Oracle 12c):
SELECT trunc(sysdate) - '25-SEP-18' FROM dual;

SELECT 1 FROM dual WHERE trunc(sysdate) = '04-SEP-19';

CREATE TABLE my_table (order_date date);
INSERT INTO my_table (order_date) VALUES ('04-SEP-19');

I expect implicit conversion and everything is good with the 2 last queries, but for the first i get error ORA-01722: invalid number. NLS_DATE_FORMAT = 'DD-MON-RR'. What is the problem?

A:
The question is WHY is does not work? I didn't find any explanations in documentation.

The documentation has a section on Datetime/Interval Arithmetic which explains what is allowed. The table shows that arithmetic is only allowed between dates, timestamp, intervals and numbers. When you do:
SELECT trunc(sysdate) - '25-SEP-18'

you are trying to subtract a string from a date, which isn't possible. Oracle 'helpfully' tries anyway and interprets the string as a number, effectively doing:
SELECT trunc(sysdate) - to_number('25-SEP-18')

which understandably throws the error you see, "ORA-01722: invalid number". As already said, you should explicitly convert your string to a date:
SELECT trunc(sysdate) - to_number('25-SEP-18', 'DD-MON-RR')

or preferably with a four-digit year, and since you're using a month name it's safer to specify the language that is in:
SELECT trunc(sysdate) - to_number('25-SEP-2018', 'DD-MON-YYYY', 'NLS_DATE_LANGUAGE=ENGLISH')

or more simply, if it's a fixed value, with a date literal:
SELECT trunc(sysdate) - DATE '2018-09-25'

I expect implicit conversion

You should not rely on implicit conversion, particularly where that is influenced by session NLS settins. As well as the date language I already mentioned, someone else running your statement could have a different NLS_DATE_FORMAT setting which could lead to errors or more subtle data mismatches or corruption; e.g.
alter session set nls_date_format = 'DD-MON-YYYY';

SELECT trunc(sysdate) - DATE '2018-09-25' FROM dual;

TRUNC(SYSDATE)-DATE'2018-09-25'
-------------------------------
                            344

SELECT trunc(sysdate) - to_date('25-SEP-18') FROM dual;

TRUNC(SYSDATE)-TO_DATE('25-SEP-18')
-----------------------------------
                             730831

SELECT 1 FROM dual WHERE trunc(sysdate) = '04-SEP-19';

no rows selected

CREATE TABLE my_table (order_date date);
INSERT INTO my_table (order_date) VALUES ('04-SEP-19');

The second query gets a much bigger value than expected; and the third gets no rows back from dual.
Looking at the implicitly converted date shows you why:
SELECT to_char(order_date, 'SYYYY-MM-DD HH24:MI:SS') FROM my_table;

TO_CHAR(ORDER_DATE,'
--------------------
 0019-09-04 00:00:00

With a YYYY mask (and no FX modifier) a 2-digit year value like 19 is converted as 0019, not 2019. That sort of problem could go unnoticed for some time, giving you incorrect results in the meantime.
If the session's format mask had RRRR or - as you have - RR then it would be interpreted as 2019; but the point is that you usually have no control over the settings in another session that runs your code later.
You can also cause performance issues or errors by creating implicit conversions where you didn't expect, or where they behave in a way you didn't expect. Not in this example - "When comparing a character value with a DATE value, Oracle converts the character data to DATE" - but it still comes up. It's better to avoid the possibility.

A: When dealing with strings with dates in them you should use the to TO_DATE command, otherwise Oracle may not always figure out that the string contains a date.
SELECT trunc(sysdate) - TO_DATE('25-SEP-18') FROM dual;

Even better is to indicate the format of the date within the string
  SELECT trunc(sysdate) - TO_DATE('25-SEP-18','DD-MON-RR') FROM dual;


text:
Q: Can't display HTML tags on error in PHP 7 With this ini settings:
ini_set("log_errors", 1);
ini_set("display_startup_errors", 1);
ini_set("error_log",APP_LOG);
ini_set("error_reporting", E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED);
ini_set("log_errors_max_len",1024);
ini_set("docref_root","http://manual/en/");
ini_set("html_errors",1);

I normally get HTML tags on displaing errors my PHP version is 7.0.22

A: Try turning on xdebug in your php.ini file. Then restart your web server.

A: ini_set("html_errors",true); will be correct settings and after setting your setting, restart your php server.
if you want to use error_handling in php-7 , it will handle this way:
try{
     // Your code
}
catch(Error $e) {
    $trace = $e->getTrace();
    echo $e->getMessage().' in '.$e->getFile().' on line '.$e->getLine().' called from '.$trace[0]['file'].' on line '.$trace[0]['line'];
}


text:
Q: How to pipe multiple exe files then output result to file? I want to merge two json files, then transform output into yaml and output it into file. My current code (which is not working):
param($parentJson, $childJson)

$cmdPath = "$PSScriptRoot\jq-win64.exe"
$cmdArgList = @(
    "-s",
    ".[0] * .[1]",
    "$parentJson"
    "$childJson"
)

$cmdPath2 = "$PSScriptRoot\yq_windows_386.exe"
$cmdArgList2 = @(
    "eval",
    "-P",
    "-o=yaml"
)

$resultJson = (cmd /c $cmdPath $cmdArgList 2>&1) -join "`r`n"

$resultYaml = $resultJson > (cmd /c $cmdPath2 $cmdArgList2)

$resultYaml

How to pipe two executable with multiple arguments into file? Honestly this is only thing I thought will be easy to do in powershell, but I don't have enough experience to comprehend why everything so hard when you work with executable stdin/stdout and just want to pipe one into another.

A: Found an easy solution:
param($parentJson, $childJson, $outputYaml)

.\jq-win64.exe -s '.[0] * .[1]' $parentJson $childJson | .\yq_windows_386.exe eval -P -o=yaml - > $outputYaml


text:
Q: How to add data via directories for training images I have been going through git repository by flyyufelix "https://github.com/flyyufelix/cnn_finetune" to fine tune an inception v3 network I want to train network to detect a disease so I have 2 set of images one with disease and without disease.
The git says X_train, Y_train, X_valid, Y_valid = load_data() he loads the cifar dataset ,The git asks us to create our own load_data() function.The author has the code as below
import cv2
import numpy as np

from keras.datasets import cifar10
from keras import backend as K
from keras.utils import np_utils

nb_train_samples = 3000 # 3000 training samples
nb_valid_samples = 100 # 100 validation samples
num_classes = 10

def load_cifar10_data(img_rows, img_cols):

    # Load cifar10 training and validation sets
    (X_train, Y_train), (X_valid, Y_valid) = cifar10.load_data()

    # Resize trainging images
    if K.image_dim_ordering() == 'th':
        X_train = np.array([cv2.resize(img.transpose(1,2,0), (img_rows,img_cols)).transpose(2,0,1) for img in X_train[:nb_train_samples,:,:,:]])
        X_valid = np.array([cv2.resize(img.transpose(1,2,0), (img_rows,img_cols)).transpose(2,0,1) for img in X_valid[:nb_valid_samples,:,:,:]])
    else:
        X_train = np.array([cv2.resize(img, (img_rows,img_cols)) for img in X_train[:nb_train_samples,:,:,:]])
        X_valid = np.array([cv2.resize(img, (img_rows,img_cols)) for img in X_valid[:nb_valid_samples,:,:,:]])

    # Transform targets to keras compatible format
    Y_train = np_utils.to_categorical(Y_train[:nb_train_samples], num_classes)
    Y_valid = np_utils.to_categorical(Y_valid[:nb_valid_samples],num_classes)
return X_train, Y_train, X_valid, Y_valid

can i know how to generate a function which loads
 data X_train, Y_train, X_valid, Y_valid = load_data() when i have directries in pc

A: Use Keras' ImageDataGenerator() class and call flow_from_directory() on it. The labels will be automatically inferred from the directory names. So if you have a directory titled "disease," then Keras would infer that all images within that directory are labeled as "disease," and the same thing would be true for another directory titled "no disease," for example.
I demonstrate how to prepare image data for training a CNN in Keras in this video. The first half of the video is about image organization on disk, and then the second half goes through the process described above.

A: Follow this tutorial once and all your doubts will get cleared.
https://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html


text:
Q: How do I design a device to automatically switch to the backup battery? I've been told that many kinds of batteries work best if they are used until they are completely drained, and then recharged.
(Edit: The "memory effect myth" is quite widespread. Batteries work just as well if they are "topped up" every time.)
Right now I design devices the standard way: try to use the battery power as long as possible, and then when there is no power left it doesn't work at all.
If there was some simple way of implementing the following, I might use it from now on:

*

*Two independent batteries (or more)

*Once you start using one battery, continue to use it until it is completely drained reaches the manufacturer-recommended minimum voltage.

*When the "in use" battery is completely dead, switch to using the next battery. Presumably you use some technique similar to the "Switch between 5V power supplies?" question.

*Once you switch to the last battery, go into some sort of low-power mode so it can still do the important things in "limp mode", but the user is notified to plug it into a charger as soon as possible.

*After plugging into the charger, go back to standard mode -- but if disconnected from the charger before the batteries are fully charged, go back to limp mode.

*(optional) When plugged into the charger, only charge the drained battery (or batteries) and keep them topped off; leave the one "in use" battery alone.

*(optional) keep track of precisely how much total energy could be extracted from each particular battery the most recent time it was fully drained. Use that number (perhaps modified using Peukert's law) to give extremely accurate estimates of future run-time.

Why don't all devices do this?

*

*cell phones: first battery: talk like crazy. last battery: only emergency calls.

*laptops: last battery: throttle back to a slow speed that is adequate for looking up static documents

*handheld GPS: last battery: try to reduce energy by updating the screen less often, dimming the backlight, etc.

A: Why don't all devices use this?  It adds cost and complexity.  Is their any other reason for not doing something?
Seriously, I'd say that there are plenty of options and implementations for this.  Having two equal batteries doesn't make much sense, so often the second is used for emergency or limp-home power.  For instance, your PC has a RAM retaining battery on the motherboard for when you loose power.  A laptop often gives a "Low battery" warning, at which time you're welcome to reduce power however you can.
I think that your statement that 'batteries work best if they are used until they are completely drained, and then recharged.' is a little broad.  This is more the case for Nickel-based (NiCd and, to a lesser extent, NiMH) chemistries.  Lithium Ion cells don't suffer this memory problem.  In fact, their lifetime improves if you avoid deep discharges.  See this page from BatteryUniversity.com for reference.
There are a couple of options for doing more intelligent power management in your own devices.
The simplest is an ORing diode on the power supply.  If all you want is a hot-swappable power supply and you have a bit of leeway for your inputs, you can connect backup battery to the anode of a diode, and connect the cathode to your main battery.  When the voltage of the main battery dips to 0.7V less than your backup (Or is removed), the other battery kicks in.  Be careful of leakage current into the backup battery, it might overcharge it.
Alternatively, you can use a power mux IC like the TPS110.  This lets you select your input independently (or dependently, if you prefer) of the input voltages, instead of always using the higher supply.
Finally, Linear Technology incorporates what they call "PowerPath" controllers into their battery charging ICs.  I've used their LTC4011 which seamlessly transitions between battery and external power, and charges the battery while running off of the external power.

A: Nickel Cadmium cells were the infamous batteries which could build up a "memory" effect if not periodically cycled.
Newer Lithium-Ion rechargeable cells are considered immune from the memory effect. In fact, its best not to fully discharge them (stored in a fully discharged state can reduce lifetime), hence most electronics enter a "death" state while they can still monitor energy but refuse to enter a high power state.
Many devices, included laptops, can very accurately monitor battery state via their charger's coloumb counter and voltage of the cell(s). This allows all of the above behavior without the need and cost of duplicate charge circuits and batteries.

A: Completely discharging you battery is bad for all batteries (well, maybe not lithium-hydrogen batteries, but if you have those in your laptop, you know what you're doing anyways).
The practice originates with NiCad batteries, due to a confluence of unfortunate design decisions. The common-knowledge belief that NiCads loose capacity if not fully cycled is false.
Basically, the shallow-cycling of NiCad batteries results in a depression of the discharge curve, resulting in many electronic devices which use NiCads incorrectly reporting the battery as being empty. Note that the capacity of the cell is not significantly reduced, the cell voltage is merely depressed by a small amount. The fact that the major portion of the NiCad discharge curve is very flat leads to a small change in overall cell voltage causing a large change in the battery "Charge State" readout.
Note that the memory effect occurs only with NiCads, and was never actually even present in any other cell chemistries. The conflation of battery types, and naive assumption that all batteries are the same is what has lead to the belief about all batteries needing periodic cycling.
It is probably more accurate to think about batteries as being able to store and release a certain amount of energy, rather than being able to withstand a certain number of cycles. Whether this energy is release in 500 half-cycles or 1000 quarter-cycles is largely not relevant (An increased depth of discharge will actually reduce the total overall energy capability of batteries, though not significantly unless the batteries is discharged completely).
The manufacturer's that state that you should fully discharge and recharge your devices battery are stating this solely so that the internal battery charge measuring electronics can properly calibrate themselves. Basically, over time, the charge-state measurement will drift due to slight variance in the efficiency of charging and discharging the battery (basically, it's an integrator). A single full-cycle lets the electronics accurately measure the battery capacity without having to guess about the battery condition. The fact that if not fully cycled, battery measurement electronics will inaccurately report the battery state has led to the perseverance of the Memory Effect myth. The battery has not actually changed, the electronics are merely reporting an incorrect charge state.
As far as I know, the biggest cause of gradually reducing battery life in electronics is time. Lithium batteries actually have a shelf-life rated in a few years, whether they are used or not. Proper storage practices can extend this shelf life, but they will decay over time, no matter what use you put them through.
Deep cycling lithiums is actually quite bad for them, actually. Don't do it unless you have to (try to stay above 20% SOC).
Note: I am skipping a few things, like the issues with whisker growth in nicads. See the below link on NiCad for further reading.
See:
http://en.wikipedia.org/wiki/Memory_effect
http://en.wikipedia.org/wiki/Nicad


text:
Q: navigationController keeps running after pop Please help me understand the mystery of navigationController. I have a HomeViewController which gets invoked from the didFinishLaunchingWithOptions. From HomeViewController user press a button and my code is
-(IBAction)showMap:(id)sender
{
    MapViewController *mapViewController = Nil;
    mapViewController = [[MapViewController alloc] initWithNibName:@"MapView-iPad" bundle:nil];
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate.navigationController pushViewController:mapViewController animated:YES];
}

When a user wants to go back from MapViewController, I use the code
-(IBAction)goBackToHome:(id)sender
{
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate.navigationController popViewControllerAnimated:YES];
}

I was under impression that once I am out of MapViewController, all my resources get freed associated with MapViewController. To verify that I put this code inside initWithNibName in MapViewController.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    // Custom initialization
    [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(printMessage) userInfo:nil repeats:YES];
 }
 return self;
}

-(void) printMessage
{
     NSLog(@"I am inside Map View Controller");
}

To my surprise, even after popping out the MapViewController, the printMessage still continues. Please help me understand what is going on and why MapViewController is still running. Is there any way I can verify the MapViewController is freed up ?

A: Take a look at the documentation for NSTimer. In particular, the scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: method. The documentation notes that

target
  The object to which to send the message specified by aSelector when the timer fires. The target object is retained by the timer and released when the timer is invalidated.

This means that your timer is causing the MapViewController to be retained. Without that timer holding onto a reference to the controller, it should indeed be deallocated when you pop it from the navigation controller.

A: MapViewController is still being retained: The timer retains the ViewController, and the timer is retained by the run loop it is scheduled on. To get your MapViewController to be released you have to remove the timer from the run loop by using [yourTimer invalidate]. One way to do this is to keep a weak reference to your timer in your MapViewController:
@property (weak) NSTimer *timer;

When you create the timer, assign it to the property:
self.timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(printMessage) userInfo:nil repeats:YES];

Now you can invalidate the timer when you no longer need it, e.g. in viewWillDisappear:
- (void)viewWillDisappear {
    [self.timer invalidate];
    [super viewWillDisappear];
}


text:
Q: jQuery Deprecation Notice jqxhr.success() I recently saw a deprecation notice on the jQuery website.

Deprecation Notice: The jqXHR.success(), jqXHR.error(), and
  jqXHR.complete() callbacks will be deprecated in jQuery 1.8. To
  prepare your code for their eventual removal, use jqXHR.done(),
  jqXHR.fail(), and jqXHR.always() instead.

I am currently coding as below:
$.ajax({
  url: '...',
  success: function(){
    alert('AJAX successful');
  }
});

I am planning to use jQuery 1.8+
Should I just change the success key into done as:
$.ajax({
      url: '...',
      done: function(){
        alert('AJAX successful');
      }
    });

?

A: I know this is an old question, and jQuery 1.8 came out ages ago - but to help Googlers like me who are upgrading ancient applications to 3.0, I thought I'd chime in for clarification.
This is valid in versions jQuery 1.8+:
$.ajax({
    url: "/api/endpoint",
    type: "POST",
    data: myData,
    success: function(json){
        console.log("success");
        console.log(json);
    },
    error: function(jqxhr){
        console.log("failure");
        console.log(jqxhr.responseText);
    }
});

This is NOT valid in versions jQuery 1.8+. It has been removed in 3.0:
var promise = $.ajax({
    url: "/api/endpoint",
    data: myData,
    method: "POST"
});

promise.success(function(json){
    console.log("function not defined!"); // same for .error and .complete
});

See @DevIshOne's answer or the jQuery AJAX documentation for how to account for this. You simply have to rename to done(), fail(), and always() respectively, or rewrite the code as per my first code block.

A: For instance, if you have any of these:
$.ajax({url: '...'}).success(function(){
    alert('AJAX successful');
});
$.ajax({url: '...'}).error(function(){
    alert('AJAX ERROR');
});
$.ajax({url: '...'}).complete(function(){
    alert('AJAX complete');
});

You would have to change it to:
$.ajax({url: '...'}).done(function(){
    alert('AJAX successful');
});
$.ajax({url: '...'}).fail(function(){
    alert('AJAX ERROR');
});
$.ajax({url: '...'}).always(function(){
    alert('AJAX complete');
});


text:
Q: Custom Dict Dropping Keys When Cast I have a custom class that inherit from dict (shown below) and when I cast the object to a dict, it drops the key called 'type'.  Is there any reason why this is happening?
I expect the following results:

dm = Parameter()
print(dict(dm))
{'tags': 'bar', 'type': 'Item', 'title': 'foo'}

What I end up getting is:

{'tags': 'bar', 'title': 'foo'}

The self._map contains the 'type' key/value pair, so I don't know what could be the problem.  Does anyone have any suggestions?
class ItemParameter(dict):
    """
    """
    def __init__(self,
                 title,
                 tags):
        super(ItemParameter, self).__init__(title=title, tags=tags)
        self._map = {}
        self._allowed_keys = {'type':'type',
                              'title': 'title',
                              'tags':'tags',
                              'thumbnail': 'thumbnail',
                              'thumbnailurl': 'thumbnailurl',
                              'metadata': 'metadata',
                              'type_keywords' : 'typeKeywords',
                              'description': 'description',
                              'snippet' : 'snippet'}
        self['type'] = "Item"
        self['title'] = title
        self['tags'] = tags

    def __iter__(self):
        for k, v in self.items():
            yield k, v

    def __setitem__(self, k, v):
        if k in self._allowed_keys:
            self._map[self._allowed_keys[k]] = v

    def __getitem__(self, k):
        if k in self._map:
            return self._map[k]
        elif k in self._allowed_keys and \
             self._allowed_keys[k] in self._map:
            return self._map[self._allowed_keys[k]]

    def __setattr__(self, k, v):
        if k in {'_map','_dynamic', '_allowed_keys',
                 '_ipython_canary_method_should_not_exist_'}:
            super(ItemParameter, self).__setattr__(k,v)
        else:
            if k in self._allowed_keys.keys():
                self._map[self._allowed_keys[k]] = v

    def __getattr__(self, k):
        if k == {'_map','_dynamic', '_allowed_keys',
                 '_ipython_canary_method_should_not_exist_'}:
            super(ItemParameter, self).__getattr__(k)
        else:
            if k in self._allowed_keys.keys() and \
               self._allowed_keys[k] in self._map:
                return self._map[self._allowed_keys[k]]
    def __delattr__(self, key):
        return self._map.__delitem__(key)
    def __contains__(self, k):
        return self._map.__contains__(k)
    def __repr__(self):
        return str(self._map)
    def __str__(self):
        return self.__repr__()
    def items(self):
        return self._map.items()

A: As ShadowRanger mentions, it's bad design to duplicate the dict data in the ._map attribute, and you're generally much better off not subclassing the built-in types.
I've reduced your code down to the bare minimum that reproduces this "bug", and I'm still not totally sure why it behaves exactly like it does, but we can fix the bug by making sure that __setitem__ adds the new item to self as well as to self._map. For example:
def __setitem__(self, k, v):
    if k in self._allowed_keys:
        k = self._allowed_keys[k]
        self._map[k] = v
        super(ItemParameter, self).__setitem__(k, v)

Here's a new version of your class that does what I think you want. It uses the Python 3 version of super() which has a zero args form.
class ItemParameter(dict):
    allowed = {
        'type':'type',
        'title': 'title',
        'tags':'tags',
        'thumbnail': 'thumbnail',
        'thumbnailurl': 'thumbnailurl',
        'metadata': 'metadata',
        'type_keywords' : 'typeKeywords',
        'description': 'description',
        'snippet' : 'snippet',
    }

    def __init__(self, title, tags):
        super().__init__(title=title, tags=tags)
        self['type'] = "Item"

    def __setitem__(self, k, v):
        if k in ItemParameter.allowed:
            k = ItemParameter.allowed[k]
            super().__setitem__(k, v)

    def update(self, other):
        for k, v in other.items():
            self[k] = v

# test

p = ItemParameter(title='foo', tags='bar')
for t in p:
    print(t)
print(p)
print(p.copy())
print(dict(p))
p['type_keywords'] = 'some thing'
print(p)
p['bad'] = 'other thing'
print(p)
p.update({'a':1, 'b':2, 'metadata': 3})
print(p)

output
title
tags
type
{'title': 'foo', 'tags': 'bar', 'type': 'Item'}
{'title': 'foo', 'tags': 'bar', 'type': 'Item'}
{'title': 'foo', 'tags': 'bar', 'type': 'Item'}
{'title': 'foo', 'tags': 'bar', 'type': 'Item', 'typeKeywords': 'some thing'}
{'title': 'foo', 'tags': 'bar', 'type': 'Item', 'typeKeywords': 'some thing'}
{'title': 'foo', 'tags': 'bar', 'type': 'Item', 'typeKeywords': 'some thing', 'metadata': 3}

A: You've got two completely different dicts here; the one that's implicitly part of your own object's structure (because you inherit from dict) and _map. The two keys you're seeing are the ones you set by calling the superclass __init__ (first line in your initializer) which delegates to update (which you also didn't override), while the dict constructor you're using to print is ignoring them.
In general, it's a bad idea to try to inherit from dict itself while changing meaningful behaviors, because it's easy to miss an important code path and not get the results you expect. For example, in this case, I believe the handling code is calling your classes's keys method, which you didn't override, so it's getting keys from the superclass implementation, which bypasses your custom code.
Even if you did override it, there are occasional fast paths scattered around the code that can end up bypassing your custom code for performance boosts, reading the dict components of your subclass directly (without seeing _map or your custom __[gs]etitem__ overrides at all).
I'd suggest looking at inheriting from collections.abc.MutableMapping, so you're not a true dict, but it's more intuitive what methods require overriding and how you must do it.
If you must be a dict subclass, operate on yourself directly, not a _map member, so you'll be usable as a dict in the first place. Use super() to call parent methods, e.g. replacing:
def __setitem__(self, k, v):
    if k in self._allowed_keys:
        self._map[self._allowed_keys[k]] = v

with:
def __setitem__(self, k, v):
    if k in self._allowed_keys:
        super().__setitem__(self._allowed_keys[k], v)

which will alter the dict structure you inherited from, not an unrelated attribute that happens to be a dict too.


text:
Q: Number Pad not showing swift 4 I am doing a side project , just to implement some UI objects and see if i can do simple programming..
i have put a uilable, a textfield and a button.. the objective is to enter numbers in the textfield and display it on the lable when pressing the button.. i have selected the number keyboard for input.. as am only interested in entering numbers..and using the iPhone 8 simulator... i am using macOS Mojave 10.14, xcode 10.1, swift 4.2 ...
on run , strange things happing.. number pad keyboard does not  compe up! and text field doesnt take in put , even from the laptop keyboard...
error message:
2018-11-08 12:11:51.910752+0300 QPages 3[4250:186019] libMobileGestalt MobileGestalt.c:890: MGIsDeviceOneOfType is not supported on this platform.
2018-11-08 12:11:54.219190+0300 QPages 3[4250:186019] [MC] System group container for systemgroup.com.apple.configurationprofiles path is /Users/mohamedabousaif/Library/Developer/CoreSimulator/Devices/0B0D8741-BDE6-4F62-900D-E52DE7B4D27C/data/Containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles
2018-11-08 12:11:54.220103+0300 QPages 3[4250:186019] [MC] Reading from private effective user settings.
2018-11-08 12:11:54.289740+0300 QPages 3[4250:186019] Can't find keyplane that supports type 4 for keyboard iPhone-PortraitChoco-NumberPad; using 20603_PortraitChoco_iPhone-Simple-Pad_Default
2018-11-08 12:11:55.532774+0300 QPages 3[4250:186137] [MC] Invalidating cache
can anybody help please ..
Thanks .enter image description here


text:
Q: Monitor the performance of individual window service I have 7 windows services. i want to monitor the performance of the individual services like the processor usage, memory usage etc.
If i use perfmon, it gives for the entire system but not the individual services. Can anyone please suggest how do i monitor the performance of individual services?

A: Perfmon can monitor individual processes! Just chose process in "Add counters/Performance objects" combo. For "quick" monitoring I have found that Sysinternals (now Microsoft) Process Explorer is easy and nice. Some services give you performance information (available by sockets/files etc) that can be displayed by tools such as MRTG or Cacti.

A: To check the memory of individual services, you will have to change the service types to "Own Process". This Gist show the complete code. The central idea is trying to change the service type from the least intrusive to the most intrusive way:
$win32Service = Get-CimInstance -ClassName Win32_Service -Filter "Name = '$ServiceName'" -Verbose:$false

if ($win32Service)
{
    if (!(Set-ServiceTypeToOwnProcessByCim $win32Service))
    {
        if (!(Set-ServiceTypeToOwnProcessByWindowsRegistry $win32Service))
        {
            if (Grant-FullControlRightsOnServiceRegistryKeyToCurrentUser $win32Service)
            {
                Set-ServiceTypeToOwnProcessByWindowsRegistry $win32Service | Out-Null
            }
        }
    }
}
else
{
    Write-Warning "[$ServiceName] Service not found"
}

When putting the Set-ServiceTypeToOwnProcess.ps1 and Enable-Privilege.ps1 files in the same folder, you can execute the script like this:
.\Set-ServiceTypeToOwnProcess.ps1 -ServiceName 'Appinfo', 'gpsvc', 'Schedule', 'SENS', 'SessionEnv', 'wuauserv'


text:
Q: AttachEvent Not Working on IE11 I am trying to make two checkboxes, out of which only one can be selected at any point of time. I searched the forums a lot and found a few suggestions.
if (document.attachEvent){
// For IE Browsers.
document.attachEvent("DOMContentLoaded", function (event) {

    var saSelector = document.querySelector('input[name=saWrite]');
    var cgSelector = document.querySelector('input[name=cgWrite]');

    if (cgSelector !== null) {
        cgSelector.attachEvent('change', function (event) {
            if (cgSelector.checked) {
                document.querySelector('input[name=saWrite]').checked = false;
            }
        });
    }

    if (saSelector !== null) {
        saSelector.attachEvent('change', function (event) {
            if (saSelector.checked) {
                document.querySelector('input[name=cgWrite]').checked = false;
            }
        });
    }
});
}

I wrote a similar function with addEventListener in place of attachEvent for non-IE browsers. That works on Firefox. But this method somehow doesn't work for IE. Am I doing something wrong here? Any suggestions would be helpful. I wish i could use JQuery for this. But i cant.

A: https://jsfiddle.net/20g7ym8q/
You say you want to use JQuery but you can't. I realize starting out that may seem like a real limitation, but it isn't. Anything you can do with JQuery you can do with JavaScript.
Your code won't work on IE11 because attachEvent has been deprecated and removed in favor of accepting addEventListener as the standard way to attach an event in all modern browsers. If you're looking for generational support without JQuery and without code duplication, setting up your own Object to use as an intermediate layer between your code and the browser is probably the best way to go about this.
 function $(ele) {
  return {
    ele: document.querySelector(ele),
    on: function(ev, fn) {
      (document.attachEvent) ?
      this.ele.attachEvent(ev, fn) :
      this.ele.addEventListener(ev, fn);
    },
    checked: function(change) {
     if(typeof change !== undefined) this.ele.checked = change;
     return this.ele.checked;
    }
  }
}

The above is a function that returns an Object with two methods and a property. It works similarly to JQuery for familiarity and consistency, but it is without the overhead of including the entire JQuery library.
The methods allow you to add an event using .on with an event type and function as parameters. The methods also allow you to set or get the checked property of the specified element. .checked() will simply return a boolean as to whether the box is checked, .checked(boolean) will set the elements property to the desired state.
In practice, to solve your dilemma of only one allowable check box, you could do this:
var sa = $('input[name="saWrite"]');
var cg = $('input[name="cgWrite"]');

cg.on('click', function(ev) {
  sa.checked(false)
});

sa.on('click', function(ev) {
  cg.checked(false);
});


text:
Q: Dockerfile dotnet restore locally instead of reaching to nuget server I'm working on a .net core 3.1 project for a company.  I have a pretty simple dockerfile configured that leverages RUN dontnet restore to retrieve all the necessary nuget packages for my project.  This works fine for me.  It will build and run the container no problem.
The problem comes when the company pulls my solution to their network and they try to run the same dockerfile.  Their firewall rules block SSL connections to external sites (with explicit exceptions that nuget is not part of).  So when they try to build the container they get failure when the restore tries to access "https://api.nuget.org/v3/index.json".  Which makes sense to me for the reasons above.
If I update my dotnet build to include nuget packages as part of the published output, can I have the dockerfile update to reference that published output for nuget packages instead of doing a dotnet restore from nuget itself?  Essentially is there a good way to handle the docker build process so it can be done offline (i.e. without relying on external sources)?

A: You could create a local cache using NuSave, then add it to your Docker container; which can be used to restore the solution offline.

A: As @Lex Li mentioned above, the better way to do things was a self contained publish with dotnet and then copying those files over into the container so that there was no need to do a dotnet restore.
I typically like to do dotnet restore to keep the size small but in this case this was the right way to do it.


text:
Q: Changing programmatically connection properties after failed connection attempt - Hibernate I want to change connection properties programmaticaly if hibernate cant connect to database. I am trying to do this using this code:
    String connectionString = "jdbc:oracle:thin:@" + Cfg.getHost() + ":" + Cfg.getPort() + ":" + Cfg.getSid();

    Configuration configuration = new Configuration()
            .setProperty("hibernate.connection.url", connectionString)
            .setProperty("hibernate.connection.password", Cfg.getPassword())
            .setProperty("hibernate.connection.username", Cfg.getLogin());

    sessionFactory = configuration.configure().buildSessionFactory();

Properties are from property file. But buildSessionFactory work for the first connection attempt. For anothers attempts he ignoring configuarion and doesnt want to create new SessionFactory.

A: SessionFactory is supposed to be created once. Later on during runtime, you should create sessions for your DB operations using that factory.


text:
Q: finding time taken for tank to get filled in differential calculus mixing problem A $200$ Gal tank is half full of distilled water.
A time $t=0$, a solution containing $0.5 ib/gal$ of concentrates enters the tank at the rate of $5 Gal/min$, and the well stirrec mixture is drawn with a route of $3Gal/min$.
A. At what time will the tank be full
B.  At the time the tank is full, how many pound of conc will the well stirred solution be conc.


text:
Q: Updating release def results in error VS402903: The specified value is not convertible to type ReleaseDefinition I am updating release definitions using the onpremise Azure DevOps API using the following powershell script:
$listurl="https://onpremdomain/{ogr}/{proj}/_apis/release/definitions?api-version=6.0"

$PAT="Personal access token"

$base64AuthInfo= [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($PAT)"))

#get the releases' ids.
$result = Invoke-RestMethod -Uri $listurl -Headers @{Authorization = "Basic {0}" -f $base64AuthInfo} -Method get

#loop the ids to get each release's definition
foreach($release in $result.value){

#get each release's definition
 $definitionurl="https://onpremdomain/{ogr}/{proj}/_apis/release/definitions/$($release.id)?&api-version=6.0"

  $releaseDefinition = Invoke-RestMethod -Uri $definitionurl-Headers @{Authorization = "Basic {0}" -f $base64AuthInfo} -Method get

  #loop through each stage
  foreach( $environment in $releaseDefinition.environments){

     #loop through each tasks to find the task group
     foreach($task in $environment.deployPhases.workflowTasks){

       # change the 'taskId'  to the taskId of your task group
        if($task.taskId -eq "{taskId}"){

            $task.version = "2.*"  # update the taskgroup version to the newest version
       }
     }
  }

    $updateurl="https://onpremdomain/{ogr}/{proj}/_apis/release/definitions?api-version=6.0"

    # update the release definition
    Invoke-RestMethod -Uri $updateurl -Headers @{Authorization = "Basic {0}" -f $base64AuthInfo} -ContentType "application/json" -Method PUT -Body (convertto-json $releaseDefinition -Depth 100)
}

When Invoke-RestMethod in the last line is called I get the following error:
 Invoke-RestMethod : {"$id":"1","innerException":null,"message":"VS402903: The specified value is not convertible to type ReleaseDefinition. Make sure it is convertible to type ReleaseDefinition and
try again.","typeName":"Microsoft.VisualStudio.Services.ReleaseManagement.Data.Exceptions.InvalidRequestException, Microsoft.VisualStudio.Services.ReleaseManagement2.Data","typeKey":"InvalidRequestE
xception","errorCode":0,"eventId":3000}

Any idea why this error occurs?

A: REST API doc:
Get a list of release definitions.
Get a release definition.
Update a release definition.
Power shell script
$listurl="https://vsrm.dev.azure.com/{Org name}/{Project name}/_apis/release/definitions?api-version=6.0"
$PAT="{PAT}"
$base64AuthInfo= [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($PAT)"))

#get the releases' ids.
$result = Invoke-RestMethod -Uri $listurl -Headers @{Authorization = "Basic {0}" -f $base64AuthInfo} -Method get

write-host $result.value.id

#loop the ids to get each release's definition
foreach($release in $result.value){

#get each release's definition
$definitionurl="https://vsrm.dev.azure.com/{Org name}/{Project name}/_apis/release/definitions/$($release.id)?api-version=6.0"
#write-host $definitionurl
$releaseDefinition = Invoke-RestMethod -Uri $definitionurl -Headers @{Authorization = "Basic {0}" -f $base64AuthInfo} -Method get

  #loop through each stage
  foreach( $environment in $releaseDefinition.environments){

     #loop through each tasks to find the task group
     foreach($task in $environment.deployPhases.workflowTasks){
     write-host $task.taskId
       # change the 'taskId'  to the taskId of your task group
        if($task.taskId -eq "e213ff0f-5d5c-4791-802d-52ea3e7be1f1"){
            write-host $task.version
            $task.version = "1.*"  # update the taskgroup version to the newest version
            write-host $task.version
       }
     }
  }
    $updateurl="https://vsrm.dev.azure.com/{Org name}/{project name}/_apis/release/definitions?api-version=6.0"

    # update the release definition
    Invoke-RestMethod -Uri $updateurl -Headers @{Authorization = "Basic {0}" -f $base64AuthInfo} -ContentType "application/json" -Method PUT -Body (convertto-json $releaseDefinition -Depth 100)
}

Update
I found the issue, the second Invoke-RestMethod method is missing the space before the -Headers parameter, and the issue should be Invoke-RestMethod : A positional parameter cannot be found that accepts argument 'System.Collections.Hashtable'.

After adding a space before the parameter, it works, you could check the pic below.


text:
Q: How do I calculate the correct resistor, capacitor for a low pass circuit? I'm looking through an article on www.allaboutcircuits.com and www.electronics-tutorials.ws in an attempt to learn more about how low pass noise filtering on for example a circuit that needs to supply 3.3V would be designed.
I don't have an oscilloscope, and I am most certainly not a mathematical or electronics genius, this stuff is all to make these weaknesses stronger, by learning.
So in a circuit like the following:

...how does one calculate the correct capacitance to use, determine which direction they need to be hooked up, and whether to use polarised or non-polarised caps?
Would I rather need to hook up the Vin supply to determine what noise there is in the first place, and decide from there, what I want to make my cut off frequencies?
I tried simulating this in iCircuit, but with some capacitor values, the frequencies fluctuated, and the voltage on my circuit increased in a stepping sinusoidal wave manner, so i clearly have no idea what I am doing. ;)

A: The use of decoupling caps is hugely dependant on the circuit in question. Any circuitry that generates a lot of high-speed switching is going to generate a noisy EMC profile. FPGAs, microcontrollers and high-speed interfaces all perform a lot of high speed switching and so require decoupling caps.
Usually a device datasheet will specify recommended cap values, locations and even dialectrics. These values are usually chosen specifically for the device in question. Sometimes these caps are optional, to be added at the user's discretion based on surrounding circuitry. If a voltage regulator is going to be used in a noisy EMC environment, then the caps may be included, otherwise they may not be necessary (the datasheet will indicate this), however decoupling is generally good practise.
Often devices will have several caps in parallel of different values. Each cap filters up to a specific frequency based on the impedance (Z) of the circuit. The cut-off frequency is calculated as follows:
\$f_c = \dfrac{1}{2 \pi Z C}\$
However, the impedance of the circuit is the most difficult factor to calculate. It's based on your allowable noise margin and the amount of current that's going to be switched at once. This really useful TI application report gives details.
If you're building a classic first order low-pass RC circuit then the Z turns out to be the R value and the maths is a lot easier.
This is the reason why most ICs give recommended cap values, they've done all the maths for you. If you'd like a practical example, the application note above gives a nice example on how to calculate a required cap value.
In terms of testing, if you have a power supply on its own, you probably won't see much noise at all. It would be necessary to measure the power supply noise when you're using it to power a microcontroller or similar device and choose cap values based on what the application note for the device says. Also, give trial and error a try. Try different cap values and see what you get.

A: Filtering you need greatly depends on your input voltage source - if it's some crappy switching power supply from China (no big transformer) you probably might want to connect a LC "pi" or "t" filter (kinda more complicated stuff, you have to avoid resonance) or just put a ferite bead in series to atenuate high frequencies that pass right thru LM7805. Another way is to add a RC filter made from small (somewhat 10 ohm) resistor and a capacitor, corner frequency of this can be calculated by 1/(2*pi*R*C); this way is tricky too as you have to consider amount of current you will be drawing and voltage drop that will be developed over a resistor.
In particular circuit the capacitors can be considered to be acting in several different modes - one thing, they are shunting high frequencies to ground (capacitor acts as a resistor for high frequencies, higher the frequency, lower the resistance) another thing - they decouple the circuit making a "local energy storage" for momentuous current demands from the circuit this circuit is powering. And finally they could be considered as stabilising components for internal voltage regulation circuit in LM7805.
That beeing said, you don't really have to calculate values for this particular circuit. By "rule of the thumb" you just put a ceramic capacitor in the range from 100nF up 1uF (1uF ceramics are available and cheap already) - this cap acts as stabilising capacitor and shunts high frequencies. Parallel to that you usually put electrolytic capacitor of 10uF - 100uF it's positive terminal connected to greater potential rail (+5, +7.5) - this cap acts as a local energy storage, it's slow and does not perform greatly in high frequencies.
If you see short high spikes from a switching power supply, put a freite bead in series on the output (you have to choose one that can put thru the current you need)


text:
Q: Gödels incompleteness vs incompleteness This has been nagging me, and might be an unfit question, but still:
I've been taught that completeness of a theory $T$ means that for any sentence $\varphi$ in the language of the theory, we have either $T \vdash \varphi$ or $T \vdash \neg\varphi$.  If this property doesn't hold (so if there is some $\varphi$ that the theory says nothing about), we have an incomplete theory.
Now, copying from wikipedia, we have:

The first incompleteness theorem states that no consistent system of axioms whose theorems can be listed by an "effective procedure" (e.g., a computer program, but it could be any sort of algorithm) is capable of proving all truths about the relations of the natural numbers (arithmetic).

These two notions of completeness seem very far away from each other, and when I ask others that know more about this, they tell me that it's incompleteness in a different sense, and that it's too technical to cover briefly. So the question is:
Is there some difference between my understanding of incompleteness, and the one Gödel meant? And how do algorithms fit into all of this?
I want the 'philosphical' difference, not sketches of Gödel's proofs.
Thanks in advance.

A: Completeness of $T$ means that for every sentence $\varphi$ we have either $T\vdash\varphi$ or $T\vdash\neg\varphi$.
Gödel's incompleteness theorem shows that if $T$ is an effective theory that can express "enough" of arithmetic and does not prove any arithmetic falsehoods (which implies that it is consistent), then it cannot be complete in the above sense.
The theorem does this by showing that there is a true sentence that it cannot prove. Since we assume that the theory doesn't prove falsehoods, this means that the theory proves neither the Gödel sentence or its negation, which means that it is not complete.

A: Gödel (well, actually Rosser building on Gödel) showed that any consistent, recursively axiomatizable set of sentences in the language of arithmetic which contains a certain (very small) theory $T_0$ is not complete (in your sense, which is what "complete" means). In particular this means that no consistent recursively axiomatizable set of sentences in the language of arithmetic proves every true sentence of arithmetic (we don't need the "contains $T_0$" bit here).
Note, though, that (Rosser's improvement of) Gödel's theorem applies also to theories containing statements not true of $\mathbb{N}$ (such as "$PA$ is inconsistent," "Goodstein processes don't always terminate," etc.) - as long as they contain $T_0$!
What is $T_0$? Gödel's original proof explicitly set $T_0$ to be the system of Principia Mathematica; however, basically just by looking at the proof we can take $T_0$ to be the vastly, vastly weaker $I\Sigma_1$; this is a very small fragment of Peano arithmetic! With some work, $T_0$ can be weakened even further to Robinson's theory $Q$, and I believe even further is known.

So what about those assumptions? Here's why they can't be dropped:

*

*"Contains $T_0$:" consider the theory (generated by) "$\exists x\forall y(x=y)$." This theory is obviously consistent and complete and recursively axiomatized (in fact, decidable :P); but it doesn't contain, say, Robinson's $Q$. (Alternatively, it does contain a statement which is false.)

*"Recursively axiomatizable:" the true theory of arithmetic is certainly complete, and contains, well all of arithmetic; but it's not recursively axiomatizable.

A: Maybe it helps when you distinguish the syntactic version from the semantic version. So we have something like the following

Gödel's first incompleteness theorem (syntactic): Every logical system, which is consistent and strong enough to formalize PA, is negation incomplete.

which is the "original" one (well, to be precise you have to speak of the stronger notion of the so called $\omega$-consistency when it comes to Gödel, because Rosser contributed the rest) and

Gödel's first incompleteness theorem (semantic):  Every logical system, which is sound and strong enough to formalize PA, is incomplete.

The semantic version can be shown as a consequence of the undecidability of the halting problem, which connects proof theory and recursion (computability) theory.
Regards,
Heywood


text:
Q: How to specify Trust store and trust store type for Spark JDBC connection I am new to Spark and we are currently using the spark-java to create orc files from Oracle database. I was able to configure the connection with
sqlContext.read().jdbc(url,table,props)

However, I couldn't find any way in the properties to specify the trustStore or trustStoreType. Can someone help me about how to specify these properties?
I already tried populating the properties as
 props.put("trustStore", "<PATH_TO_SSO>");
 props.put("trustStoreType", "sso");

But it didn't work for me
Update1:
I have tried what user8371915 has suggested and also placed the sso file in both my executor nodes. I am still getting the following exception (abridged version)
oracle.net.ns.NetException: The Network Adapter could not establish the connection
    at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:470)
    at oracle.net.resolver.AddrResolution.resolveAndExecute(AddrResolution.java:506)
    at oracle.net.ns.NSProtocol.establishConnection(NSProtocol.java:595)
    at oracle.net.ns.NSProtocol.connect(NSProtocol.java:230)
    at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:1452)
    at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:496)
    ... 23 more
Caused by: oracle.net.ns.NetException: Unable to initialize ssl context.
    at oracle.net.nt.CustomSSLSocketFactory.getSSLSocketFactory(CustomSSLSocketFactory.java:325)
    at oracle.net.nt.TcpsNTAdapter.connect(TcpsNTAdapter.java:117)
    at oracle.net.nt.ConnOption.connect(ConnOption.java:159)
    at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:428)
    ... 28 more
Caused by: oracle.net.ns.NetException: Unable to initialize the trust store.
    at oracle.net.nt.CustomSSLSocketFactory.getTrustManagerArray(CustomSSLSocketFactory.java:413)
    at oracle.net.nt.CustomSSLSocketFactory.getSSLSocketFactory(CustomSSLSocketFactory.java:309)
    ... 31 more
Caused by: java.security.KeyStoreException: sso not found
    at java.security.KeyStore.getInstance(KeyStore.java:851)
    at oracle.net.nt.CustomSSLSocketFactory.getTrustManagerArray(CustomSSLSocketFactory.java:401)
    ... 32 more
Caused by: java.security.NoSuchAlgorithmException: sso KeyStore not available
    at sun.security.jca.GetInstance.getInstance(GetInstance.java:159)
    at java.security.Security.getImpl(Security.java:695)
    at java.security.KeyStore.getInstance(KeyStore.java:848)
    ... 33 more

A: First of all (credits go to Xephi for this answer) properties are javax.net.ssl.trustStore and javax.net.ssl.trustStoreType.
The second problem is that trustStore should be accessible on each executor node. Being able to access it from the driver is not enought.


text:
Q: How to make a mechanism of column configuration in tables on a website I use MSSQL, at the moment I was creating a new materialized view in the applications, which contained columns from several different tables. Of course, for such a view, I had to create objects for EFCore, provide a GET endpoint that, using OData, handled pagination, sorting, filtering, etc.
My question is, is there a way to give the user the ability to configure such a table (adding, removing columns), without having to rebuild and deploy the application?
It would be possible to configure such a table in the DB, so that the frontend would know what and what type of columns it should show. Only the possibility of changes in the DB, extension of the materialized view, configuration is at stake.
Anyone encountered something like this?


text:
Q: How to use lint-staged with jest --collectCoverageFrom I'm using lint-staged with Jest testing framework to test only changed files from last commit as described in this blog.
My configuration is as below:
"src/**/*.{ts}": [
  "prettier --write",
  "tslint --fix --project .",
  "jest --bail --findRelatedTests",
  "git add"
]

I also want to generate coverage-report for only changed files. To do this, I have to put list of changed files in multiple places.
jest --bail --findRelatedTests <spaceSeparatedListOfSourceFiles> --collectCoverageFrom=<glob>
Using lint-staged, how can I limit both test and coverage-report only for changed files?

A: I didn't know about lint-staged. I'll give it a try. I looked for this a while ago.
Have you tried?
"jest --bail --coverage --findRelatedTests",
Jest docs say that findRelatedTests can be used together with --coverage to include a test coverage for the source files, no duplicate --collectCoverageFrom arguments needed.
Should work but I haven't tried.

A: it works correctly when you define the collectCoverageFrom parameter as follows
--collectCoverageFrom="<rootDir>/src/components/Home/index.js"

for multiple files you can define each as above
--collectCoverageFrom="<rootDir>/src/components/Home/index.js" --collectCoverageFrom="<rootDir>/src/components/Home/utils.js"

or you can define it as a glob
--collectCoverageFrom="<rootDir>/src/components/Home/*"


text:
Q: How to get the size of a JavaScript object? I want to know the size occupied by a JavaScript object.
Take the following function:
function Marks(){
  this.maxMarks = 100;
}

function Student(){
  this.firstName = "firstName";
  this.lastName = "lastName";
  this.marks = new Marks();
}

Now I instantiate the student:
var stud = new Student();

so that I can do stuff like
stud.firstName = "new Firstname";

alert(stud.firstName);

stud.marks.maxMarks = 200;

etc.
Now, the stud object will occupy some size in memory. It has some data and more objects.
How do I find out how much memory the stud object occupies? Something like a sizeof() in JavaScript? It would be really awesome if I could find it out in a single function call like sizeof(stud).
I've been searching the Internet for months—couldn't find it (asked in a couple of forums—no replies).

A: Sometimes I use this to flag really big objects that might be going to the client from the server. It doesn't represent the in memory footprint.  It just gets you approximately what it'd cost to send it, or store it.
Also note, it's slow, dev only. But for getting an ballpark answer with one line of code it's been useful for me.
roughObjSize = JSON.stringify(bigObject).length;

A: I just wrote this to solve a similar (ish) problem. It doesn't exactly do what you may be looking for, ie it doesn't take into account how the interpreter stores the object.
But, if you are using V8, it should give you a fairly ok approximation as the awesome prototyping and hidden classes lick up most of the overhead.
function roughSizeOfObject( object ) {

    var objectList = [];

    var recurse = function( value )
    {
        var bytes = 0;

        if ( typeof value === 'boolean' ) {
            bytes = 4;
        }
        else if ( typeof value === 'string' ) {
            bytes = value.length * 2;
        }
        else if ( typeof value === 'number' ) {
            bytes = 8;
        }
        else if
        (
            typeof value === 'object'
            && objectList.indexOf( value ) === -1
        )
        {
            objectList[ objectList.length ] = value;

            for( i in value ) {
                bytes+= 8; // an assumed existence overhead
                bytes+= recurse( value[i] )
            }
        }

        return bytes;
    }

    return recurse( object );
}

A:
i want to know if my memory reduction efforts actually help in reducing memory

Following up on this comment, here's what you should do:
Try to produce a memory problem - Write code that creates all these objects and graudally increase the upper limit until you ran into a problem (Browser crash, Browser freeze or an Out-Of-memory error). Ideally you should repeat this experiment with different browsers and different operating system.
Now there are two options:
option 1 - You didn't succeed in producing the memory problem. Hence, you are worrying for nothing. You don't have a memory issue and your program is fine.
option 2- you did get a memory problem. Now ask yourself whether the limit at which the problem occurred is reasonable (in other words: is it likely that this amount of objects will be created at normal use of your code). If the answer is 'No' then you're fine. Otherwise you now know how many objects your code can create. Rework the algorithm such that it does not breach this limit.

A: Here's a slightly more compact solution to the problem:
const typeSizes = {
  "undefined": () => 0,
  "boolean": () => 4,
  "number": () => 8,
  "string": item => 2 * item.length,
  "object": item => !item ? 0 : Object
    .keys(item)
    .reduce((total, key) => sizeOf(key) + sizeOf(item[key]) + total, 0)
};

const sizeOf = value => typeSizes[typeof value](value);

A: This Javascript library sizeof.js does the same thing.
Include it like this

The sizeof function takes an object as a parameter and returns its approximate size in bytes. For example:
// define an object
var object =
    {
      'boolean' : true,
      'number'  : 1,
      'string'  : 'a',
      'array'   : [1, 2, 3]
    };

// determine the size of the object
var size = sizeof(object);

The sizeof function can handle objects that contain multiple references to other objects and recursive references.
Originally published here.

A: There is a NPM module to get object sizeof, you can install it with npm install object-sizeof
  var sizeof = require('object-sizeof');

  // 2B per character, 6 chars total => 12B
  console.log(sizeof({abc: 'def'}));

  // 8B for Number => 8B
  console.log(sizeof(12345));

  var param = {
    'a': 1,
    'b': 2,
    'c': {
      'd': 4
    }
  };
  // 4 one two-bytes char strings and 3 eighth-bytes numbers => 32B
  console.log(sizeof(param));

A: If your main concern is the memory usage of your Firefox extension, I suggest checking with Mozilla developers.
Mozilla provides on its wiki a list of tools to analyze memory leaks.

A: Chrome developer tools has this functionality. I found this article very helpful and does exactly what you want:
https://developers.google.com/chrome-developer-tools/docs/heap-profiling

A: I have re-factored the code in my original answer. I have removed the recursion and removed the assumed existence overhead.
function roughSizeOfObject( object ) {

    var objectList = [];
    var stack = [ object ];
    var bytes = 0;

    while ( stack.length ) {
        var value = stack.pop();

        if ( typeof value === 'boolean' ) {
            bytes += 4;
        }
        else if ( typeof value === 'string' ) {
            bytes += value.length * 2;
        }
        else if ( typeof value === 'number' ) {
            bytes += 8;
        }
        else if
        (
            typeof value === 'object'
            && objectList.indexOf( value ) === -1
        )
        {
            objectList.push( value );

            for( var i in value ) {
                stack.push( value[ i ] );
            }
        }
    }
    return bytes;
}

A: Many thanks to everyone that has been working on code for this!
I just wanted to add that I've been looking for exactly the same thing, but in my case it's for managing a cache of processed objects to avoid having to re-parse and process objects from ajax calls that may or may not have been cached by the browser. This is especially useful for objects that require a lot of processing, usually anything that isn't in JSON format, but it can get very costly to keep these things cached in a large project or an app/extension that is left running for a long time.
Anyway, I use it for something something like:
var myCache = {
    cache: {},
    order: [],
    size: 0,
    maxSize: 2 * 1024 * 1024, // 2mb

    add: function(key, object) {
        // Otherwise add new object
        var size = this.getObjectSize(object);
        if (size > this.maxSize) return; // Can't store this object

        var total = this.size + size;

        // Check for existing entry, as replacing it will free up space
        if (typeof(this.cache[key]) !== 'undefined') {
            for (var i = 0; i < this.order.length; ++i) {
                var entry = this.order[i];
                if (entry.key === key) {
                    total -= entry.size;
                    this.order.splice(i, 1);
                    break;
                }
            }
        }

        while (total > this.maxSize) {
            var entry = this.order.shift();
            delete this.cache[entry.key];
            total -= entry.size;
        }

        this.cache[key] = object;
        this.order.push({ size: size, key: key });
        this.size = total;
    },

    get: function(key) {
        var value = this.cache[key];
        if (typeof(value) !== 'undefined') { // Return this key for longer
            for (var i = 0; i < this.order.length; ++i) {
                var entry = this.order[i];
                if (entry.key === key) {
                    this.order.splice(i, 1);
                    this.order.push(entry);
                    break;
                }
            }
        }
        return value;
    },

    getObjectSize: function(object) {
        // Code from above estimating functions
    },
};

It's a simplistic example and may have some errors, but it gives the idea, as you can use it to hold onto static objects (contents won't change) with some degree of intelligence. This can significantly cut down on any expensive processing requirements that the object had to be produced in the first place.

A: The accepted answer does not work with Map, Set, WeakMap and other iterable objects. (The package object-sizeof, mentioned in other answer, has the same problem).
Here's my fix
export function roughSizeOfObject(object) {
  const objectList = [];
  const stack = [object];
  const bytes = [0];
  while (stack.length) {
    const value = stack.pop();
    if (value == null) bytes[0] += 4;
    else if (typeof value === 'boolean') bytes[0] += 4;
    else if (typeof value === 'string') bytes[0] += value.length * 2;
    else if (typeof value === 'number') bytes[0] += 8;
    else if (typeof value === 'object' && objectList.indexOf(value) === -1) {
      objectList.push(value);
      if (typeof value.byteLength === 'number') bytes[0] += value.byteLength;
      else if (value[Symbol.iterator]) {
        // eslint-disable-next-line no-restricted-syntax
        for (const v of value) stack.push(v);
      } else {
        Object.keys(value).forEach(k => {
           bytes[0] += k.length * 2; stack.push(value[k]);
        });
      }
    }
  }
  return bytes[0];
}

It also includes some other minor improvements: counts keys storage and works with ArrayBuffer.

A: This is a hacky method, but i tried it twice with different numbers and it seems to be consistent.
What you can do is to try and allocate a huge number of objects, like one or two million objects of the kind you want. Put the objects in an array to prevent the garbage collector from releasing them (note that this will add a slight memory overhead because of the array, but i hope this shouldn't matter and besides if you are going to worry about objects being in memory, you store them somewhere). Add an alert before and after the allocation and in each alert check how much memory the Firefox process is taking. Before you open the page with the test, make sure you have a fresh Firefox instance. Open the page, note the memory usage after the "before" alert is shown. Close the alert, wait for the memory to be allocated. Subtract the new memory from the older and divide it by the amount of allocations. Example:
function Marks()
{
  this.maxMarks = 100;
}

function Student()
{
  this.firstName = "firstName";
  this.lastName = "lastName";
  this.marks = new Marks();
}

var manyObjects = new Array();
alert('before');
for (var i=0; i<2000000; i++)
    manyObjects[i] = new Student();
alert('after');

I tried this in my computer and the process had 48352K of memory when the "before" alert was shown. After the allocation, Firefox had 440236K of memory. For 2million allocations, this is about 200 bytes for each object.
I tried it again with 1million allocations and the result was similar: 196 bytes per object (i suppose the extra data in 2mill was used for Array).
So, here is a hacky method that might help you. JavaScript doesn't provide a "sizeof" method for a reason: each JavaScript implementaion is different. In Google Chrome for example the same page uses about 66 bytes for each object (judging from the task manager at least).

A: The Google Chrome Heap Profiler allows you to inspect object memory use.
You need to be able to locate the object in the trace which can be tricky. If you pin the object to the Window global, it is pretty easy to find from the "Containment" listing mode.
In the attached screenshot, I created an object called "testObj" on the window. I then located in the profiler (after making a recording) and it shows the full size of the object and everything in it under "retained size".
More details on the memory breakdowns.

In the above screenshot, the object shows a retained size of 60. I believe the unit is bytes here.

A: Having the same problem. I searched on Google and I want to share with stackoverflow community this solution.
Important:

I used the function shared by Yan Qing on github
  https://gist.github.com/zensh/4975495

function memorySizeOf(obj) {
    var bytes = 0;

    function sizeOf(obj) {
        if(obj !== null && obj !== undefined) {
            switch(typeof obj) {
            case 'number':
                bytes += 8;
                break;
            case 'string':
                bytes += obj.length * 2;
                break;
            case 'boolean':
                bytes += 4;
                break;
            case 'object':
                var objClass = Object.prototype.toString.call(obj).slice(8, -1);
                if(objClass === 'Object' || objClass === 'Array') {
                    for(var key in obj) {
                        if(!obj.hasOwnProperty(key)) continue;
                        sizeOf(obj[key]);
                    }
                } else bytes += obj.toString().length * 2;
                break;
            }
        }
        return bytes;
    };

    function formatByteSize(bytes) {
        if(bytes < 1024) return bytes + " bytes";
        else if(bytes < 1048576) return(bytes / 1024).toFixed(3) + " KiB";
        else if(bytes < 1073741824) return(bytes / 1048576).toFixed(3) + " MiB";
        else return(bytes / 1073741824).toFixed(3) + " GiB";
    };

    return formatByteSize(sizeOf(obj));
};

var sizeOfStudentObject = memorySizeOf({Student: {firstName: 'firstName', lastName: 'lastName', marks: 10}});
console.log(sizeOfStudentObject);

What do you think about it?

A: Sorry I could not comment, so I just continue the work from tomwrong.
This enhanced version will not count object more than once, thus no infinite loop.
Plus, I reckon the key of an object should be also counted, roughly.
function roughSizeOfObject( value, level ) {
    if(level == undefined) level = 0;
    var bytes = 0;

    if ( typeof value === 'boolean' ) {
        bytes = 4;
    }
    else if ( typeof value === 'string' ) {
        bytes = value.length * 2;
    }
    else if ( typeof value === 'number' ) {
        bytes = 8;
    }
    else if ( typeof value === 'object' ) {
        if(value['__visited__']) return 0;
        value['__visited__'] = 1;
        for( i in value ) {
            bytes += i.length * 2;
            bytes+= 8; // an assumed existence overhead
            bytes+= roughSizeOfObject( value[i], 1 )
        }
    }

    if(level == 0){
        clear__visited__(value);
    }
    return bytes;
}

function clear__visited__(value){
    if(typeof value == 'object'){
        delete value['__visited__'];
        for(var i in value){
            clear__visited__(value[i]);
        }
    }
}

roughSizeOfObject(a);

A: function sizeOf(parent_data, size)
{
    for (var prop in parent_data)
    {
        let value = parent_data[prop];

        if (typeof value === 'boolean')
        {
            size += 4;
        }
        else if (typeof value === 'string')
        {
            size += value.length * 2;
        }
        else if (typeof value === 'number')
        {
             size += 8;
        }
        else
        {
            let oldSize = size;
            size += sizeOf(value, oldSize) - oldSize;
        }
    }

    return size;
}

function roughSizeOfObject(object)
{
    let size = 0;
    for each (let prop in object)
    {
        size += sizeOf(prop, 0);
    } // for..
    return size;
}

A: I use Chrome dev tools' Timeline tab, instantiate increasingly large amounts of objects, and get good estimates like that. You can use html like this one below, as boilerplate, and modify it to better simulate the characteristics of your objects (number and types of properties, etc...). You may want to click the trash bit icon at the bottom of that dev tools tab, before and after a run.

    Quantifier:
    <input id="quantifier" style="color:green;" type="text"></input>
    <button onclick="scaffold()">Scaffold</button>
    <button onclick="start()">Start</button>
    <button onclick="tearDown()">Clean</button>

Instantiating 2 million objects of just one property each (as in this code above) leads to a rough calculation of 50 bytes per object, on my Chromium, right now. Changing the code to create a random string per object adds some 30 bytes per object, etc.
Hope this helps.

A: If you need to programatically check for aprox. size of objects you can also check this library http://code.stephenmorley.org/javascript/finding-the-memory-usage-of-objects/ that I have been able to use for objects size.
Otherwise I suggest to use the Chrome/Firefox Heap Profiler.

A: Building upon the already compact solution from @Dan, here's a self-contained function version of it. Variable names are reduced to single letters for those who just want it to be as compact as possible at the expense of context.

const ns = {};
ns.sizeof = function(v) {
  let f = ns.sizeof, //this needs to match the name of the function itself, since arguments.callee.name is defunct
    o = {
      "undefined": () => 0,
      "boolean": () => 4,
      "number": () => 8,
      "string": i => 2 * i.length,
      "object": i => !i ? 0 : Object
        .keys(i)
        .reduce((t, k) => f(k) + f(i[k]) + t, 0)
    };
  return o[typeof v](v);
};

ns.undef;
ns.bool = true;
ns.num = 1;
ns.string = "Hello";
ns.obj = {
  first_name: 'John',
  last_name: 'Doe',
  born: new Date(1980, 1, 1),
  favorite_foods: ['Pizza', 'Salad', 'Indian', 'Sushi'],
  can_juggle: true
};

console.log(ns.sizeof(ns.undef));
console.log(ns.sizeof(ns.bool));
console.log(ns.sizeof(ns.num));
console.log(ns.sizeof(ns.string));
console.log(ns.sizeof(ns.obj));
console.log(ns.sizeof(ns.obj.favorite_foods));

A: I had problems with the above answer with an ArrayBuffer.
After checking the documentation, I found that ArrayBuffer has a byteLength property which tells me exactly what I need, hence:

function sizeOf(data)
{
    if (typeof(data) === 'object')
    {
        if (data instanceof ArrayBuffer)
        {
            return data.byteLength;
        }
        // other objects goes here
    }
    // non-object cases goes here
}

console.log(sizeOf(new ArrayBuffer(15))); // 15

Reference:

*

*https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/byteLength

A: I know this is absolutely not the right way to do it, yet it've helped me a few times in the past to get the approx object file size:
Write your object/response to the console or a new tab, copy the results to a new notepad file, save it, and check the file size. The notepad file itself is just a few bytes, so you'll get a fairly accurate object file size.

A: I believe you forgot to include 'array'.
  typeOf : function(value) {
        var s = typeof value;
        if (s === 'object')
        {
            if (value)
            {
                if (typeof value.length === 'number' && !(value.propertyIsEnumerable('length')) && typeof value.splice === 'function')
                {
                    s = 'array';
                }
            }
            else
            {
                s = 'null';
            }
        }
        return s;
    },

   estimateSizeOfObject: function(value, level)
    {
        if(undefined === level)
            level = 0;

        var bytes = 0;

        if ('boolean' === typeOf(value))
            bytes = 4;
        else if ('string' === typeOf(value))
            bytes = value.length * 2;
        else if ('number' === typeOf(value))
            bytes = 8;
        else if ('object' === typeOf(value) || 'array' === typeOf(value))
        {
            for(var i in value)
            {
                bytes += i.length * 2;
                bytes+= 8; // an assumed existence overhead
                bytes+= estimateSizeOfObject(value[i], 1)
            }
        }
        return bytes;
    },

   formatByteSize : function(bytes)
    {
        if (bytes < 1024)
            return bytes + " bytes";
        else
        {
            var floatNum = bytes/1024;
            return floatNum.toFixed(2) + " kb";
        }
    },


text:
Q: Add powerpoint template preview in html I'm sorry I'm new to this. I have been looking for a solution for this, but I can't find any.I want to add into my web page the preview of the powerpoint templates.
These powerpoint templates are uploaded and after the upload, it is supposed to display its preview in the web.
Thank you!

A: One way to do this is to add them to your google docs and then use:
<iframe src="http://docs.google.com/gview?url=http://www.yourwebsite.com/powerpoint.ppt&embedded=true" style="width:600px; height:500px;" frameborder="0"></iframe>


text:
Q: how to remove ' from string Im trying to use the TRIM command in SQL to Remove special characters from a string. thing is i cant seem to figure out how to remove the ' character like how when people use it in their surname.
e.g O'Reilly
in order to remove a character i have to quote it, but how can put in quotes or identify the character ' when it is used for quoting.

A: You want to use replace() and not trim().  Then, the escaping of single quotes requires doubling it, plus the outer single quotes.  So:
replace(name, '''', '')
---------------^^  escaped single quote
--------------^--^ string delimiter for the single quote character

A: Use Replace function to replace that character (').
replace(name,"'","");
Link 1
Link 2


text:
Q: How can I multiply an HTML character entity reference or  ? I would like to draw a rectangle with a function in JavaScript, and I need to multiply the HTML character entity reference   to draw the spaces between the sides.
Can I save the character entity reference on a variable and then multiply it like in Python?
function drawRectangle(side, figure) {
    var spaces = " ";
    for (var i=0; i < side; i++) {
        document.write(figure);
    }
    for (var i=0; i< side-2; i++) {
        document.write(figure + spaces*side + figure);
    }
    document.write("
");
    for (var i=0; i < side; i++) {
        document.write(figure);
    }
}

A:   isn't a tag. It's a character entity reference.
To do exactly what you're asking, you're going to want to "repeat" the string, not multiply it. If you're in an environment which supports it, you can use the repeat function.

var input = ' ';
var output = input.repeat(3);
console.log(output);

If your environment does not support it, you can write one of your own.

function repeatStr(str, count) {
  return new Array(count + 1).join(str);
}

var input = ' ';
var output = repeatStr(input, 3);
console.log(output);

Note that you should really avoid using document.write and what you're trying to do is likely easier to do with CSS.

body {
  background: #000;
}
div {
  width: 100px;
  height: 100px;
  background: #0F0;
  /* This will move it to the right */
  margin-left: 4em;
}

A: Use .repeat():
function drawRectangle(side, figure){
  var spaces = " ";
  for (var i=0; i < side; i++) {
    document.write(figure);
  }
  for (var i=0; i< side-2; i++){
    document.write(figure + spaces.repeat(side) + figure);
  }
  document.write("
");
  for (var i=0; i < side; i++) {
    document.write(figure);
  }
}

Note: this may not be supported in all browsers, so you can use the polyfill provided by MDN, here.


text:
Q: SaltStack: Execute `systemctl --system daemon-reload` if service file was changed We deploy and change system service files via SaltStack.
For example, if file /etc/systemd/system/superfoo.service gets changed, then systemd emits this warning:
Warning: Unit file of superfoo.service changed on disk,
         'systemctl --system daemon-reload' recommended.

How to automate this with salt-stack?

A: I'd like to provide more complete solution although @MaksaSila did answer first.
You just need a cmd.run that'll handle file change, I'm using similar approach:
# sample.sls

systemd-reload:
  cmd.run:
   - name: systemctl --system daemon-reload
   - onchanges:
     - file: superbar.service

superbar.service:
  file.managed:
    - name: /etc/systemd/system/superbar.service

superfoo.service:
  file.managed:
    - name: /etc/systemd/system/superfoo.service
    - onchanges_in:
       - cmd: systemd-reload

The latter approach will allow you to split the systemd part and the service part into different SLS files (don't forget to include systemd for every sls file you do onchanges_in in).
See this manual page to get more details on the state relations and dependencies.

A: @jollyroger's answer is good for version < 0.15.0
Starting from 0.15.0, we can make use of systemd_service.systemctl_reload:
https://docs.saltstack.com/en/latest/ref/modules/all/salt.modules.systemd_service.html#salt.modules.systemd_service.systemctl_reload
superbar.service
  file.managed:
    - name: /etc/systemd/system/superbar.service
  module.run:
    - name: service.systemctl_reload
    - onchanges:
      - file: /etc/systemd/system/superbar.service

I believe this greatly simplifies the code.
[Edit]
The directive "systemctl_reload" might look like systemctl reload, but it executes systemctl --system daemon-reload underneath.
https://github.com/saltstack/salt/blob/9bbbd3629418b2b086360f5b303323ec55ca0315/salt/modules/systemd_service.py#L377-L399
Saltstack doc also clearly states that it

"Reloads systemctl, an action needed whenever unit files are updated."

A: I would suggest after coping this file to run this in your state:
update-systemd:
  cmd.run:
    - name: systemctl --system daemon-reload


text:
Q: why am i getting errors while attempting to build my signed APK I was just trying to create a signed APK and saw THIS tutorial online. i followed all the steps exactly in the tutorial , but i still get the following error in the messages tab .
Error :
Error:A problem occurred configuring project ':app'.
> Could not resolve all dependencies for configuration ':app:_debugCompile'.
   > Could not find com.android.support:appcompat-v7:22.2.0.
     Searched in the following locations:
         https://jcenter.bintray.com/com/android/support/appcompat-v7/22.2.0/appcompat-v7-22.2.0.pom
         https://jcenter.bintray.com/com/android/support/appcompat-v7/22.2.0/appcompat-v7-22.2.0.jar
         file:/C:/Users/Silambu/AppData/Local/Android/sdk/extras/android/m2repository/com/android/support/appcompat-v7/22.2.0/appcompat-v7-22.2.0.pom
         file:/C:/Users/Silambu/AppData/Local/Android/sdk/extras/android/m2repository/com/android/support/appcompat-v7/22.2.0/appcompat-v7-22.2.0.jar
         file:/C:/Users/Silambu/AppData/Local/Android/sdk/extras/google/m2repository/com/android/support/appcompat-v7/22.2.0/appcompat-v7-22.2.0.pom
         file:/C:/Users/Silambu/AppData/Local/Android/sdk/extras/google/m2repository/com/android/support/appcompat-v7/22.2.0/appcompat-v7-22.2.0.jar
     Required by:
         Droidone:app:unspecified

if i don't generate a signed APK , android studio does't build my project and run it, so i really need to build a signed APK. So why am i getting this error and how do i solve this ?
EDIT: Build gradle files .
apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"

    defaultConfig {
        applicationId "com.example.gautam.droidone"
        minSdkVersion 8
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
//        testPackageName "com.example.gautam.droidone.tests.MainActivityTest"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.2.0'
}

Other gradle file:
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.2.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}


text:
Q: Are the classes "ResultSet" and "executeQuery" database-vendor-specific? I came up with this question when working on establishing a connection between Oracle and JDBC

A: ResultSet is an interface (not a class). The idea is that the class implementing the interface will be vendor specific but the interface is common.


text:
Q:  Must specify extras for registerAdNetworkExtras:? I'm receiving a message in Xcode's debug area stating :
 Must specify extras for registerAdNetworkExtras:
I didn't get this error yesterday but today I'm getting it on debug area out of nowhere. I didn't change my code in any way. Is this an error on google's end? Why am I receiving this message?
My code to get AdMob banner:
   adMobView = [[GADBannerView alloc] initWithAdSize:kGADAdSizeSmartBannerPortrait];

  adMobView.adUnitID =  @"unit-id";
  adMobView.rootViewController = self;
  GADRequest *request =[GADRequest request];
  request.testDevices = @[ @"testdeviceID" ];
  [adMobView loadRequest:request];

A: Here i found the right answer, is a last version SDK issue, that don't have effect on the mediation/ad serving functionality. Hope this help.
More info: Ram Parameswaran (Mobile SDK Team) say: "This issue does not affect functionality and can be ignored for the time being. Changes will be made to address the issue and pushed out in a future release."


text:
Q: Get RadioButtons By Row - Javascript I have to get the radiobuttons row by row, but this query gets all the radios in the table.
function Check() {
var table = document.getElementById("tblMain");
for (var i = 0, row; row = table.rows[i]; i++) {
var arrRadios = new Array();
arrRadios = this.document.getElementsByName("radio");
var len = arrRadios.length; //it gives 6 here, when I want 3
}
}

                <input type="radio" name="radio" />1)
                <input type="radio" name="radio" />2)
                <input type="radio" name="radio" />3)

                <input type="radio" name="radio" />1)
                <input type="radio" name="radio" />2)
                <input type="radio" name="radio" />3)

    <asp:Button ID="btn" runat="server"
      OnClientClick="return Check()" value="click"/>

Please suggest a solution by Javascript

A: Why not do this:
  var table = document.getElementById("tblMain");
  for (var i = 0, row; row = table.rows[i]; i++) {
      var arrRadios = new Array();
      arrRadios = document.querySelectorAll('#tblMain tr:nth-child(' + (i+1) + ') input[type=radio]');
      var len = arrRadios.length;
  }

This might not work, if your browser isn't a reasonably current version.

A: Althought there is different solution. Here is one close to what you have started
function Check() {
var table = document.getElementById("tblMain");
for (var i = 0, row; row = table.rows[i]; i++) {
var arrRadios = new Array();
arrRadios = this.document.getElementsByName("radio_"+i);
var len = arrRadios.length; //it gives 6 here, when I want 3
}
}

                <input type="radio" name="radio_0" />1)
                <input type="radio" name="radio_0" />2)
                <input type="radio" name="radio_0" />3)

                <input type="radio" name="radio_1" />1)
                <input type="radio" name="radio_1" />2)
                <input type="radio" name="radio_1" />3)

    <asp:Button ID="btn" runat="server"
      OnClientClick="return Check()" value="click"/>

There is two changes : rename the radio with by added _ + the number of the row
Then il your for loop add the same thing to call the radio on the row.


text:
Q: Laravel error Class 'App\Http\Controllers\App\Model' not found I am having troubles using eloquent with Laravel.
I am getting an error which I found a lot here on SO but didn't find a solution to it.
Class 'App\Http\Controllers\App\Activity' not found

After searching in the asked questions, it appears everyone omitted the use App/'Model' statement, but I included it in my controller, still getting this error, and I don't know what I am doing wrong
My model:
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Activity extends Model
{
    public function covers()
    {
        return $this->belongsToMany('App\Cover');
    }

    public function languages()
    {
        return $this->belongsToMany('App\Language');
    }

}

My controller:
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Activity;

class ActivityController extends Controller
{
    public function get_wixer_activities($wid){
        $activities = App\Activity::all();
        dd($activities);
    }
}

I am using Laravel 5.6

A: Because you are importing the Activity class here:
use App\Activity;

It means you can use the Activity class like this:
$activities = Activity::all();

And you don't need the App\Activity.