text:
Q: Custom LINQ extension method throws VerificationException: type argument IEnumerable`1[entity]' violates constraint of type parameter 'TCollection' I've got some entities that looks like this:
public class MyEvent
{
    // ...
    public IEnumerable<MyEncounter> Encounters { get; set; } // Navigation property
    // ...
}

public class MyEncounter
{
    public Guid MyEventID { get; set; }
    public MyEvent MyEvent { get; set; }  // Navigation property

    public Guid? MySpecialProperty { get; set; }

    public int Status { get; set; }
    //...
}

I want to add an extension method to do some filtering of the Encounters collection on MyEvent and return the value of MySpecialProperty for one of the MyEncounter instances (specifically, the instance where status = 1).
So, I wrote my extension method:
public static class MyExtensions
{
    public static Guid? GetMySpecialProperty(this IEnumerable<MyEncounter> encounters)
    {
        return encounters.Where(e => e.Status == 1)
                         .Select(e => e.MySpecialProperty)
                         .FirstOrDefault();
    }
}

Now, I'm ready to use my extension method. I've simplified this dramatically to remove stuff that should be irrelevant:
var qry = MyEventsContext.
    .Where(<some logic>)
    .Select(x => new MyViewModel
    {
        SpecialPropValue = x.Encounters.GetMySpecialProperty()
    });

This compiles as expected, and I'm ready to run the query:
IList<MyViewModel> items = await qry.ToListAsync();

This is where things go wrong. As soon as .ToListAsync() is executed, I get this exception:
VerificationException: Method Microsoft.EntityFrameworkCore.Query.RelationalShapedQueryCompilingExpressionVisitor+CustomShaperCompilingExpressionVisitor.PopulateCollection: type argument 'System.Collections.Generic.IEnumerable`1[<fully qualified name of MyEncounter>]' violates the constraint of type parameter 'TCollection'.

The inner exception is only slightly more detailed:
ArgumentException: GenericArguments[0], 'System.Collections.Generic.IEnumerable`1[<fully qualified name of MyEncounter>]', on 'Void PopulateCollection[TCollection,TElement,TRelatedEntity](Int32, Microsoft.EntityFrameworkCore.Query.QueryContext, System.Data.Common.DbDataReader, Microsoft.EntityFrameworkCore.Query.Internal.ResultCoordinator, System.Func`3[Microsoft.EntityFrameworkCore.Query.QueryContext,System.Data.Common.DbDataReader,System.Object[]], System.Func`3[Microsoft.EntityFrameworkCore.Query.QueryContext,System.Data.Common.DbDataReader,System.Object[]], System.Func`3[Microsoft.EntityFrameworkCore.Query.QueryContext,System.Data.Common.DbDataReader,System.Object[]], System.Func`5[Microsoft.EntityFrameworkCore.Query.QueryContext,System.Data.Common.DbDataReader,Microsoft.EntityFrameworkCore.Query.Internal.ResultContext,Microsoft.EntityFrameworkCore.Query.Internal.ResultCoordinator,TRelatedEntity])' violates the constraint of type 'TCollection'.

What is this exception telling me, and is there a way to resolve it? As far as I can tell, I've created my extension method correctly.

Interestingly, if I create an extension method to just get the MyEncounters that match the criteria and do the Select/FirstOrDefault in the query, everything works as expected:
// Extension method
public static IEnumerable<MyEncounter> GetMySpecialEncounters(this IEnumerable<MyEncounter> encounters)
{
    return encounters.Where(e => e.Status == 1)
}

// Query
var qry = MyEventsContext.
    .Where(<some logic>)
    .Select(x => new MyViewModel
    {
        SpecialPropValue = x.Encounters.GetMySpecialEncounters()
                                       .Select(x => x.MySpecialProperty)
                                       .FirstOrDefault()
    });

I was mistaken about the above. Using that extension method in the query results in this exception:
When called from 'VisitLambda', rewriting a node of type 'System.Linq.Expressions.ParameterExpression' must return a non-null value of the same type

What does work is doing all the logic inside the query, with no extension method at all:
// Query
var qry = MyEventsContext.
    .Where(<some logic>)
    .Select(x => new MyViewModel
    {
        SpecialPropValue = x.Encounters.Where(e => e.Status == 1)
                                       .Select(x => x.MySpecialProperty)
                                       .FirstOrDefault()
    });

A: Invoking ToList on the x.Encounters works for me in 3.1 EF Core (though AsEnumerable() and ToArray() does not):
.Select(x => new MyViewModel
{
    SpecialPropValue = x.Encounters.ToList().GetMySpecialProperty()
});

The reason for such behavior is typing issue - CustomShaperCompilingExpressionVisitor.VisitExtension method tries to handle populating collection and tries to build expression tree to call PopulateCollection method which has generic constraint for collection type to be ICollection<TElement> but determines IEnumerable<TElement> and passes it to MakeGenericMethod call which fails cause IEnumerable is not ICollection (it is vice versa actually).


text:
Q: Как использовать счетчик времени для подсчета очков в Python? Пишу небольшую игру в Python 3.7. Понадобилось использовать время для подсчета очков. Т.е. каждую секунду с момента запуска программы к счету должно прибавляться одно очко. Имеется данный код, который нужно доработать до рабочего состояния или предложить альтернативные способы решения проблемы
score = 0

def label2():
    global SCORElabel
    SCORElabel = c.create_text(350, 10, width=300, text="Score: " + str(score), fill='#fff', anchor=NW)

def scoremeter():
    global score
    game_time = time.clock()
    if game_time//1==0:
        score+=1
        c.delete(SCORElabel)
        label2()
        scoremeter()
    else:
        scoremeter()

A: в tkinter есть встроенная функция tkinter.Tk.after("second", func) которая позволяет повторять функцию раз в определенное кол-во секунд пример ниже
import tkinter as tk

class Main(tk.Tk):
    score = 0

    def __init__(self):
        super(Main, self).__init__()
        self.label = tk.Label(self, text="Количество очков 0")
        self.label.pack()
        self.score_plus()

    def score_plus(self):
        self.score += 5
        self.label["text"] = "Количество очков {}".format(self.score)
        self.after(1000, self.score_plus)

if __name__ == "__main__":
    Main().mainloop()

redpajama_set_name: RedPajamaStackExchange


text:
Q: (Keras) Does the TensorBoard callback work for a recurrent network with return_state on? I defined a recurrent network with return_state set to True:
import numpy as np
from tensorflow.python import keras

data, targets = np.ones((4, 2, 3)), np.zeros((4, 2, 3))

input_shape = data.shape

input_1 = keras.layers.Input(batch_shape=(None,)+input_shape[1:])

recurrent_1, _, state = keras.layers.LSTM(units=input_shape[-1],
                                          input_shape=input_shape[1:],
                                          return_sequences=True,
                                          return_state=True)(input_1)

model = keras.models.Model(inputs=[input_1], outputs=[recurrent_1])
model.compile(loss='mean_squared_error',
              optimizer='RMSprop',
              metrics=['accuracy'])

tensorboard_callback = keras.callbacks.TensorBoard(log_dir='/', histogram_freq=1, write_graph=True,
                                                   write_grads=True, write_images=False)

model.fit(data, targets, validation_split=0.25, callbacks=[tensorboard_callback])

The fit() call failed with this error:
Traceback (most recent call last):
  File "/home/joshuaf/PycharmProjects/skyline/catkin_ws/src/learning/src/functional_recurrent_tensorboard.py", line 23, in <module>
    model.fit(data, targets, validation_split=0.25, callbacks=[tensorboard_callback])
  File "/home/joshuaf/PycharmProjects/skyline/venv/local/lib/python2.7/site-packages/tensorflow/python/keras/engine/training.py", line 1348, in fit
    validation_steps=validation_steps)
  File "/home/joshuaf/PycharmProjects/skyline/venv/local/lib/python2.7/site-packages/tensorflow/python/keras/engine/training_arrays.py", line 157, in fit_loop
    callbacks.set_model(callback_model)
  File "/home/joshuaf/PycharmProjects/skyline/venv/local/lib/python2.7/site-packages/tensorflow/python/keras/callbacks.py", line 70, in set_model
    callback.set_model(model)
  File "/home/joshuaf/PycharmProjects/skyline/venv/local/lib/python2.7/site-packages/tensorflow/python/keras/callbacks.py", line 762, in set_model
    tf_summary.histogram('{}_out'.format(layer.name), layer.output)
  File "/home/joshuaf/PycharmProjects/skyline/venv/local/lib/python2.7/site-packages/tensorflow/python/summary/summary.py", line 187, in histogram
    tag=tag, values=values, name=scope)
  File "/home/joshuaf/PycharmProjects/skyline/venv/local/lib/python2.7/site-packages/tensorflow/python/ops/gen_logging_ops.py", line 283, in histogram_summary
    "HistogramSummary", tag=tag, values=values, name=name)
  File "/home/joshuaf/PycharmProjects/skyline/venv/local/lib/python2.7/site-packages/tensorflow/python/framework/op_def_library.py", line 528, in _apply_op_helper
    (input_name, err))
ValueError: Tried to convert 'values' to a tensor and failed. Error: Shapes must be equal rank, but are 3 and 2
    From merging shape 0 with other shapes. for 'lstm_out/packed' (op: 'Pack') with input shapes: [?,2,3], [?,3], [?,3].

I assume the extra two shapes are the hidden state output and cell state, as explained here https://machinelearningmastery.com/return-sequences-and-return-states-for-lstms-in-keras/.
Does that mean the TensorBoard callback simply does not work with layers that return their state? I'm using Tensorflow 1.9 and Keras 2.1.6.


text:
Q: How do I get my position by use openstreetmap this is my code to get my position:
IMyLocationProvider ilp = new IMyLocationProvider() {
        @Override
        public void stopLocationProvider() {
        }
        @Override
        public boolean startLocationProvider(IMyLocationConsumer arg0) {
            return false;
        }
        @Override
        public Location getLastKnownLocation() {
            return null;
        }
    };
MyLocationNewOverlay myLocationOverlay = new MyLocationNewOverlay(getApplicationContext(), ilp,mMapView);
mMapView.getOverlays().add(myLocationOverlay);
myLocationOverlay.enableMyLocation(ilp);
myLocationOverlay.enableFollowLocation();

but result is the screen turned blue and no map,where is the mistake?


text:
Q: Using Sagemath to check if a ring is integrally closed I was playing around in Sage earlier today, and I can't seem to figure out how to check whether the localization of an order in a number field is integrally closed. I'm fairly new to Sage, so I'm a little confused as to what the issue is. My code is below:
K.<i> = NumberField(x^2 + 1)
O = K.order(2*i)
Op = O.localization(2 + 2*i)
Op.is_integrally_closed()

This gives me a NotImplementedError saying that IntegerModRing_generic_with_category object has no attribute is_integrally_closed. I can see, however, that the object Op has type sage.rings.localization.Localization_with_category. I can't find the class sage.rings.localization.Localization_with_category in the documentation, but in sage.rings.localization, the base is listed as sage.rings.ring.IntegralDomain, which has a method is_integrally_closed() listed.
I know how to check the math here - I'm just trying to figure out how to get Sage to check this for me, and better understand how Sage categories, parents, classes, etc. work.
P.S. I am running Sage 9.5

A: The method is_integrally_closed for integral domains is what is raising this error: see https://doc.sagemath.org/html/en/reference/rings/sage/rings/ring.html#sage.rings.ring.IntegralDomain.is_integrally_closed. Note that if you instead do O.is_integrally_closed(), it returns False: it can apparently check orders, but not rings in this generality.


text:
Q: Unable to access folder directly but can via UNC path I am a domain administrator on our network. Recently, I noticed that there was a folder that I was unable to browse directly (when logged on to the server via Remote Desktop) to due to unusual NTFS permissions - although, I could of course make myself the owner then grant myself access if I wanted to.
The strange thing is, leaving the restrictive permissions just as they are, I am able to access that same folder via its UNC path (i.e. \\server\share).
How is it possible for a share to provide a higher level of access than directly browsing the same folder when logged onto the server locally? Surely, if anything, a share can only grant the same or lower access compared to locally browsing a server?
The server OS is Server 2008 R2.

A: In 2008 R2, you have share permissions and NTFS permissions. You can access these in the Share and Storage Manager MMC snap-in. Because these are seperate, the NTFS permissions set the local file path access, and the share permissions set the share file path access.


text:
Q: passing php variable to javascript syntax issue trying to upload pictures to a users folder /uploads/$uid i think i have the variable syntax right maybe the syntax in file path is incorrect /uploads/user/
(function($){
   $.simpleuploader = {version: '0.1'};
  $.fn.simpleuploader = function(options){
    // the container to inject the form into
    var $this = $(this);

    var user = '<?php echo $uid; ?>'; //is users id from session

    // set defults
    var defaults = {
        prefix: 'simpleuploader-',
        latency: 500,
        reuse: true,
        when: 'onchange',
        submitText: 'Submit',
        disabledOpacity: .3,
        settings: {
            fullPath: 'http://www.mysite.com/image_upload/uploads/user/',
            relPath: '../uploads/user/',

        },

A: Were you trying to use the user variable when defining the paths?
You should did it this way
var defaults = {
    prefix: 'simpleuploader-',
    latency: 500,
    reuse: true,
    when: 'onchange',
    submitText: 'Submit',
    disabledOpacity: .3,
    settings: {
        fullPath: 'http://www.mysite.com/image_upload/uploads/' + user + '/',
        relPath: '../uploads/' + user + '/',

    }


text:
Q: Signature OAuth 1.0 invalid caracter I am using the implementation example for two-legged authentication.
Based on the Absolute minimum code to get a valid oauth_signature populated in Java or Groovy? implementation.
However, I have a problem when the secret key has the character "#", I will exemplify.
For this test data, it works perfectly ..
nonce = 54408462
timestamp = 1589925486
url https://test.com/test
secretKey: Test123
key: test
generated signature: 19Cuj9dwWFmROc3Snxg5awltK10=

However when it has a character "#"...
nonce = 92475502
timestamp = 1589925554
url https://test.com/test
secretKey: Test#123
key: test
generated signature: 87QlLaFOZRsMMkJq3FGozFRNdJ0=

signature that should have been generated: OUl0yBF5sBv3/0uB0YIoTRPnrCM=

seems to me to be something of encoding, but I can't get it right
public String buildAuthorization(String url) {

    String oauth_nonce = "" + (int) (Math.random() * 100000000);
    String oauth_timestamp = "" + (System.currentTimeMillis() / 1000);
    List<BasicNameValuePair> qparams = new ArrayList<>();
    qparams.add(new BasicNameValuePair(OAUTH_CONSUMER_KEY, key));
    qparams.add(new BasicNameValuePair(OAUTH_NONCE, oauth_nonce));
    qparams.add(new BasicNameValuePair(OAUTH_SIGNATURE_METHOD, HMAC_SHA_1));
    qparams.add(new BasicNameValuePair(OAUTH_TIMESTAMP, oauth_timestamp));
    qparams.add(new BasicNameValuePair(OAUTH_VERSION, "1.0"));
    String signature = "";
    try {
        signature = getSignature(URLEncoder.encode(url, "UTF-8"), secret,
                URLEncoder.encode(URLEncodedUtils.format(qparams, "UTF-8"), "UTF-8"));
    } catch (IOException | NoSuchAlgorithmException | InvalidKeyException io) {
        throw new RuntimeException("Error");
    }

    return "OAuth "+OAUTH_CONSUMER_KEY+"=\"" + key + "\"," +
            OAUTH_SIGNATURE_METHOD+"=\"HMAC-SHA1\"," +
            OAUTH_TIMESTAMP+"=\"" + oauth_timestamp + "\"," +
            OAUTH_NONCE+"=\"" + oauth_nonce + "\"," +
            OAUTH_VERSION+"=\"1.0\"," +
            OAUTH_SIGNATURE + "=\"" + signature + "\"";

}

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;

public class OAuthPassword {

private static final String HMAC_SHA1 = "HmacSHA1";
private static final String ENC = "UTF-8";
private static Base64 base64 = new Base64();

public static String getSignature(String url, String secret, String params)
        throws UnsupportedEncodingException, NoSuchAlgorithmException,
        InvalidKeyException {

    StringBuilder base = new StringBuilder();
    base.append("POST&");
    base.append(url);
    base.append("&");
    base.append(params);
    byte[] keyBytes = (secret + "&").getBytes(ENC);
    SecretKey key = new SecretKeySpec(keyBytes, HMAC_SHA1);
    Mac mac = Mac.getInstance(HMAC_SHA1);
    mac.init(key);

    return new String(base64.encode(mac.doFinal(base.toString().getBytes(
            ENC))), ENC).trim();
}
}


text:
Q: How to Show Maximum and Minimum point in List Point Plot I have a list point of data per day. I want to plot this list of points in Mathematica and so that the maximum and minimum identified by for example red point.
How can I figure it out?
In the following my my data are available.
Thanks
ClearAll["Global`*"]
dataMT103891062day = {{{95, 5, 1}, 0.0764}, {{95, 5, 2},
0.0774}, {{95, 5, 3}, 0.0824}, {{95, 5, 4}, 0.0795}, {{95, 5, 5},
0.0887}, {{95, 5, 6}, 0.0867}, {{95, 5, 7}, 0.0794}, {{95, 5, 8},
0.0731}, {{95, 5, 9}, 0.0686}, {{95, 5, 10},
0.0797}, {{95, 5, 11}, 0.0792}, {{95, 5, 12},
0.0874}, {{95, 5, 13}, 0.0814}, {{95, 5, 14},
0.0809}, {{95, 5, 15}, 0.0775}, {{95, 5, 16},
0.0757}, {{95, 5, 17}, 0.0717}, {{95, 5, 18},
0.0811}, {{95, 5, 19}, 0.0773}, {{95, 5, 20},
0.0743}, {{95, 5, 21}, 0.0767}, {{95, 5, 22},
0.0744}, {{95, 5, 23}, 0.0787}, {{95, 5, 24},
0.0772}, {{95, 5, 25}, 0.0916}, {{95, 5, 26},
0.0801}, {{95, 5, 27}, 0.0724}, {{95, 5, 28},
0.0636}, {{95, 5, 29}, 0.0699}, {{95, 5, 30},
0.0634}, {{95, 5, 31}, 0.0695}};
DateListPlot[dataMT103891062day, PlotLegends -> "Load Coefficient"]

A: You can use MaximalByand MinimalBy,
{max, min} = {MaximalBy[#, Last], MinimalBy[#, Last]} &@ dataMT103891062day;

Plot them using Epilogattribute.
DateListPlot[dataMT103891062day, PlotLegends -> "Load Coefficient",
 Epilog -> {PointSize -> Medium, Red, Point@max, Point@min}]

To label the max and min points Labeled  can be used as follows.
DateListPlot[{dataMT103891062day, Labeled[min, min, {Right}],
  Labeled[max, max, {Right}]}, PlotLabel -> "Load Coefficient",
 Epilog -> {PointSize -> Medium, Red, Point@max, Point@min}, ImageSize -> Medium]


text:
Q: Updating field on GL Impact on Item Fullfillment record I'm trying to update fields on GL Impact Sublist of a Item Fullfillment record. I do not know which sublist ID to assign it. To then loop through each line and update a field on the sublist record.
Can anyone assist on  what I need to do in Suitescript

A: You can not edit GL Impact lines using script or even using the UI. The GL Impact is calculated by Netsuite based on the Transaction data (in your case, based on the Item Fulfillment record data), like the selected Accounts (or the concerned Items accounts), the Transaction Status or Approval Status...
And to answer exactly your question: the GL Impact is not a sublist that you can loop through using Scripting the way you do with other sublists like Items and Expenses.
Netsuite doesn't provide a Sublist ID for the GL Impact lines.
This is said, this help article provide a "workaround" that can be useful for your case.

A: Although @b-assem is correct in that you cannot directly affect the GL Impact of a transaction you can do this after a fashion using the 'Custom GL Lines Plug-in'. Search for that in the Netsuite help for more details.
The plugin calls a script every time the GL impact of a transaction is updated so it should be quick or it could have a major impact on your account's performance.
basically it allows you to reverse some or all of the GL impacts of your transaction and to add new GL Lines to balance those reversals.
You could also do much the same by scripting a JE in an Item Fulfillment After Submit Event script but that is a much more involved process. You'd do that by getting the Item Fulfillment's GL Impact from a search and create or update the JE in response. You'd need to add a linking field to the JE so you can find the JE created for a particular fulfillment and keep it up-to-date or delete it if the Item fulfillment gets deleted.


text:
Q: Port checking tool causes infinite packet received loop on TcpClient server I've written a relatively basic asynchronous server which boots up a task to accept clients and each client then boots up a task to accept incoming packets, the code for which is as follows:
        MessageListeningTask = new Task(async () => {
            while (true) {
                byte[] buffer = new byte[256];
                try {
                    await tcpClient.GetStream().ReadAsync(buffer, 0, buffer.Length);
                } catch {
                    break;
                }
                string data = Encoding.UTF8.GetString(buffer).Trim('\0', '\n', '\r', '\t', ' ');
                OnMessageReceived(data);
            }
        });

This seems to work pretty well for most things, and after routing it through a class that splits the tokens based on a token at the start, is quite an effective listener.
Except, given my naivety to the topic, I seem to have done something stupidly somewhere in my implementation, and checking with this tool: http://www.yougetsignal.com/tools/open-ports/ seems to break this loop and cause it to trigger OnMessageReceived constantly with no data.
I'm not entirely sure what procedures to take to help diagnose this issue, and figure it's probably something to do with how the information stream operates, so I was hoping someone with experience in the topic could help me solve my issue but also explain what is causing it. If it's relevant, it's running under Mono on Ubuntu, but it usually runs perfectly so I can't see this being the issue.
I am happy to provide any additional information, or to check anything.
Thanks!

A: From the documentation of ReadAsync:
https://msdn.microsoft.com/en-us/library/hh137813(v=vs.110).aspx
"Return Value
Type: System.Threading.Tasks.Task
A task that represents the asynchronous read operation. The value of the TResult parameter contains the total number of bytes read into the buffer. The result value can be less than the number of bytes requested if the number of bytes currently available is less than the requested number, or it can be 0 (zero) if the end of the stream has been reached."
In the loop ReadAsync must be constantly returning 0 because it reached the end of stream.


text:
Q: Extract attribute from shortcode and assign it to id url anchor To start off, I am a complete beginner with PHP. I am currently building a website on wordpress and using this plugin.
https://wordpress.org/plugins/fruitful-shortcodes/
This plugin allows me to easily add tabs with corresponding content boxes. In the shortcode I can specify a title that goes on the tab through an attribute called title. By default when I click on any tab, the url wilk add a hashtag for that tab. So it goes from www.mywebsite.com/services to something like www.mywebsite.com/services#ffs-tabbed-856 with the number at the end being randomly generated everytime.
What I want to do is be able to click on a tab and have the plugin extract the title of the tab and add it as the hashtag. So if the tab I click is titled Foot Care, the url should change from www.mywebsite.com/services to www.mywebsite.com/services#foot-care. I have been digging around the plugin php files and located the line responsible for generating the current hashtag.

$id   = 'ffs-tabbed-' . rand( 1, 100 );

Being inexperienced with PHP, I have been trying random combinations of php to try and get it to work. There is some variables like $title and $tab_title but I have no clue how to work them in. I have searched for hours and even emailed the plugin creator. Here is the function that I believe is being used by the particular shortcode I am using.
function fruitful_tabs_shortcode($atts, $content = null) {
    $output     = '';
    $tab_titles = array();
    $tabs_class = 'tab_titles';
    extract(shortcode_atts(array('id' => '', 'type' => '', 'width' => '', 'fit' => '', 'widthtab' => '', 'tabcolor' => '#71AFFF', 'closed' => 'true'), $atts, 'fruitful_tabs'));

    $id     = 'ffs-tabbed-' . rand( 1, 100 );
    $type   = 'default';
    $width  = 'auto';
    $fit    = 'false';
    $link   = '#';
    $widthtab   = '30%';

    if (isset($atts['id']))     { $id    = sanitize_html_class($atts['id']); }
    if (isset($atts['type']))   { $type  = esc_js($atts['type']); }
    if (isset($atts['width']))  { $width = esc_js($atts['width']); }
    if (isset($atts['fit']))    { $fit   = esc_js($atts['fit']); }
    if (isset($atts['widthtab']))   { $widthtab  = esc_js($atts['widthtab']); }
    if (isset($atts['tabcolor']))   { $tabcolor  = esc_html($atts['tabcolor']); }
    if (isset($atts['closed']))     { $closed    = esc_html($atts['closed']); }

    $output .= '';

    preg_match_all( '/tab title="([^\"]+)"/i', $content, $matches, PREG_OFFSET_CAPTURE );
    if ( isset( $matches[1] ) ) { $tabs = $matches[1]; }

    $output .= '
';
        $output .= '
';

    if (count($tabs)) {
        foreach ($tabs as $tab) {
            $output .= '
' . esc_html($tab[0]) . '
';
        }
    }
    $output .= '
';

    $output .= '
';
            $output .= fruitful_sh_esc_content_pbr(do_shortcode($content));
        $output .= '
';
    $output .= '
';
    $output .= '

';
    return $output;
}
add_shortcode('fruitful_tabs', 'fruitful_tabs_shortcode');

Any help would be great.


text:
Q: Proof that a proposition is not provable and that its negation is not provable Many propostions are not provable within (some) logic, i.e. LEM, the law of the excluded middle is not provable within IL, intutionistic logic.  (However, LEM is not inconsistent with IL,  see here for a proof ).
My question is the following: Is there an example of

*

*a proposition that is provably unprovable in IL, and

*whose negation is also provably unprovable in IL?

A: $A \lor \lnot A$ is not provable in IL.
See : Dirk van Dalen, Logic and Structure (5th ed - 2013), Ch.6.3 Kripke Semantics, page 164-on, and page 166 for a model showing : $\nvDash \lnot \lnot \varphi \to \varphi$ and $\nvDash \varphi \lor \lnot \varphi$.
$\lnot \lnot (A \lor \lnot A)$ is provable in IL.
Thus, by consistency :

$\lnot (A \lor \lnot A)$

is not provable in IL.

Here is the proof in IL of $\lnot \lnot (A \lor \lnot A)$ :
1) $\lnot (A \lor \lnot A)$ --- assumed [a]
2) $A$ --- assumed [b]
3) $A \lor \lnot A$ --- from 2) by $\lor$-intro
4) $\bot$ --- from 1) and 3)
5) $\lnot A$ --- from 2) and 4) by $\lnot$-intro, discharging [b]
6) $A \lor \lnot A$ --- from 5) by $\lor$-intro
7) $\bot$ --- from 1) and 6)

8) $\lnot \lnot (A \lor \lnot A)$ --- from 1) and 7) by $\lnot$-intro, discharging [a].


text:
Q: Is there a way to delete a branch on heroku I am using heroku to host my application. With merges and rebases i got 2 different stages of my app.
Local master is different from master on heroku.
pushing to heroku master failed with:
 ! [rejected]        master -> master (non-fast-forward)
 error: failed to push some refs to 'git@heroku.com:xxxxx.git'
 Merge the remote changes (e.g. 'git pull') before pushing again.  See the
 'Note about fast-forwards' section of 'git push --help' for details.

is there a way to delete the heroku master?
then i can push it again to heroku master..

A: You can force push
git push --force origin master

That will overwrite remote master.
You can also delete remote branch by doing this
git push origin :master

Note the colon before branch name. This command says "take void from local machine and put this instead of remote branch 'master'"

A: In my case, I renamed the branch on Heroku from master to main, and I want to delete the old master branch. If I delete the remote master branch directly on Heroku, it will be rejected.
The only way I found working is based on this document to reset.
Assume your app name is my-app. You can reset by
heroku plugins:install heroku-repo
heroku repo:reset --app=my-app

Note this will remove all branches in Heroku. So you need push to Heroku again by
git push heroku main


text:
Q: Is there a selective replace function? Should it be done using a If statement or For loop? I am relatively new to R. I need some help with more of a find and replace function but it is a bit more selective.
The example datasets I am using can be derived through:
name_1 <- c("Madeline","Maximillian","Maxon","Mad","Marvin")
value <- c(2.3,3.4,7.5,1.9,16.2)
scoreboard_table <- data.frame(name_1,value)

name_2 <- c("Madeline","Maximillian","Maxon","Mad")
nickname_1 <- c("Mad","Max","M","N/A")
nickname_2 <- c("Madine","Maxim","N/A","N/A")
nickname_table <- data.frame(name_2,nickname_1,nickname_2)

I want to replace the name of the scoreboard table with the second nickname. In that case, it would result in scoreboard_table to turn into:
name_1 <- c("Madine","Maxim","Maxon","Mad","Marvin")
value <- c(2.3,3.4,7.5,1.9,16.2)
scoreboard_table <- data.frame(name_1,value)

I am sure if doing a for loop would be easier or making an if, else statement. How should I go about this overall?
Thank you for the help in advance. It is really appreciated.

A: You can perform a join and use coalesce to get names from nickname_2.
library(dplyr)

left_join(scoreboard_table, nickname_table, by = c('name_1' = 'name_2')) %>%
  transmute(name_1 = coalesce(nickname_2, name_1),
            value) -> scoreboard_table

scoreboard_table

#  name_1 value
#1 Madine   2.3
#2  Maxim   3.4
#3  Maxon   7.5
#4    Mad   1.9
#5 Marvin  16.2

If they are not already change the "N/A" values to real NA in your data.
nickname_table[nickname_table == 'N/A'] <- NA


text:
Q: Bluetooth Won't Turn On in Ubuntu 18.04 I'm using a ThinkPad 13 Gen 2 and Bluetooth won't turn on. Once I toggle the bluetooth toggle from settings, it'll work then when I change screen and come back it's off.
This is the result of lspci -nnk | grep -iA3 net; lsusb; rfkill list; uname -r; dmesg | egrep -i 'blue|firm'
Output:
00:1f.6 Ethernet controller [0200]: Intel Corporation Ethernet Connection (4) I219-V [8086:15d8] (rev 21)
    Subsystem: Lenovo Ethernet Connection (4) I219-V [17aa:5063]
    Kernel driver in use: e1000e
    Kernel modules: e1000e
03:00.0 Network controller [0280]: Intel Corporation Wireless 8265 / 8275 [8086:24fd] (rev 78)
    Subsystem: Intel Corporation Dual Band Wireless-AC 8265 [8086:1010]
    Kernel driver in use: iwlwifi
    Kernel modules: iwlwifi
Bus 002 Device 009: ID 0451:8025 Texas Instruments, Inc.
Bus 002 Device 008: ID 0451:8140 Texas Instruments, Inc.
Bus 002 Device 002: ID 0bda:0411 Realtek Semiconductor Corp.
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 005: ID 8087:0a2b Intel Corp.
Bus 001 Device 003: ID 1bcf:2c94 Sunplus Innovation Technology Inc.
Bus 001 Device 013: ID 0451:ca01 Texas Instruments, Inc.
Bus 001 Device 014: ID 1532:005c Razer USA, Ltd
Bus 001 Device 012: ID 0451:8027 Texas Instruments, Inc.
Bus 001 Device 011: ID 1b1c:1b15 Corsair
Bus 001 Device 010: ID 0451:8142 Texas Instruments, Inc. TUSB8041 4-Port Hub
Bus 001 Device 002: ID 0bda:5411 Realtek Semiconductor Corp.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
0: tpacpi_bluetooth_sw: Bluetooth
    Soft blocked: no
    Hard blocked: no
1: phy0: Wireless LAN
    Soft blocked: no
    Hard blocked: no
4.18.0-21-generic
[    0.028000] [Firmware Bug]: TSC ADJUST: CPU0: -21639656 force to 0
[    0.028000] Spectre V2 : Enabling Restricted Speculation for firmware calls
[    0.004000] [Firmware Bug]: TSC ADJUST differs within socket(s), fixing all errors
[    0.100022] ACPI: [Firmware Bug]: BIOS _OSI(Linux) query ignored
[    2.905989] psmouse serio1: elantech: assuming hardware version 4 (with firmware version 0x4d1f00)
[    9.625944] iwlwifi 0000:03:00.0: loaded firmware version 36.9f0a2d68.0 op_mode iwlmvm
[    9.640894] thinkpad_acpi: rfkill switch tpacpi_bluetooth_sw: radio is unblocked
[    9.653124] [drm] Finished loading DMC firmware i915/kbl_dmc_ver1_04.bin (v1.4)
[   10.589911] Bluetooth: Core ver 2.22
[   10.589923] Bluetooth: HCI device and connection manager initialized
[   10.589925] Bluetooth: HCI socket layer initialized
[   10.589926] Bluetooth: L2CAP socket layer initialized
[   10.589929] Bluetooth: SCO socket layer initialized
[   11.933976] Bluetooth: BNEP (Ethernet Emulation) ver 1.3
[   11.933978] Bluetooth: BNEP filters: protocol multicast
[   11.933980] Bluetooth: BNEP socket layer initialized
[   31.523702] audit: type=1107 audit(1560246752.395:67): pid=975 uid=103 auid=4294967295 ses=4294967295 subj==unconfined msg='apparmor="DENIED" operation="dbus_method_call"  bus="system" path="/" interface="org.freedesktop.DBus.ObjectManager" member="GetManagedObjects" mask="send" name="org.bluez" pid=2518 label="snap.mailspring.mailspring" peer_pid=973 peer_label="unconfined"
[18446744056.005637] [Firmware Bug]: TSC ADJUST differs: CPU0 0 --> -21895161. Restoring

Also bluez is latest 5.50
I appreciate your help everyone.
Thanks


text:
Q: How to find out the embedded JDK version of Android Studio? I'm trying to find out what JDK's version does my Android Studio use.
I'm confused, because i have many versions in my /Program Files/Java catalog

Unfortunately the project structure doesn't have any JDK's version number.

A: In the installation directory of Android Studio there is a "release" file where you will find the detailed java information.
Contents of C:\...\Android Studio\jre\release :
JAVA_VERSION="1.8.0_242"
OS_NAME="Windows"
OS_VERSION="5.2"
OS_ARCH="amd64"
SOURCE=""

A: The embedded JDK is included in the Android Studio install. If you open the folder where you installed Android Studio, you'll see a jre folder in it:

Inside the folder there is a file called THIRD_PARTY_README in which the second sentence says:
%% This notice is provided with respect to ASM Bytecode Manipulation
Framework v5.0.3, which may be included with JRE 8, and JDK 8, and
OpenJDK 8.

I'm using Android Studio 3.0, in which the embedded JDK version is 8. To find the version in any later version though, go to [SDK_INSTALL_ROOT]/jre/ and find THIRD_PARTY_README

THIRD_PARTY_README is in my system defined as a file and not a txt file. You can open it in Notepad, Notepad++ or any other text editor. The content is plain text. You can also look for a file called release, which contains similar information about versions.


text:
Q: How to make rows as headers on SQL Server I have a table like below
    -------------------------------------
   | Date      | EventName | Occurrences|
   --------------------------------------
   | 4/30/2019 | Party     | 20         |
   | 4/30/2019 | Reunion   | 10         |
   | 4/30/2019 | Auction   | 5          |
   | 4/30/2019 | Party     | 10         |
   | 4/30/2019 | Reunion   | 10         |
   --------------------------------------

If I run a query like this
SELECT Date, EventName, SUM(Occurrences)
FROM [dbo].[Mytable]
GROUP BY Date, EventName
ORDER BY Date DESC

I get a result similar to this...
   | Date      | EventName | Occurrences|
   --------------------------------------
   | 4/30/2019 | Party     | 30         |
   | 4/30/2019 | Reunion   | 20         |
   | 4/30/2019 | Auction   | 5          |

How can I transform the rows into Columns so my result looks more like this?
   | Date      | Party     | Reunion    | Auction |
   ------------------------------------------------
   | 4/30/2019 | 30        | 20         |    5    |

I don't know how to transform rows into columns but what I have tried so far is to query for each EventName and then join them. I think this is not optimal at all but I haven't been able to figure out a better way.

A: You can try to use condition aggregate function, CASE WHEN with SUM
SELECT Date,
    SUM(CASE WHEN EventName = 'Party' THEN Occurrences ELSE 0 END) Party,
    SUM(CASE WHEN EventName = 'Reunion' THEN Occurrences ELSE 0 END) Reunion,
    SUM(CASE WHEN EventName = 'Auction' THEN Occurrences ELSE 0 END) Auction
FROM [dbo].[Mytable]
GROUP BY Date

A: The SQL language has a very strict rule that you must know the number and types of columns in the results based only on the schema, before a query starts to execute. What you're asking for is not known until after the query begins to inspect the data.
This is still possible if you know the values you expect as columns. In that case, you can use conditional aggregration, or sometimes a PIVOT statement... but in both cases you must specify every column you need along with the calculation required for that column by hand. It can quickly become unwieldy to write and maintain if you have a lot of result columns.
This is also possible using dynamic SQL, whereby you run the query in three steps: first, run a query to get the column names you'll need. Second, use that information to build a new query string with the needed columns. Third, execute the new query string. Dynamic is sql is both dangerous and slow, and should only be used when you absolutely have to.
In most situations, the correct response here is option 3: pivot the data in the client program or reporting tool. Run the query you already have, and let the data consumer worry about the rest. The reason this is difficult boils down to formal relational set theory. What you're asking to do isn't only outside of traditional set theory, but in direct opposition to how to best use relations, and therefore database engine language designers are reluctant to build in a simple syntax for those operations.


text:
Q: Simple inner join result with Dapper? I can't seem to find documentation or examples for my problem (been searching a while now). I think my problem is pretty straightforward, so here goes.
I have two tables. My primary table is called Persons and the secondary table is PersonEntries. For each person in Person table, i can have 0 or more entries in the PersonEntries table. Like this.
Table: Person
Id
Name

Table: PersonEntry
PersonId
CheckinTime
CheckoutTime

I have two objects like this
public class Person {
  public string Name;
  public List<PersonEntry> PersonEntries;
}

public class PersonEntry {
  public DateTime CheckinTime;
  public DateTime CheckoutTime;
}

If i was to get it from the database into my c# classes how would i do it? I can map a single table into my c# class and do it for each table, but then i'm left to match what entries maps to what person.
I've seen several examples of mapping ONE PersonEntry to ONE Person, the problem here is that i have a zero-to-many relation. My Person have a LIST of PersonEntry items.

A: You can do something like this (see https://www.tritac.com/blog/dappernet-by-example):
public class Shop {
  public int? Id {get;set;}
  public string Name {get;set;}
  public string Url {get;set;}
  public IList<Account> Accounts {get;set;}
}

public class Account {
  public int? Id {get;set;}
  public string Name {get;set;}
  public string Address {get;set;}
  public string Country {get;set;}
  public int ShopId {get;set;}
}

var lookup = new Dictionary<int, Shop>()
conn.Query<Shop, Account, Shop>(@"
                SELECT s.*, a.*
                FROM Shop s
                INNER JOIN Account a ON s.ShopId = a.ShopId
                ", (s, a) => {
                     Shop shop;
                     if (!lookup.TryGetValue(s.Id, out shop)) {
                         lookup.Add(s.Id, shop = s);
                     }
                     if (shop.Accounts == null)
                         shop.Accounts = new List<Account>();
                     shop.Accounts.Add(a);
                     return shop;
                 }
                 ).AsQueryable();
var resultList = lookup.Values;


text:
Q: Xml Linq. A problem with the objects. The name does not exist in the current context I have a problem with my objects of class XDocument of System.Xml.Linq namespace.
I tried to describe all xml things in the class TemplateXML.cs (not Main class) and after of declaring object I can't do nothing with it.

ERROR was in the last line with xdoc.Save: The name 'xdoc' does not
  exist in the current context.

After I founded that it is problem only when I create xml objects not in Main class.
Which type of item (obviously not a class) I have to create for describing my code? In my winform application there is just one button for generate xml file and I dont want to place it to Main class cause its huge.
PS I use needed namespace and xml.linq link in references of my project.


text:
Q: Sql Statement cutting Rows in half Here is my current sql query
        SELECT
    w.city, t.tmc, t.date, t.time, w.event,
    ROUND(AVG(w.Pave), 0) surface_temperature,
    ROUND(AVG(w.Air), 0) air_temperature,
    ROUND(AVG(a.material_rate),0) material_rate,
    w.intensity, t.avg
    FROM winter2010.traffictest t
    LEFT OUTER JOIN winter2010.application a ON a.DATE = t.DATE AND a.tmc = t.tmc AND a.tmc = t.tmc AND Left(a.time,2) = Left(t.time, 2)
    LEFT OUTER JOIN winter2010.weather w ON t.DATE = w.DATE AND t.tmc = w.tmc AND  Left(t.time, 2) =  Left(w.time, 2)
    GROUP BY tmc, t.time
    INTO OUTFILE 'c:/sass2.csv' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES
TERMINATED BY '\n';

I'm creating this csv file from the following sql statement and it works great except for one thing, its only taking 1/2 the rows!
There are a total of 2661 rows in traffictest
And when I outfile the data into the csv its only putting 1331.
I've changed the size of traffictest and this holds true except when I had only 3 rows it actually pulled all three rows.
Any help figuring this out would be much appreciated.

A: When you use GROUP BY MySql returns only one row per group, You have rows with similar tmc-time and MySql is returning only one row for all such rows that's the reason for decrease in row number.


text:
Q: How to "diff" effective/computed css rules of an HTML element from two different pages? I've come across this problem enough times that I'd like to find a smarter approach. The scenario is that I make changes to a web app, and an element on the page ends up looking different than it used to look and I'm not sure why. Sometimes it's because I've refactored markup and css, or sometimes because I've added a new css include on the page, or other reasons.
Sometimes the css looks to be pretty much the same, and so I have to go an elaborate hunt in the browser dev tools for what css rules have been applied. If I can't spot the cause in the "properties" section of Chrome's dev tools, I look at the "Computed Style" section. Sometimes I still have trouble spotting the difference, so I paste the "Computed Style" section for the broken and working versions into text files, save to disk and then diff the two. It ends up being something frustrating, like the element in the broken version inherited a different line-height from an ancestor element.
Is there an easier way to do this?


text:
Q: Is "coding on OOP JavaScript" phrased well? I want to use it in a CV I need to write in my CV that I write on JavaScript Object Oriented Language. So is the following sentence correct?

Coding on OOP JavaScript

A: You should probably in already have a section in your CV/resume called Technical Skills or Programing Languages. So just putting "Object-oriented JavaScript" or "OO JavaScript" as a bullet point is sufficient. Or maybe something like "3 years of OO JavaScript". If you want to specify that for a particular job you used this skill, then you can just say something like "Developed web apps using OO JavaScript". In general, "development" and "programming" are more professional terms to reflect your skill.


text:
Q: Cannot find module using gulp and react I am new to react.js and somehow i have setup react environment with gulp build tool. I want to create custom React component and use it in another component. Please look at my code and help me.
index.html
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>React and ES6</title>

Header.js
import React from "react";

export class Header extends React.Component {
  render(){
    return (

Home

About

Contact Us

    );
  }
}

and Login.js
import React from "react";
import {render} from "react-dom";
import {Header} from "./components/Header.js";

class Login extends React.Component {

  render(){
    return(

Login Test!!

    );
  }
}
render(<Login/>, window.document.getElementById("testdiv"));

gulpfile.js
// declarations, dependencies
// ----------------------------------------------------------------------------
var gulp = require('gulp');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var gutil = require('gulp-util');
var babelify = require('babelify');
var notifier = require('node-notifier');
var watchify = require('watchify');

// External dependencies you do not want to rebundle while developing,
// but include in your application deployment
var dependencies = [
    'react',
    'react-dom'
];

// Gulp tasks
// ----------------------------------------------------------------------------
gulp.task('scripts', function () {
    bundleApp(true);
});

gulp.task('deploy', function (){
    bundleApp(true);
});

gulp.task('watch', function () {
    gulp.watch([
    './app/Controller/*.js'
  ], ['scripts']);
});

var notify = function(title, message) {
  notifier.notify({
    title: title,
    message: message
  });
  gutil.log(title + ': ' + message);
};

// When running 'gulp' on the terminal this task will fire.
// It will start watching for changes in every .js file.
// If there's a change, the task 'scripts' defined above will fire.
gulp.task('default', ['scripts','watch']);

var reactFiles = {
  path: [
    {
      from: ['app/components/Header.js'],
      to: 'Header.js'
    },
    {
      from: ['app/components/Home.js'],
      to: 'Home.js'
    },
        {
      from: ['app/controller/login.js'],
      to: 'login.js'
    }
  ],
  watchPath: ['web/controller/*.js']
};

// Private Functions
// ----------------------------------------------------------------------------
function bundleApp(isProduction) {
    // Browserify will bundle all our js files together in to one and will let
    // us use modules in the front end.
  var finished = 0;
  reactFiles.path.map(function(reactModuleEntry){
    var appBundler = browserify(reactModuleEntry.from)
    .transform(babelify, { presets: ['es2015', 'react'] })
    .bundle();

    appBundler.pipe(source(reactModuleEntry.to))
    .pipe(gulp.dest('./web/js/dist'))
    .on('finish', function() {
            finished++;
            if (finished === (reactFiles.path.length - 1)) {
              notify('Reactify', 'build: done')
              //done();
            }
          });
  });

}

Directory Structure is
ReactPractice
|
|---index.html
|---gulpfile.js
|--app
    |---Components
    |             |--Header.js
    |---Controller
    |             |--Login.js

Error when gulp file is run
events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: Cannot find module './components/Header.js' from '/home/subro/reactpractice/app/controller'
    at /home/subro/reactpractice/node_modules/browser-resolve/node_modules/resolve/lib/async.js:55:21
    at load (/home/subro/reactpractice/node_modules/browser-resolve/node_modules/resolve/lib/async.js:69:43)
    at onex (/home/subro/reactpractice/node_modules/browser-resolve/node_modules/resolve/lib/async.js:92:31)
    at /home/subro/reactpractice/node_modules/browser-resolve/node_modules/resolve/lib/async.js:22:47
    at Object.oncomplete (fs.js:107:15)

A: The path in the import statement is relative to where it is called from. Relative to Login.js, you need to move up a directory to access components/Header.js. Change the import to:
import {Header} from '../components/Header';


text:
Q: Как работает функция trim в данном случае? Есть код
<?php

$a = array(1, 1, 2, 3, 4, 5, 15);
$b = implode('', $a);
$r = trim($b, '15');
echo $r;
?>

Можно пояснить почему результатом будет 234 ?

A: Согласно описанию, найденному в интернет:),

The trim() function is used to remove the white spaces and other
  predefined characters from the left and right sides of a string.
  Specifies the character(s) to remove. Without this remove the
  following " " an ordinary space

функция trim удаляет начальные и конечные символы  согласно заданному шаблону в виде строки. Например, для фрагмента кода
$a = array(1, 1, 2, 3, 4, 5, 15);
$b = implode('', $a);
$r = trim($b, '14');

будут удалены начальные '1' И в резуьтате получится
'234515'

Символы '4' и '1', которые находятся внутри строки, не будут удалены, так как они не является начальным или завершающим символом строки.
А для данного фрагмента код
$a = array(1, 1, 2, 3, 4, 5, 15);
$b = implode('', $a);
$r = trim($b, '15');

будет результат
'234'


text:
Q: Draw strokes from SurfaceInkCanvas onto image I'm trying to create an app that allows the user to draw on an image.  I started with the PhotoPaint SDK sample.  I understand that the SurfaceInkCanvas is set to transparent and is located on top of the image.  When the user is finished drawing I would like to draw the strokes onto the image itself.  This is where I'm stuck.  Can anyone please point me in the right direction?
Thanks!

A: Download WriteableBitmap extenstion library from:  http://writeablebitmapex.codeplex.com/
Usage:
using System;
using System.IO;
using System.Net;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace TestApp
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void SaveImage(object sender, RoutedEventArgs e)
        {
            var bi = FromUrl("http://www.dynamicdrive.com/dynamicindex4/lightbox2/horses.jpg", Environment.CurrentDirectory);

            if (bi.Format != PixelFormats.Pbgra32)
                bi = BitmapFactory.ConvertToPbgra32Format(bi);

            WriteableBitmap wrb = new WriteableBitmap(bi);

            foreach (var stroke in ink.Strokes)
            {
                foreach (var point in stroke.StylusPoints)
                {
                    wrb.DrawLine((int)point.X, (int)point.Y, (int)(point.X + 1), (int)(point.Y + 1), Colors.Red);
                }
            }

            var encoder = new JpegBitmapEncoder();
            BitmapFrame frame = BitmapFrame.Create(wrb);
            encoder.Frames.Add(frame);

            using (var stream = File.Create("result.jpg"))
            {
                encoder.Save(stream);
            }

        }

        public static BitmapSource FromUrl(string url, string workingPath)
        {
            string[] strArr = url.Split(new char[] { '/' });
            string file = workingPath + "\\" + strArr[strArr.Length - 1];
            if (!File.Exists(file))
            {
                using (WebClient client = new WebClient())
                {
                    client.DownloadFile(url, file);
                }
            }
            return BitmapImageFromFile(file);
        }

        public static BitmapSource BitmapImageFromFile(string file)
        {
            BitmapImage bi = new BitmapImage();
            try
            {
                bi.BeginInit();
                bi.CacheOption = BitmapCacheOption.OnLoad;
                bi.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
                bi.UriSource = new Uri(file, UriKind.RelativeOrAbsolute);
                bi.EndInit();
            }
            catch { return ToBitmapSource(System.Drawing.Bitmap.FromFile(file)); }
            return bi;
        }

        public static BitmapSource ToBitmapSource(System.Drawing.Image bitmap)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                stream.Position = 0;
                BitmapImage result = new BitmapImage();
                result.BeginInit();
                result.CacheOption = BitmapCacheOption.OnLoad;
                result.StreamSource = stream;
                result.EndInit();
                result.Freeze();

                return result;
            }
        }
    }
}

XAML:
<Window x:Class="TestApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow"
        Height="350" Width="525">
    <Grid>
        <Image Source="http://www.dynamicdrive.com/dynamicindex4/lightbox2/horses.jpg"
               Name="img"/>
        <InkCanvas Background="Transparent"
                   Name="ink"/>
        <Button Content="Save"
                HorizontalAlignment="Left"
                VerticalAlignment="Top"
                Margin="5"
                Click="SaveImage"/>
    </Grid>
</Window>

maybe you'll find a better way to draw on the WriteableBitmap using this extension, drawing method i have used it's just an experiment.


text:
Q: How do I access these dynamically created controls from the code behind? I am trying to create a web page that starts off blank. With every button press new textboxes are added with a delete button to remove whatever row they want. That works great. The problem is I cannot access the dynamically created controls using C#.
In the code below I have them set up as <input I've also tried using <asp:Textbox but it also did not work. Request.Form["txtItemName1"] always returns a blank string and I cannot do txtItemName1.Text in the CS file because the textboxes don't exist yet.
How am I suppose to access the textboxes from the C# side?
Is there a better way to create controls dynamically?

<button type="button" class="btn btn-default" id='addButton'>

</button>

A: C# backend will not have access to dynamically jquery-created input fields. You can create server controls in ASP.Net with the code behind and using an UpdatePanel as in the example.


text:
Q: Estimate the scale of the power series with Poisson pdf-like terms Sorry to bother you, but I guess that this question is not appropriate for MO, so I repost it here hoping that someone could give me a clue.
I would like to have an estimate for the series
$$P(t) = \sum\limits_{k = 0}^\infty (e^{-t}\frac{t^k}{k!})^m,$$
where $e$ is the base of natural logarithm, $k!$ is the factorial of the integer $k$, $t$ represents the time and $t>0$, $m$ is a positive integer and $m>1$ (Obviously, $P(t)=1$ when $m=1$ since $P(t)$ is exactly the cdf of Poisson distribution with associated parameter $t$ in this case.).
I am interested in showing that the order of the scale could look something like
$$P(t) = O(t^{-\alpha m}),\alpha > 0.$$
But I find it difficult for me to extend their method to the cases when $m>2$.
 I also tried to calculate $P(t)$ in Mathematica and it gave me the result like
$$P(t) = \sum\limits_{k = 0}^\infty (e^{-t}\frac{t^k}{k!})^m = e^{-mt}\text{HypergeometricPFQ}[...,t^m]$$
It seems that the decreasing speed of $P(t)$ is much slower than that of $e^{-mt}$ as $t$ increases. But I could not find the closed-form bound for $P(t)$ when $m>2$ just like $O(1/\sqrt t)$ when $m=2$.
Does anyone know of a scale or a bound of $P(t)$ in the literature? Any comments and answers would be highly appreciated. Many thanks!

A: The function you have, and this is also the closed form that Mathematica gave you, is related to the hypergeometric function,
$$ P(t) = e^{-m t}\,\,{}_0F_{m-1}(;1,1,\ldots,1; t^m). $$
To calculate its behaviour as $t\to\infty$, at least in this case, is relatively easy. In particular the DLMF gives the formulas necessary, 16.11.9 and 16.11.1-4.
The result is
$$ P(t) = \frac{1}{(2\pi)^{\frac{m-1}{2}}\sqrt{m}}\frac{1}{t^{\frac{m-1}{2}}} + O(t^{\frac{-1-m}{2}}). $$
You can also check this for small values of $m$ using Mathematica's function Series, which understands how to calculate asymptotic behaviour.


text:
Q: How to make textArea object accessible I have been coding for about 3 months now, (I've never had any programming experience) and I ran into a bit of an issue. I'm working on an idle clicking game, but I can't seem to access textArea.
I need to update textArea from outside its class since I am multi-threading and need separate run() methods.
class AddOne extends Thread {

    public static int money = 0;
    public static boolean flag = false;
    public void run() {
        try {
            money++;
            System.out.println(money);
            //update textArea with new money value

        }
        catch(Exception e){
            System.out.println("The exceptions are: " + e);
        }
    }
}

class AddOnePerSec extends Thread {

    public void run() {
        try {
            if(AddOne.flag == false)
            {
                for(int i = 0; i<=100; i++)
                {
                    AddOne.flag = true;
                    AddOne.money++;
                    Thread.sleep(1000);
                    //update textArea with new money value

                }
                AddOne.flag = false;
            }
            else {System.out.println("Please wait...");}
        }
        catch(Exception e){
            System.out.println("The exceptions are: " + e);
        }
    }
}

public class ClickGame {

    private static JFrame frame;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    AddOne.flag = false;
                    ClickGame window = new ClickGame();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public ClickGame() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    public static void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(new BorderLayout(0, 0));

        JButton btnAdd = new JButton("Add 1");
        btnAdd.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                AddOne add = new AddOne();
                add.start();
            }
        });
        frame.getContentPane().add(btnAdd, BorderLayout.WEST);

        JButton btnAddEvery = new JButton("Add 1 every second for 100 seconds");
        btnAddEvery.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                AddOnePerSec persec = new AddOnePerSec();
                persec.start();
            }
        });
        frame.getContentPane().add(btnAddEvery, BorderLayout.EAST);

        JTextArea textArea = new JTextArea();
        frame.getContentPane().add(textArea, BorderLayout.CENTER);
    }
}

Ideally, the textArea will be updated with the new money variable every time money is changed in each thread.

A: Well, I added the code that got it to do what you want. In my opinion, it's not the best way, it's simply what I call a quick-and-dirty solution. If you haven't already done so, I suggest reading the tutorial Creating a GUI With JFC/Swing
I simply added a member variable to class AddOne and AddOnePerSec. I also added a constructor to each one of those classes that initializes the member variable. That way you have a reference to the JTextArea from within the class.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;

class AddOne extends Thread {
    private JTextArea textArea;
    public static int money = 0;
    public static boolean flag = false;

    public AddOne(JTextArea txtAr) {
        textArea = txtAr;
    }

    public void run() {
        try {
            money++;
            System.out.println(money);

            //update textArea with new money value
            // NOTE: Updating GUI must be done on EDT.
            EventQueue.invokeLater(() -> textArea.append(String.valueOf(money) + "\n"));
        }
        catch(Exception e){
            System.out.println("The exceptions are: " + e);
        }
    }
}

class AddOnePerSec extends Thread {
    private JTextArea textArea;

    public AddOnePerSec(JTextArea txtAr) {
        textArea = txtAr;
    }

    public void run() {
        try {
            if(AddOne.flag == false)
            {
                for(int i = 0; i<=100; i++)
                {
                    AddOne.flag = true;
                    AddOne.money++;
                    Thread.sleep(1000);

                    //update textArea with new money value
                    // NOTE: Updating GUI must be done on EDT.
                    EventQueue.invokeLater(() -> textArea.append(String.valueOf(AddOne.money) + "\n"));
                }
                AddOne.flag = false;
            }
            else {System.out.println("Please wait...");}
        }
        catch(Exception e){
            System.out.println("The exceptions are: " + e);
        }
    }
}

public class ClickGame {

    private static JFrame frame;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    AddOne.flag = false;
                    ClickGame window = new ClickGame();
                    ClickGame.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public ClickGame() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    public static void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(new BorderLayout(0, 0));

        final JTextArea textArea = new JTextArea(110, 80);
        JButton btnAdd = new JButton("Add 1");
        btnAdd.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                AddOne add = new AddOne(textArea);
                add.start();
            }
        });
        frame.getContentPane().add(btnAdd, BorderLayout.WEST);

        JButton btnAddEvery = new JButton("Add 1 every second for 100 seconds");
        btnAddEvery.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                AddOnePerSec persec = new AddOnePerSec(textArea);
                persec.start();
            }
        });
        frame.getContentPane().add(btnAddEvery, BorderLayout.EAST);
        frame.getContentPane().add(textArea, BorderLayout.CENTER);
    }
}

Here is a screen-capture of the running app.


text:
Q: Android-O launch on secondary display The new ActivityOptions setLaunchDisplayId (int launchDisplayId) function in Android-O seems to always crash my app when I try to launch an activity intent.
Both when I launch activities from my own app and when I try to launch other apps i.e. Chrome Canary.
Does anyone know if this is a general problem with the new API's or am I missing something:
A small snippet of my code is below:
options.setLaunchDisplayId(1);
startActivity(intent, options);
NOTE
I was testing with 'simulate a second screen' enabled (@1080p if it matters).
UPDATE
I have tried the ADB command adb shell start com.chrome.canary --display 1,
and I get the message:

start: must be root

A: I have connected to the second screen via the new API's with the code below, but as of yet have no way of interacting with it.
 Bundle bdl;
 MediaRouter mediaRouter = (MediaRouter) mContext.getSystemService(Context.MEDIA_ROUTER_SERVICE);
 MediaRouter.RouteInfo route = mediaRouter.getSelectedRoute(MediaRouter.ROUTE_TYPE_LIVE_VIDEO);
 if (route != null) {
     Display presentationDisplay = route.getPresentationDisplay();
     bdl = ActivityOptions.makeClipRevealAnimation(mView, left, top, width, height).setLaunchBounds(rect).setLaunchDisplayId(presentationDisplay.getDisplayId()).toBundle();
     Bundle optsBundle = true ? bdl : null;
     Intent intent = new Intent(mContext, SecondaryActivity.class);
     intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
     mContext.startActivity(intent, optsBundle);
 }

A: Here's a simplified answer which is working for me, built off of @Smiler. I tested this via a Button click in my MainActivity. Thanks for the help!
    ((Button) findViewById(R.id.launchTopScreen)).setOnClickListener(v -> {
        Intent intent = getPackageManager().getLaunchIntentForPackage("com.example.new.app");
        intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT | Intent.FLAG_ACTIVITY_NEW_TASK);
        ActivityOptions options = ActivityOptions.makeBasic().setLaunchDisplayId(1);
        startActivity(intent, options.toBundle());
    });

The Intent.FLAG_ACTIVITY_NEW_TASK is extremely important in order to have the new application launch on a different display. Otherwise it'll launch in the same task stack, on the same display.
That 'new application' needs to also have android:resizeableActivity="true" in the manifest. True is the default, but I specified to just be explicit and protect future framework changes.
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:resizeableActivity="true"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

A: each time you add a new simulate screen the display id changes. it resets to 1 when you restart. check if this is the issue. adb command that you specified doesnt seem to work as you said.


text:
Q: PDO + SqlAnywhere, its possible? I would like use PHP PDO with SqlAnywhere, but don't have the driver on php site. Can I add a lib of sqlanywhere to use with PDO? ODBC is the last option.

A: A PDO SQL Anywhere driver has now been released here: http://pecl.php.net/package/PDO_SQLANYWHERE/

A: I haven't tried this, but no one has answered in two days so I'll give a suggestion:
The PDO_MSSQL driver should in theory be able to talk to any FreeTDS back-end, including Sybase Server and perhaps even Sybase ASA.  It may require you to do some hunting and reading blogs, forums, etc. to figure out the right freetds.conf entries to make it work.
However, the PDO_MSSQL driver is marked as "experimental" and AFAIK no one is maintaining it.  Microsoft has abandoned it as well, since they're developing their own (non-PDO) PHP extension for SQL Server.*
So it's probably the better part of valor on your part to use PDO_ODBC.

* There was an effort a couple of years ago for Microsoft and other RDBMS vendors to cooperate to contribute code to the PDO project, but the core PHP community rebuffed the vendors over their requirement to use a contributor license agreement to ensure that the code in the project remain free.  It was a sad episode.

A: Yes, but you should modify the unixodbc library, the script: SQLExecute.c, otherwise will get the error : PERMISSION DENIED CREATE STORE PROCEDURE


text:
Q: Pandas DataFrame replace does not work with inplace=True In my column of the data frame i have version numbers like 6.3.5, 1.8, 5.10.0 saved as objects and thus likely as Strings. I want to remove the dots with nothing so i get 635, 18, 5100. My code idea was this:
for row in dataset.ver:
    row.replace(".","",inplace=True)

The thing is it works if I don't set inplace to True, but we want to overwrite it and safe it.

A: You're iterating through the elements within the DataFrame, in which case I'm assuming it's type str (or being coerced to str when you replace).  str.replace doesn't have an argument for inplace=....
You should be doing this instead:
dataset['ver'] = dataset['ver'].str.replace('.', '')

A: Sander van den Oord in the comments is quite correct to point out:
dataset['ver'].replace("[.]","", inplace=True, regex=True)

This is the way we do operations on a column in Pandas because in general, Pandas tries to optimize over for loops. The Pandas developers consider for loops the among least desirable pattern for row-wise operations in Python (see here.)


text:
Q: JQuery detect widget attached I have a web application with a medium amount of ajax requests.
I load all jquery and jquery widgets on head then i load my base.js before close body tag.
function baseScripts() {
        $(".open-dialog").click(function (event) {
            event.preventDefault();
            event.stopPropagation();
            alert("Opening dialog");
            href = $().buildUrl($(this).attr("href"), "&isAjax=true");
            $().createDialog(href, "Window Title");
            return false;
        });

        $("input:hidden.select").each(function () {
                var element = $(this);
                if (!($("#s2id_" + element.attr("id")).length)) {
                    $(element).select2({
                        // select2 properties...
                    });
                }
            });
        }
}

SCRIPT BLOCK TO LOAD BASE SCRIPTS ON EVERY AJAX REQUEST
$(document).ajaxComplete(baseScripts);

The problem is after every ajax request the base scripts its called again and them opening dialog multiple times and attaching select2 multiples times too.
How i can detect if widget is already attached into element or class?
Execute scripts on every ajax request (like i did) its a bad pratice?

A: It doesn't make sense that you will want to re-bind the click event and select2 on ajaxComplete. They should be a one-time binding, in which case, you can just do:
$(document).ready(function(){
    baseScripts();

    function baseScripts() {
        $(".open-dialog").click(function (event) {
            event.preventDefault();
            event.stopPropagation();

            alert("Opening dialog");

            href = $().buildUrl($(this).attr("href"), "&isAjax=true");

            $().createDialog(href, "Window Title");

            return false;
        });

        $("input:hidden.select").each(function () {
            var element = $(this);

            if (!($("#s2id_" + element.attr("id")).length)) {
                $(element).select2({
                    // select2 properties...
                });
            }
        });
    }
});


text:
Q: Excel VBA XL4 Application Level Defined Name Defined Names are normally defined at the worksheet or workbook level. But it is also possible to define them at the Application level using an old xl4 macro call. They thus become a place to store state that does not get reset when a VBA project is reset (e.g. due to an error).
This is an old trick, but I cannot remember how to do it. And not much documentation - some people must think that xl4 is obsolete.

A: Chip Pearson has it documented here: http://www.cpearson.com/Excel/hidden.htm


text:
Q: Installing python mac 2.7.6 I would like to have a local install of python in my mac for an older version of python. For instance I have python 2.7.10. However I would like python 2.7.6 for a particular project development. How can I install 2.7.6, without impacting mac's default python or previously installed versions?

A: You can use Homebrew or [MacPorts] to install multiple versions of Python on the same machine without necesarrily overriding the default Python interpreter (https://www.macports.org/) (based on my personal experience I recommend Homebrew).
Have a look at http://docs.python-guide.org/en/latest/starting/install/osx/#doing-it-right.
Edit: I checked for Python and it's not among the standard old repositories like homebrew/versions or homebrew/boneyard so you have to install it directly from github by searching for the formualr with 2.7.6 version which is this one:
https://github.com/Homebrew/legacy-homebrew/blob/72eb84e61e46f9c22193b7b0fbcf60993b795c8e/Library/Formula/python.rb
Brew can install it right from github:
$ brew install https://raw.githubusercontent.com/Homebrew/legacy-homebrew/72eb84e61e46f9c22193b7b0fbcf60993b795c8e/Library/Formula/python.rb

A: You should learn about using virtualenvs. A Virtual Environment is a tool to keep the dependencies required by different projects in separate places, by creating virtual Python environments for them. It solves the "Project X depends on version 1.x but, Project Y needs 4.x" dilemma, and keeps your global site-packages directory clean and manageable.
Here You have a good tutorial for Mac OS, it's written for Yosemite but should work on other os versions too.
As mentioned in this question: Use different Python version with virtualenv, You can use virtualenv -p /usr/bin/python2.6 <path/to/new/virtualenv/> command to specify the Python version for virtualenv.


text:
Q: Stop scrolling on zoomable iframe I'm working on a webpage that embeds another page from a different domain inside an iframe. The content of this page fits the iframe exactly, so there's no overflowing content and no scrollbars. However, the content can be zoomed with the mousewheel.
But in Safari and Chrome, zooming with the mousewheel also scrolls the entire page. I don't want this scrolling to happen---only the zooming of the iframe. How can I stop this scrolling when the mouse is over the iframe?
I've attempted to recreate the problem in a minimal example on JSFiddle: https://jsfiddle.net/twodee/57a68k3h. When I zoom over the green iframe, the text zooms but the page also scrolls.

frame = document.getElementById('myframe');
frame_child = document.createElement('div');

var font_size = 12;
frame_child.addEventListener('wheel', function(e) {
  font_size += e.wheelDelta;
  frame_child.style.fontSize = font_size + 'px';
});

frame_child.style.width = '190px';
frame_child.style.height = '190px';
frame_child.innerHTML = 'this text should zoom';
frame.contentWindow.document.body.appendChild(frame_child);
#myframe {
  background-color: #00FF00;
}

a

a

a

a

a

a

a

a

a

a

a

a

a

a

a

a

a

a

a

a

a

a

a

a

a

a

a

b

b

b

b

b

b

b

b

b

b

b

b

b

EDIT:
The example above is a little misleading in that the iframe source is not really generated dynamically by my own script. Instead, the source is generated by a separate website, which expects form input from the requester. Here's a CodePen that better demonstrates my issue: http://codepen.io/twodee/pen/PGqgyw. (JSFiddle only allows https:// sources.)
When I wheel over the iframe, the 3D cube zooms and the page scrolls.
EDIT:
The effect I'm after is what I see when Google Maps is embedded in a page. Or Sketchfab. When I embed these in an iframe, I don't have to do anything special in the page that's doing the embedding to make zooming happen without scrolling. There seems to be something about the embedded content itself that disables the scrolling, but I don't know what.

A: You can add mouse event listeners on your Iframe to check to see if your mouse is in it, and if it is then stop the scroll from happening on the window:
frame = document.getElementById('myframe');
frame_child = document.createElement('div');
var font_size = 12;
var inFrame=false;
frame_child.addEventListener('wheel', function(e) {
  font_size += e.wheelDelta;
  frame_child.style.fontSize = font_size + 'px';
});
frame.addEventListener("mouseover",function(e){
inFrame=true;
});
frame.addEventListener("mouseout",function(e){
inFrame=false;
});
window.addEventListener('wheel',function(e){
if(inFrame)
    e.preventDefault();
})
frame_child.style.width = '190px';
frame_child.style.height = '190px';
frame_child.innerHTML = 'this text should zoom';
frame.contentWindow.document.body.appendChild(frame_child);

Just add prevent default on your div wheel listener:
frame_child.addEventListener('wheel', function(e) {
e.preventDefault();
  font_size += e.wheelDelta;
  frame_child.style.fontSize = font_size + 'px';
});

A: use this code on mouse :hover
    $("#myframe").hover(
  function() {
   function disableScroll() {
  if (window.addEventListener) // older FF
      window.addEventListener('DOMMouseScroll', preventDefault, false);
  window.onwheel = preventDefault; // modern standard
  window.onmousewheel = document.onmousewheel = preventDefault; // older browsers, IE
  window.ontouchmove  = preventDefault; // mobile
  document.onkeydown  = preventDefaultForScrollKeys;
  }, function() {
     if (window.removeEventListener)
        window.removeEventListener('DOMMouseScroll', preventDefault, false);
    window.onmousewheel = document.onmousewheel = null;
    window.onwheel = null;
    window.ontouchmove = null;
    document.onkeydown = null;
  }
);

$( "#myframe.fade" ).hover(function() {
  $( this ).fadeOut( 100 );
  $( this ).fadeIn( 500 );

A: As others have stated, preventDefault() works fine for your first example, where it's a div.
But this does not appear to be possible on iframes to external sites, because only certain events are captured on the iframe.
On this codepen, you can see that the mouseenter event is captured on the iframe, but the click and the wheel are not.
Pay close attention to the console.log(target) statements and which work and which do not.
Codepen

  test

CSS
iframe {
  width:600px;
  height:200px;
  border: 10px solid red;
}
div {
 width:600px;
 height:40px;
 border: 10px solid blue;
}
#div2 {
 width:600px;
 height:800px;
 border: 10px solid green;
}

JS
frame = document.getElementById('myframe');
div = document.getElementById('div1');

frame.addEventListener('mouseenter', function(e) {
  console.log('entered');
  var target = e.target;
  console.log(target);
});
frame.addEventListener('click', function(e) {
  console.log('clicked');
  var target = e.target;
  console.log(target);
});
frame.addEventListener('wheel', function(e) {
  console.log('wheel');
  var target = e.target;
  console.log(target);
});

font_size = 12;
div1.addEventListener('wheel', function(e) {
  var target = e.target;
  console.log(target);
  font_size += -e.wheelDelta/100;
  this.style.fontSize = font_size + 'px';

  if(target.id === 'div1')
    e.preventDefault();
});

Updated:
Since you say you have control over the iframe content, you can add the wheel event handler to the framed content. Try this...
HTML on the framed content

  abc

  def

  ghi

  jkl

  mno

  pqr

  stu

  vwx

  abc

  def

  ghi

  jkl

  mno

  pqr

  stu

  vwx

  abc

  def

  ghi

  jkl

  mno

  pqr

  stu

  vwx

JS on the framed content
framed = document.getElementById('framedDiv');
font_size = 12;

framed.addEventListener('wheel', function(e) {
  var target = e.target.id;
  console.log(target);
  font_size += -e.wheelDelta/100;
  this.style.fontSize = font_size + 'px';
  e.preventDefault();
});

A: Add a listener for window (the iframe's parent) and try this:
window.addEventListener("wheel", function () {

    if ($("#myframe").is(":hover")) {

        // call iframe zoom function here

        return false;

    }

});

When the mouse is hovering over the iframe, return false on the window scroll but execute the zoom.


text:
Q: A partitioning scheme for ubuntu server I am setting up an ubuntu server to be used for experimentation, testing and learning. Basically with LAMP and then setting up WordPress and most likely Drupal. I also plan to experiment with setting up a home intranet. This system will not be serving over the Internet.
My desktop has a fairly standard /, swap, /home partitioning scheme. Would this be an adequate scheme for the server as well? Or would it be beneficial to do something fancy like creating separate partitions for /usr, /var, /tmp, and /home?
I'll probably wind up doing things like corrupting MySQL and having to start over while on my learning curve. Also, I have 2 drives and plan on setting up with software RAID0 if that matters.
Thanks.

A: For a production system it can be a good idea to put directories that can fill up quickly on  their own partitions, like /tmp/ or parts of /var.
Sometimes you want to use different file systems or file systems with different parameters for some directories, like big mail or news spools which hold very much small files.
If /usr is on its own partition it can be mounted read-only so it doesn't get corrupted at  system crashes.
For a learning system this things aren't needed - but maybe it's something you want to play with.

A: I think from your standpoint there would be no real benefit to creating more partitions outside of your standard partitioning scheme.  Your not going to be overloading the system or mapping core directories to nfs shares or seperate drives, so I don't see any benefit to it.


text:
Q: Conexión a 2 bases de datos en distintos servidores SQL SERVER Buenos días: Estoy conectando una aplicación a 2 bases de datos diferentes alojadas en distintos servidores (SQL SERVER). El problema que estoy teniendo es al cerrar la conexión a la primera para ingresar a la segunda. Al no cerrar la conexión no me reconoce el insert en la tabla de la segunda base de datos.
Estoy utilizando sql.close() para cerrar las conexiones una vez terminada cada función, pero no me funciona.
const getAsiento = async (req,res) =>{
    const pool = await getConnection();
    const result = await pool.request().query(querys.getAsiento)
    var a = result.recordset[0]
    asiento = a.jobid
    sql.close();

}

const updateAsiento = async (req,res) =>{
    const pool = await getConnection();
    const result = await pool.request().query(querys.updateAsiento)
    update = true
    sql.close();
}

const conectar = async (stn_cam, etiqueta1, asiento) => {
    const pool = await getConnectionDTA();
    const result = await pool.request()
    .input("stn_cam", sql.VarChar, stn_cam)
    .input("cam", sql.VarChar, etiqueta1)
    .input("jobid", sql.Int, asiento)
    .query(querys.cargarNombre);
    sql.close();
    console.log('Cargado en tabla');
}

Las funciones getAsiento y updateAsiento se ejecutan en la BD del primer servidor y la función conectar en la BD del segundo servidor.
Y en este orden las estoy ejecutando en la función principal:
function iniciar(){
    webcam.list(function (list) {
        var webcam1 = NodeWebcam.create({device: list[0],frames: 60, width: 960, height: 540,quality:80, delay:2})
        var webcam2 = NodeWebcam.create({device: list[5],frames: 25, width: 1600, height: 896})
        try {
            getAsiento();
            var horaFinal = obtenerHora();
            if(asiento != 0){
                var etiqueta1 = asiento + '_Camera1_' + horaFinal;
                var etiqueta2 = asiento + '_Camera2_' + horaFinal;

                updateAsiento();

                webcam1.capture(`./images/${etiqueta1}.${opts.output}`, (err, data) => {
                    if(!err) {
                        console.log('Imagen creada:', etiqueta1)
                    }else{
                        console.log(err)
                    };
                });
                webcam2.capture(`./images/${etiqueta2}.${opts.output}`, (err, data) => {
                    if(!err) {
                        console.log('Imagen creada:', etiqueta2)
                    }else{
                        console.log(err)
                    };
                });
            }
        } catch (err) {
            iniciar()
        }
    conectar(stn_cam, etiqueta1, asiento);
    asiento = 0;
    }
)};

El error que me arroja es en la función conectar, porque no reconoce la tabla, me aparece que sigo conectado en el primer servidor. ¿Qué me está faltando realizar? O de que manera tengo que cerrar la conexión a la primera BD?


text:
Q: SharePoint 2013 User Profile SYNC Mysite does export data to AD? I have been try export data of Mysite to Active Directory. In the manage user properties i have configured the mapping to export direction, but after the full sync dont update in my Active Directory.
Any one can help me?
tks.

A: There are a lot of steps to configuring Write back to AD.  I would copy the text of the article here but it copied very poorly.

A: Are you first configure the UPSA? If so, please check the below things:

*

*The Farm Account must be added to local administrator group during starting UPS service.

*Farm Account must have Log on Locally rights.
Please go to User Profile Service Application > Configure Synchronization Settings, make sure you are using SharePoint Profile Synchronization for Synchronization options. Also make sure your profile properties are mapped correctly. Here is a link about how to export data to active directory:
https://docs.microsoft.com/en-us/SharePoint/administration/configure-profile-synchronization#phase-4-configure-connections-and-export-data-to-directory-services
In addition, you can use miisclient to get more error message. Below is the default location of the miisclient:
C:\Program Files\Common Files\Microsoft Office Servers\15.0\Synchronization Service\UIShell\miisclient.exe


text:
Q: Создание блоков в kivymd Делаю приложение на python, котрое взаимодействует в SQLite добавляя или выводя записи (значения)
Прошёл через русских, английских, индуских блогеров, но не нашёл решения или примера, как созлавать блоки со значениями. Везде статическое всё.
Допустим есть таблица с фамилией, именем, возрастом и краткой информацией. Нужно, чтобы в заранее созданый шаблон блока добавлялись значения и выводиличь на экран несколько блока

A: Как оказалось очень просто. Создаём метод, который возвращает необходимые блоки. Можно в качестве параметров принимать значения, которые необходимо вставить.
from kivy.uix.button import Button
from kivymd.uix.label import MDLabel
from kivymd.uix.gridlayout import GridLayout
from kivymd.uix.boxlayout import MDBoxLayout
from kivymd.app import MDApp

class MainApp(MDApp):
    def CreateBox(self):
        bl = MDBoxLayout(orientation='vertical', padding=10)
        bl.add_widget(MDLabel(text="Hello, World", halign="center"))
        bl.add_widget(Button(text="Hello, World", pos_hint={'center_x': 0.5, 'center_y': 0.5}))
        bl.add_widget(MDLabel(text="Hello, World", halign="center"))
        return bl

    def build(self):
        gl = GridLayout(cols=3, padding=10)
        for i in range(10):
            gl.add_widget(self.CreateBox())
        return gl

MainApp().run()

А ещё я немного пошаманил и цикл перенёс в метод, который принимает количество итераций(блоков), так же можно передавать массив данных.
from kivy.uix.button import Button
from kivymd.uix.label import MDLabel
from kivymd.uix.gridlayout import GridLayout
from kivymd.uix.boxlayout import MDBoxLayout
from kivymd.app import MDApp

class MainApp(MDApp):
    def CreateBox(self, number_blocks=3):
        big_layout = GridLayout(cols = 3, padding=10)
        for i in range(number_blocks):
            bl = MDBoxLayout(orientation='vertical', padding=10)
            text_widgets = "Hello, World" + str(i)
            bl.add_widget(MDLabel(text=text_widgets, halign="center"))
            bl.add_widget(Button(text=text_widgets, pos_hint={'center_x': 0.5, 'center_y': 0.5}))
            bl.add_widget(MDLabel(text=text_widgets, halign="center"))
            big_layout.add_widget(bl)
        return big_layout

    def build(self):
        bl = GridLayout(cols=3, padding=10)
        bl.add_widget(self.CreateBox(10))
        return bl

MainApp().run()

Фото итога последней версии


text:
Q: The mapping of a Set onto the characteristic function is a bijection Let $X$ be a Set. For all Subsets $ A \subset X$ the characteristic function of A is defined as:
\begin{align}
\chi_A(x)= \begin{cases} 1 \iff x \in A \\ 0 \iff x \notin A \end{cases}
\end{align}
Let $\lbrace0,1\rbrace^X$ be the Set of functions $ X \longrightarrow \lbrace 0,1\rbrace  $. Further let $P(X)$ be the power set of $X$.
Show that the following function is a bijection:
\begin{align}
P(X) & \longrightarrow \lbrace 0,1\rbrace ^X \\
A & \longmapsto \chi_A
 \end{align}
I have struggled with this problem for a few days now and I believe one of my biggest issues is to create the desired set $\lbrace0,1\rbrace^X$.

A: $P$ is injective: Let $A,B$ be two sets with $\chi_A=\chi_B$. Then $\chi_{A\backslash B}=\chi_A-\chi_B = 0$ and thus $A\subseteq B$. In the same way $B\subseteq A$.
$P$ is surjective: Let $f\in\{0,1\}^X$, i.e. $f:X\rightarrow\{0,1\}$. Define the set $C =\{x\in X|f(x)=1\}$. Then $f=\chi_C$.


text:
Q: Encryption of Data that should be stored in a Database. And understanding the concept of the "key" used, I'm new to C# and ASP.NET and I have to do a project now. It deals with confidential data of a firm's employees so it needs to be encrypted. I am not sure if I will be able to get through with my own encryption algorithm. If I use any existing algorithms, they said that I should find a foolproof way to store the key.
To be honest, I don't really understand the term "key" in encryption. I would like someone to brief about it and help me with how I should move forward with this project.

A: http://en.wikipedia.org/wiki/Key_%28cryptography%29
dunno, but maybe start there?

A: The first rule of cryptography - never use your own algorithm, unless you are a Ph.D. and several other Ph.D's are helping you, even then, use only after public auditing.
What they mean about storing the key is that it shouldn't be exposed anywhere - if an attacker can get the key, they can decrypt all data in the database. Currently, there are no known ways to do this. You can store the key in a file outside the website's root folder - this way either the server itself must be compromised, your app must be compromised (e.g. by making it display the "../../key.txt" file, thus descending below the webroot) or your app must be tricked into encrypting/decrypting the data transparently for the attacker (e.g. by having a bug that allows authentication bypass, thus allowing them to use your app to talk to the database).
For the last part of the question, use @Haxx's answer :)

A: IMHO:

*

*as already advised, don't cobble up your "own", use existing algorithms in the framework that have been tested extensively. Whatever weaknesses they may have will (likely) still be better than what you can cobble up on your own.

*understand what needs to be encrypted which pretty much means at some point will need to be decrypted vs. data that needs to be hashed (one-way - e.g. passwords).

*decide if you want this to happen on the application side or perhaps, if resources are available to you like SQL server (to store data), on the database side (discuss this with your DBA). You can do both encryption and hashing in SQL server alone.

*on the application side, you can think about storing keys in your web.config and subsequently encrypting that section - just like the option to do so for your db connection strings (encrypting the connection section of web.config). This way even your keys aren't in plain text.


text:
Q: Refactor if statement where i have to initialize different object i'm searching the smartest way of handle this method
public boolean addAccount(String cf, AccountType type) {
    String iban = name + cf;
    if (bankAccounts.containsKey(iban)) return false;
    if (type.name().equals("CHECKINGACCOUNT")) {
        CheckingAccount cc = new CheckingAccount(cf, iban, 0);
        bankAccounts.put(iban, cc);
        return true;
    }
    if (type.name().equals("DEPOSIT")) {
        DepositAccount cd = new DepositAccount(cf, iban, 0);
        bankAccounts.put(iban, cd);
        return true;
    }
    if (type.name().equals("WEB")) {
        WebAccount cw = new WebAccount(cf, iban, 0);
        bankAccounts.put(iban, cw);
        return true;
    }
  return false;
}

AccountType is enum that contains (DEPOSIT,WEB,CHECKINGACCOUNT);
bankAccounts is an HashMap that contains iban (key) & CheckingAccounts OR DepositAccount OR WebAccount;
CheckingAccounts ,DepositAccount,WebAccount are 3 classes that inherit an abstract class called Account.
I'm trying to substitute the if with an HashMap that check the key (Type of account) with the String insert by the user and instantiates one of the three class associated to the key in the HashMap.
The problem is that i can't create the correspondence between the String and the Account because i need to instantiate that (but i don't know the cf in that moment)
Could someone show me some better way to manage it?

A: Why not put the logic for which Account to create right in the enum itself, using a factory pattern? Ever since Java 8, this pattern is really slick, as you can literally pass in the constructor as an implementation of the factory:
public boolean addAccount(String cf, AccountType type) {
    String iban = name + cf;
    if (bankAccounts.containsKey(iban)) return false;
    Account account = type.createAccount(cf, iban, 0);
    bankAccounts.put(iban, account);
    return true;
}

public enum AccountType {
    CHECKING(CheckingAccount::new),
    DEPOSIT(DepositAccount::new),
    WEB(WebAccount::new);

    private final AccountFactory factory;
    AccountType(AccountFactory factory) {
        this.factory = factory;
    }

    public Account createAccount(String cf, String iban, int x) {
        return factory.create(cf, iban, x);
    }
}

public interface AccountFactory {
    Account create(String cf, String iban, int x);
}

This solution has a huge advantage over the switch or map approach: if you ever add a new subclass and a new type of account, there is no way you can forget to handle this new type. The other solutions will fail, or give incorrect results, at runtime (instead of compile time)

A: I would advise against using any sort of type map as it just increases complexity and runtime cost. A switch statement seems the easiest.
Here is an example:
public boolean addAccount(String cf, AccountType type) {
    String iban = name + cf;
    if (bankAccounts.containsKey(iban)) return false;
    Account account;
    switch(type) {
      case CHECKINGACCOUNT:
        account = new CheckingAccount(cf, iban, 0);
        break;
      case DEPOSIT:
        account = new DepositAccount(cf, iban, 0);
        break;
      case WEB:
        account = new WebAccount(cf, iban, 0);
        break;
      default:
         return false;
   }
   bankAccounts.put(iban, account);
   return true;
}

However, if you are determined to use a type map:
static Map<AccountType, Class> TYPE_MAP = new HashMap<>()
{
   {AccountType.CHECKINGACCOUNT, CheckingAccount.class},
   {AccountType.DEPOSIT, DepositAccount.class},
   {AccountType.WEB, WebAccount.class}
};

public boolean addAccount(String cf, AccountType type) {
    String iban = name + cf;
    if (bankAccounts.containsKey(iban)) return false;
    if (!TYPE_MAP.containsKey(type)) return false;
    Class classType = TYPE_MAP.get(type);
    Account account = (Account)classType
      .getDeclaredConstructor(
        String.class,
        String.class,
        Integer.class)
      .newInstance(cf, iban, 0);
    bankAccounts.put(iban, account);
    return true;
}

A: My opinion is that conceptually everything is fine with this method. I would change it a bit though:
   public boolean addAccount(String cf, AccountType type) {
    String iban = name + cf;
    if (bankAccounts.containsKey(iban)) return false;

    Account ac;
    if (type == CHECKING) {
        ac = new CheckingAccount(cf, iban, 0);
    } else if (type == DEPOSIT) {
        ac = new DepositAccount(cf, iban, 0);
    } else if (type == WEB) {
        ac = new WebAccount(cf, iban, 0);
    }
    bankAccounts.put(iban, cc);
    return true;
}

I do not see any reasons to make it more complex using reflection or factories to create acount instances. It will not give you any benefit, you will just get more code and new person will spend more time to understand it.


text:
Q: Liferay Portal don't send object from process phase to jsp i'm new in liferay, and now i'm learning Liferay with liferaycookbook. I have a problem with send object from porlet to jsp page
here's my porlet,.In LibraryPortlet.java i have a function:
public void searchBooks(ActionRequest actionRequest,
        ActionResponse actionResponse) throws IOException, PortletException {

    String searchTerm = ParamUtil.getString(actionRequest, "searchTerm");

    if (Validator.isNotNull(searchTerm)) {
        try {
            List<LMSBook> lmsBooks = LMSBookLocalServiceUtil
                    .searchBooks(searchTerm);

            actionRequest.setAttribute("SEARCH_RESULT", lmsBooks);
            actionRequest.setAttribute("test", "sentence to test");
            actionResponse.setRenderParameter("jspPage",
                    LibraryConstants.PAGE_LIST);

        } catch (SystemException e) {
            e.printStackTrace();
        }
    }
}

in file list.jsp, i have
List<LMSBook> booksTemp = (List<LMSBook>) request
        .getAttribute("SEARCH_RESULT");

List<LMSBook> books = Validator.isNotNull(booksTemp) ? ListUtil
        .copy(booksTemp) : LMSBookLocalServiceUtil.getLMSBooks(0,
        LMSBookLocalServiceUtil.getLMSBooksCount());
System.out.println("test: "+ request.getAttribute("test"));

in list.jsp, booksTemp is null because liferay can't send my object from LibraryPortlet.java to jsp, i try to send the string "sentence to test", but in console, it shows test: null
Anybody have had same problem, can you help me, please!

A: You must first use the correct request to set your attribute. The problem is that in the LibraryPortlet, you are using a type of PortletRequest and the object in the JSP is a HttpServletRequest.
For your case, in LibraryPortlet.java, do the following:
HttpServletRequest request = PortalUtil.getHttpServletRequest(actionRequest);

request.setAttribute("SEARCH_RESULT", lmsBooks);

This also goes for any other attribute you are setting.