Q: Dynamically updating string from one div to another I have a list of divs that contain a string in h3 format. Upon clicking these divs (they are all the same class) a screen is displayed (part of the same html doc) containing some sliders for user input.
Is there a way to make it so that when the screen is displayed it contains the string of whatever div was clicked? In other words, if the user taps/clicks the "Push Ups" card, I would like the div "#info" to update to shoe "push Ups", if the user selects "Iquats" I would like "#info" to show "Squats" ec.
I can't think of a way to do this without using JSON or some sort of server magic. CODE!
HTML:

Select Exercise

Push Ups

Dips

Burpees

Plank

Sit Ups

Leg Ups

Russian Twists

Back Raises

Time:

      <output id="timeValue">60 sec.</output>
      <input type="range" id="determineTime" step="10" value="60" min="0" max="180" />

Rest Time:

      <output id="restValue">10 sec.</output>
      <input type="range" id="determineRest" step="10" value="10" min="0" max="180" />

Add Break

JavaScript (jQuery)
  $(".exercise").click(function()
  {
    $("#specifier").css("display", "block");
    $(".backButton").css("display", "none");
  });

Thanks for any help and ideas given!

A: It would be preferable to create the elements programatically.
var arrExercises = ['Push Ups', 'Dips', 'Burpees'];//add all exercises here
arrExercises.forEach(function(exercise, i){
    var $exercise = $('
', {id:'div-excercise-'+i, "class":'exercise'});//create the exercise element
    //give the on click handler to the exercise
    $exercise.on('click', function(e){
        $("#specifier").css("display", "block");
        $(".backButton").css("display", "none");
        $("#info").text(exercise);//set the info to the exercise text
    });
    $('#exerciseContainer').append($exercise);//append this exercise to the container
});

A: If I understand you correctly, you can get the clicked element text by using $(this).text() inside the click event.

$(function() {
  $('.exercise').click(function() {
    $('#info').text($(this).text());
  });
});

Select Exercise

Push Ups

Dips

Burpees

Plank

Sit Ups

Leg Ups

Russian Twists

Back Raises

Time:

      <output id="timeValue">60 sec.</output>
      <input type="range" id="determineTime" step="10" value="60" min="0" max="180" />

Rest Time:

      <output id="restValue">10 sec.</output>
      <input type="range" id="determineRest" step="10" value="10" min="0" max="180" />

Add Break


Q: How to push into an existing session array , key and value in laravel With php I used
if (!isset($_SESSION['cart']) || !isset($_SESSION['cart'][$product])) {
    $_SESSION['cart'][$product] = 0;
    $_SESSION['cart'][$product] = $_SESSION['cart'][$product] + $product_quantity;

}else{
    $_SESSION['cart'][$product] = $_SESSION['cart'][$product] + $product_quantity;
}

I tried with put() but it's not working, cause every time I try to insert a new value it replace the first one
session()->put('cart',[request('variant_id') => request('quantity')]);

With push() I put inside the array cart another array with key and value
session()->push('cart',[request('variant_id') => request('quantity')]);

Is there a way to insert into session array with key and value cause right now I can't figure it out how to do it


Q: How to Display plain text of api result ( noob question ) I am completely new to api.
I want to display the plain text response of the output of this:
https://vurl.com/api.php?url=https://google.com
to my webpage html but it's not working.
My code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>

$url = urlencode('https://google.com');
$api_url = 'vurl.com/api.php?url='.$url;
$arr_output = json_decode(file_get_contents($api_url), true);
document.write($arr_output);
</script>

Thanks

A: Not really sure why you're mixing javascript with your php code. Nevertheless, this is the approach you should follow:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>

<?php
$url = urlencode("https://google.com");
$api_url = "vurl.com/api.php?url=".$url;
$arr_output = json_decode(file_get_contents($api_url), true);

echo $arr_output;
?>

</script>


Q: overlaying a div over three floats I need a bit of help overlaying a
 over 3 other
 elements which are styled float:left in their own container.
It looks like this now (http://i.imgur.com/2xk4tax.jpg) and i would like the text to overlay on top of the three floated colorlines.
Here's my hmtl/css any help would be appreciated.
HTML

hi

CSS
#introtextcontainer {
    margin: 0px auto 0px auto;
    width: 500px;
    height: 100px ;
    text-align:center;
    font-color: black;
    float:middle;
}

#linecontainer {
    margin: 0px auto 0px auto;
    width: 500px;
    height: 3000px ;
}

#line1 {
    width:160px;
    height:2000px;
    background-color: #00A7B0;
    float:left;
}

#line2 {
    width:160px;
    height:2000px;
    background-color: #D1DE3E;
    float:left;
}

#line3{
    width:160px;
    height:2000px;
    background-color: #DE006B;
    float:left;
}

A: By just adding position:absolute and width:100% to your introtextcontainer container it seems to work:
#introtextcontainer {
    margin: 0px auto 0px auto;
    height: 100px;
    text-align:center;
    font-color: black;
    position:absolute;
    width:100%;
}

jsFiddle example
Note that there is no such float:middle; property (left or right only).

A: You could also position:absolute the #linecontainer to slide up behind the text (I also centered it with left:50%; margin-left:- 0.5 * width ). You might have to give the text a position:relative; z-index:1; to force it on top.
#introtextcontainer {
    margin: 0px auto 0px auto;
    height: 100px;
    text-align:center;
    font-color: black;
    position:relative;
    width:100%;
    z-index:1;
}
#linecontainer {
    margin: 0 0 0 -250px;
    width: 500px;
    height: 3000px;
    position:absolute;
    top:0;
    left:50%;
}

Or even better, use a gradient generator, remove the 3 divs and make the bars a background: http://www.colorzilla.com/gradient-editor/
#introtextcontainer {
    margin: 0px auto 0px auto;
    height: 100px;
    text-align:center;
    font-color: black;
    position:absolute;
    width:100%;
    background: rgb(0,167,176); /* Old browsers */
    /* IE9 SVG, needs conditional override of 'filter' to 'none' */
    background: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/Pgo8c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgdmlld0JveD0iMCAwIDEgMSIgcHJlc2VydmVBc3BlY3RSYXRpbz0ibm9uZSI+CiAgPGxpbmVhckdyYWRpZW50IGlkPSJncmFkLXVjZ2ctZ2VuZXJhdGVkIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgeDE9IjAlIiB5MT0iMCUiIHgyPSIxMDAlIiB5Mj0iMCUiPgogICAgPHN0b3Agb2Zmc2V0PSIzMyUiIHN0b3AtY29sb3I9IiMwMGE3YjAiIHN0b3Atb3BhY2l0eT0iMSIvPgogICAgPHN0b3Agb2Zmc2V0PSIzMyUiIHN0b3AtY29sb3I9IiNkMWRlM2UiIHN0b3Atb3BhY2l0eT0iMSIvPgogICAgPHN0b3Agb2Zmc2V0PSIzNCUiIHN0b3AtY29sb3I9IiNkMWRlM2UiIHN0b3Atb3BhY2l0eT0iMSIvPgogICAgPHN0b3Agb2Zmc2V0PSI2NiUiIHN0b3AtY29sb3I9IiNkMWRlM2UiIHN0b3Atb3BhY2l0eT0iMSIvPgogICAgPHN0b3Agb2Zmc2V0PSI2NiUiIHN0b3AtY29sb3I9IiNkZTAwNmIiIHN0b3Atb3BhY2l0eT0iMSIvPgogIDwvbGluZWFyR3JhZGllbnQ+CiAgPHJlY3QgeD0iMCIgeT0iMCIgd2lkdGg9IjEiIGhlaWdodD0iMSIgZmlsbD0idXJsKCNncmFkLXVjZ2ctZ2VuZXJhdGVkKSIgLz4KPC9zdmc+);
    background: -moz-linear-gradient(left,  rgba(0,167,176,1) 33%, rgba(209,222,62,1) 33%, rgba(209,222,62,1) 34%, rgba(209,222,62,1) 66%, rgba(222,0,107,1) 66%); /* FF3.6+ */
    background: -webkit-gradient(linear, left top, right top, color-stop(33%,rgba(0,167,176,1)), color-stop(33%,rgba(209,222,62,1)), color-stop(34%,rgba(209,222,62,1)), color-stop(66%,rgba(209,222,62,1)), color-stop(66%,rgba(222,0,107,1))); /* Chrome,Safari4+ */
    background: -webkit-linear-gradient(left,  rgba(0,167,176,1) 33%,rgba(209,222,62,1) 33%,rgba(209,222,62,1) 34%,rgba(209,222,62,1) 66%,rgba(222,0,107,1) 66%); /* Chrome10+,Safari5.1+ */
    background: -o-linear-gradient(left,  rgba(0,167,176,1) 33%,rgba(209,222,62,1) 33%,rgba(209,222,62,1) 34%,rgba(209,222,62,1) 66%,rgba(222,0,107,1) 66%); /* Opera 11.10+ */
    background: -ms-linear-gradient(left,  rgba(0,167,176,1) 33%,rgba(209,222,62,1) 33%,rgba(209,222,62,1) 34%,rgba(209,222,62,1) 66%,rgba(222,0,107,1) 66%); /* IE10+ */
    background: linear-gradient(to right,  rgba(0,167,176,1) 33%,rgba(209,222,62,1) 33%,rgba(209,222,62,1) 34%,rgba(209,222,62,1) 66%,rgba(222,0,107,1) 66%); /* W3C */
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#00a7b0', endColorstr='#de006b',GradientType=1 ); /* IE6-8 */

}


Q: (AudioManager)getSystemService(Context.AUDIO_SERVICE) causing memory leak I had memory leak that was being caused by AudioManager. So I've commented out this line in my code to see if it would solve my problem:
public class FireRoomActivity extends Activity {

AudioManager am;
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
  }
}

And it did solve the problem and I don't have memory leak any more. Is that because of Context.AUDIO_SERVICE? If yes then how could I replace it?
If it matters, I have this non-static class inside my activity that is not used elsewhere outside
class GestureListener extends GestureDetector.SimpleOnGestureListener {
RelativeLayout parentLayout;

public void setLayout(RelativeLayout layout){
    parentLayout = layout;  }
@Override
public boolean onDown(MotionEvent e) {
    return true;
}
// event when double tap occurs
@Override
public boolean onDoubleTap(MotionEvent e) {
    makeArrowsVisible();
    parentLayout.findViewById(R.id.cabinet_zoomed).setVisibility(View.INVISIBLE);
    Button key = (Button)parentLayout.findViewById(R.id.key);
    if(key!=null){
        key.setVisibility(View.INVISIBLE);}
    return true;
}

Edit:
screenshot of heap dump

A: Fix mentioned in https://gist.github.com/jankovd/891d96f476f7a9ce24e2 worked for me.
public class ActivityUsingVideoView extends Activity {

  @Override protected void attachBaseContext(Context base) {
    super.attachBaseContext(AudioServiceActivityLeak.preventLeakOf(base));
  }
}

/**
 * Fixes a leak caused by AudioManager using an Activity context.
 * Tracked at https://android-review.googlesource.com/#/c/140481/1 and
 * https://github.com/square/leakcanary/issues/205
 */
public class AudioServiceActivityLeak extends ContextWrapper {

  AudioServiceActivityLeak(Context base) {
    super(base);
  }

  public static ContextWrapper preventLeakOf(Context base) {
    return new AudioServiceActivityLeak(base);
  }

  @Override public Object getSystemService(String name) {
    if (Context.AUDIO_SERVICE.equals(name)) {
      return getApplicationContext().getSystemService(name);
    }
    return super.getSystemService(name);
  }
}

Thanks to Dejan Jankov :)

A: You can avoid memory leak using application context to get audio service.

A: I found in another post that the AudioManager does keep a strong reference, but will still be properly garbage collected. See this google group conversation. Here's what I get out of it:
This means that if you manually launch a couple of garbage collections through the DDMS tab in Eclipse just before taking the head dump, this reference should not be there anymore.
This indeed solved the "problem" for me, as it turned out not to be a problem after all...
It was also mentionned that the debugger should not be on hook (i.e. use Run As... instead of Debug As...). The debugger being active could cause the references to be held by the AudioManager, thus creating a heap overflow (I have not tested this affirmation).


Q: Dynamically List contents of a table in database that continously updates It's kinda real-world problem and I believe the solution exists but couldn't find one.
So We, have a Database called Transactions that contains tables such as Positions, Securities, Bogies, Accounts, Commodities and so on being updated continuously every second whenever a new transaction happens. For the time being, We have replicated master database Transaction to a new database with name TRN on which we do all the querying and updating stuff.
We want a sort of monitoring system (  like htop process viewer in Linux) for Database that dynamically lists updated rows in tables of the database at any time.
TL;DR Is there any way to get a continuous updating list of rows in any table in the database?
Currently we are working on Sybase & Oracle DBMS on Linux (Ubuntu) platform but we would like to receive generic answers that concern most of the platform as well as DBMS's(including MySQL) and any tools, utilities or scripts that can do so that It can help us in future to easily migrate to other platforms and or DBMS as well.

A: To list updated rows, you conceptually need either of the two things:

*

*The updating statement's effect on the table.

*A previous version of the table to compare with.

How you get them and in what form is completely up to you.
The 1st option allows you to list updates with statement granularity while the 2nd is more suitable for time-based granularity.
Some options from the top of my head:

*

*Write to a temporary table

*Add a field with transaction id/timestamp

*Make clones of the table regularly

AFAICS, Oracle doesn't have built-in facilities to get the affected rows, only their count.

A: Not a lot of details in the question so not sure how much of this will be of use ...

*

*'Sybase' is mentioned but nothing is said about which Sybase RDBMS product (ASE? SQLAnywhere? IQ? Advantage?)

*by 'replicated master database transaction' I'm assuming this means the primary database is being replicated (as opposed to the database called 'master' in a Sybase ASE instance)

*no mention is made of what products/tools are being used to 'replicate' the transactions to the 'new database' named 'TRN'

So, assuming part of your environment includes Sybase(SAP) ASE ...

*

*MDA tables can be used to capture counters of DML operations (eg, insert/update/delete) over a given time period

*MDA tables can capture some SQL text, though the volume/quality could be in doubt if a) MDA is not configured properly and/or b) the DML operations are wrapped up in prepared statements, stored procs and triggers

*auditing could be enabled to capture some commands but again, volume/quality could be in doubt based on how the DML commands are executed

*also keep in mind that there's a performance hit for using MDA tables and/or auditing, with the level of performance degradation based on individual config settings and the volume of DML activity

Assuming you're using the Sybase(SAP) Replication Server product, those replicated transactions sent through repserver likely have all the info you need to know which tables/rows are being affected; so you have a couple options:

*

*route a copy of the transactions to another database where you can capture the transactions in whatever format you need [you'll need to design the database and/or any customized repserver function strings]

*consider using the Sybase(SAP) Real Time Data Streaming product (yeah, additional li$ence is required) which is specifically designed for scenarios like yours, ie, pull transactions off the repserver queues and format for use in downstream systems (eg, tibco/mqs, custom apps)

I'm not aware of any 'generic' products that work, out of the box, as per your (limited) requirements.  You're likely looking at some different solutions and/or customized code to cover your particular situation.


Q: Choosing a model for machine learning problem Update: See bottom of question for insight into the real application which this small example is attempting to simplify.

Questin:
In the different machine learning libraries, what kind of model suits the following problem? Here's a simplified version:
The algorithmic connection (which the model will hopefully learn) between X and y is as follows:
If X[i][0] != X[i][2] ----------------> y[i] is 0

If X[i][0] == X[i][2] ----------------> y[i] is 10

If X[i][0] == X[i][1] == X[i][2] -----> y[i] doubles (to 20 in this simplified example)

I've had some success with categorical outputs; in this example there are three output categories "0", "10", or "20".
In that case the model looked something like this:
inputs = keras.Input(shape=(3,), name="input")
x = keras.regularizers.l1_l2(0.01)
x = layers.Dense(64, activation="relu", name="dense_1")(inputs)
outputs = layers.Dense(3, activation="sigmoid", name="predictions")(x)
model = keras.Model(inputs=inputs, outputs=outputs)

x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=.2)

y_train = keras.utils.to_categorical(y_train, 3)
y_test = keras.utils.to_categorical(y_test, 3)

model.compile(
    optimizer=keras.optimizers.Nadam(),
    loss=keras.losses.BinaryCrossentropy(),
    metrics=[keras.metrics.BinaryAccuracy()],
)

history = model.fit(
    x_train,
    y_train,
    batch_size=16,
    epochs=50)

But if the relationship between X and y is more complex e.g. there are 100 different outputs, would it still be advisable to use categorical output?

Update 1: More realistic example to illustrate the actual problem?
Putting together two users user1 (blue), user2 (pink) and a conversation starter question question1 (yellow): Assume the more similar the users are in profile, the higher the satisfaction-score of the conversation (y), and also if the question matches the users the score goes up (doubles in the simple example, y = y*2).
I posted a more realistic version of the problem here on Cross Validated some days ago. I hope it sheds light on the type of problem, and helps identify the right ML-approach given real data from users, questions and their conversations.
The goal of the real-world application is to understand which conversation starter questions fit to which user combinations. Real world conversation satisfaction could be the length of the conversation following a conversation starter question.
So we would like to predict: What conversation starter question should be asked given the two users who are about to talk.

A: I now have something that works for this simple example. The improvement lies in the preprocessing with preprocessing.StandardScaler().fit(y_rshaped). I was inspired by the preprocessing documentation which says:

Standardization of datasets is a common requirement for many machine learning estimators implemented in scikit-learn; they might behave badly if the individual features do not more or less look like standard normally distributed data: Gaussian with zero mean and unit variance.

Here's the working code for the simple example in the question:
import random
import numpy as np

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers

from sklearn import preprocessing
from sklearn.model_selection import train_test_split
import itertools

X_data = list((itertools.product([0, 1], repeat=3)))*100
random.shuffle(X_data)
print(X_data[0:8])
print("length of X_data = ", len(X_data))

[(1, 0, 0), (0, 0, 0), (1, 0, 0), (0, 0, 1), (0, 1, 0), (1, 1, 1), (0, 0, 0), (0, 1, 0)]
length of X_data =  800

scorelist = []
for tup in X_data:
    score = 0
    if tup[0] == tup[2]:
        score += 10
        if tup[0] == tup[1]:
            score = score*2
    scorelist.append(score)
print("y values are: ", scorelist[0:10])

y values are:  [0, 20, 0, 0, 10, 20, 20, 10, 20, 0]

This is the preprocessing part that improved the results:
X = np.array(X_data)
y = np.array(scorelist)
y_reshaped = y.reshape(-1, 1)
scaler = preprocessing.StandardScaler().fit(y_reshaped)
y_transformed = scaler.transform(y_reshaped)

Here the model: It runs/learns in 30 seconds on my slow computer (anno 2007).
inputs = keras.Input(shape=(3,), name="digits")
x = keras.regularizers.l1_l2(0.01)
x = layers.Dense(8, activation="relu", name="dense_1")(inputs)
outputs = layers.Dense(1, activation="linear", name="predictions")(x)
model = keras.Model(inputs=inputs, outputs=outputs)

x_train, x_test, y_train, y_test = train_test_split(X, y_transformed, test_size=.2)

# Reserve 200 samples (out of 800) for validation
x_val = x_train[-200:]
y_val = y_train[-200:]
x_train = x_train[:-200]
y_train = y_train[:-200]

model.compile(
    optimizer=keras.optimizers.Adam(),
    loss=keras.losses.MeanSquaredError()
)
history = model.fit(
    x_train,
    y_train,
    batch_size=8,
    epochs=150
)

Epoch 1/150 [======] - loss: 1.4777
Epoch 2/150 [======] - loss: 1.1794
Epoch 3/150 [======] - loss: 1.0652
...
Epoch 150/150 [======] - loss: 8.6565e-14

Finally we predict X and compare to the real y values:
predictions = model.predict(X)

prediction_list = scaler.inverse_transform(predictions).astype(int).tolist()
prediction_deviation = [[(a[0]-b[0])] for a, b in zip(prediction_list, y_reshaped)]
print("predicted:", prediction_list[0:10])
print("real value:", y_reshaped.tolist()[0:10])
print("deviation:", prediction_deviation[0:10])

predicted: [[0], [20], [0], [0], [9], [19], [20], [9], [20], [0]]
real value: [[0], [20], [0], [0], [10], [20], [20], [10], [20], [0]]
deviation: [[0], [0], [0], [0], [-1], [-1], [0], [-1], [0], [0]]

The deviations are negligible for my purposes as it's clear which predictions are 0, 10 or 20.


Q: New browser tabs for pdf files from glob-created list? To list a large number of sheet-music pdfs on a website, I'm using this at the top of my php/html file:
<?php
header('Content-Type: text/html; charset=utf-8');
function getFiles(){
    $files=array();
    if($dir=opendir('.')){
        while($file=readdir($dir)) {
            if($file!='.' && $file!='..'){
                $files[]=($file);
            }
        }
        closedir($dir);
    }
    natsort($files); //sort
    return $files;
}
?>

... then in the ul bit of the html section I have this:
 <? foreach (glob("*.pdf") as $file)
    echo "
$file
";
    ?>

It works fine, except that when clicked, the pdf replaces the web page content in the browser, and I would prefer it to appear in a separate browser tab.
I've tried inserting "_blank" in various places but it kills the page, so I'm obviously not doing it right (I'm a musician, not a programmer!).
Similar questions on here seem to relate to different set-ups and I don't have the knowledge to apply the answers to my situation.
How can I get my otherwise successful website set-up to trigger a new browser tab for each tune clicked?  Thanks.

A: "I've tried inserting "_blank" in various places" -- the correct place is in the a element:
The code of your template should read:
<?php
foreach (glob("*.pdf") as $file) {
    echo '
'.$file.'
';
}
?>


Q: Assignment of defaults to field not working I am using ArcGIS 10.2.2 for Desktop.
I have assigned default values to some fields in a feature class, which is sitting in a file geodatabase.
I used the "Assign Default To Field Tool", which claims to have been successful, yet when I go to create a new feature none of the default values populate in the fields.
When I check the field properties it shows the default value that I assigned, it just doesn't use them.
I do have domains assigned to the fields in question, and the default values I have chosen do conform to the coded values within the domains.
I am also using a subtype within the feature class, but I can't see why that would be interfering.
I think I have covered all relevant information, just ask if I have missed something.

A: By global, I mean domains and default values that are shared between all subtypes.
What I've noticed is that if in the Fields tab you set all your global domains and default values BEFORE you create the subtypes, then these settings will be present for each subtype when you create them.
But, if you create the subtypes BEFORE you set the domains and default values in the Fields tab, they will not be present and you'll need to set them individually for each subtype.
Another way to do this is to set the Default Subtype in the Subtypes tab, and set all the global domains and default values for the default subtype. Then for each additional subtype other than the default, click the Use Defaults button. This will set the domains and default values equal to the ones in the default subtype. From there you can set any unique domains and default values for each subtype.
If you're creating a new feature class, I'd recommend setting all the global domains and default values in the Fields tab, then creating the subtypes, and then setting any unique domains and default values for each subtype.
But, of course, there's more than one way to do everything.


Q: Can we use props to pass variable in vue? Slall question:
I have a 2 parent components nesting the same child component inside of them.
I use props so the parents can tell the child what title to show.
this child component is a photo gallery. It makes a query to the database, download photos and show them up. classic.
I need the parents to tell the child where to get the photos from:
Get the photos from All users, for the home page
or
get only the photos from a specific user for a user's page.
I'm wondering if I can pass this information through a prop.
Is that possible? Can we use the info from a prop as a varialble inside of the setup() function?
Is there a better way to do this?

A: Passing objects from one component to a child component is the purpose of props.
You can pass many items through props. VueJS has the following types built-in:

*

*String

*Number

*Boolean

*Array

*Object

*Function

*Promise

In the V3 VueJS guide it gives the following example of a prop being passed into a component and then being logged to the console inside the setup() method.
export default {
  props: {
    title: String
  },
  setup(props) {
    console.log(props.title)
  }
}

However, when using props, you should always mark whether the is required, what its type is and what the default is if it is not required.
For example:
export default {
  props: {
    title: String, // This is the type
    required: false, // If the prop is required
    default: () => 'defaultText' // Default needed if required false
  },
  setup(props) {
    console.log(props.title)
  }
}

It's important to note that when using default, the value must be returned from a function. You cannot pass a default value directly.


Q: Uncaught ReferenceError: jQuery is not defined at file I am using phonegap and every time it gives me error at this line .I am trying to submit the form through phonegap , javascript works but with jquery it always me this errro Uncaught ReferenceError: jQuery is not defined at file
  jQuery(function() {

Here Is my code
<!DOCTYPE HTML>
<html>
  <head>

  <script type="text/javascript" charset="utf-8" src="cordova-1.5.0.js">
  </script>
  <script type="text/javascript" src="jquery-1.6.4.min.js"></script>

  <script>
  function validation()
  {
    alert('validation');
  }

  jQuery(function() {

    alert("login");
    /* stop form from submitting normally */
    event.preventDefault();

    /*clear result div*/

    /* get some values from elements on the page: */
    //var values = $(this).serialize();
    var values = "user";
    /* Send the data using post and put the results in a div */
    jQuery.ajax({
      url: server_url,
      type: "post",
      data: values,
      success: function() {
        alert("success");
        jQuery("#result").html('submitted successfully');
      },
      error: function() {
        alert("failure");
        jQuery("#result").html('there is error while submit');
      }
    });
  });

  </script>
</head>

A: You need to have jQuery file in the folder your current page is, also try to get the latest jQuery file you are using quite old, you can download latest here.

A: Is Cordova based on jQuery ? If so, you have to include jQuery first.
If not, your jQuery file is probably not found. Press Ctrl+u to see the source code, and then click on the link jquery-1.6.4.min.js in the head, and see if it opens your file ?


Q: K-Means Clustering having error of "Too many indexers" when multiple columns are given The code below is of K-Means Clustering copied from www.analyticsvidhya.com
K=3

# Select random observation as centroids
Centroids = (X.sample(n=K))
plt.scatter(X["DATE_ID"],X.iloc[:,-1],c='black')
plt.scatter(Centroids["DATE_ID"],Centroids.iloc[:,-1],c='red')
plt.xlabel('Number of Days')
plt.ylabel('POI1 Sales')
plt.show()

Output of above code

diff = 1
j=0

while(diff!=0):
    XD=X
    i=1
    for index1,row_c in Centroids.iterrows():
        ED=[]
        for index2,row_d in XD.iterrows():
            d1=(row_c["DATE_ID"]-row_d["DATE_ID"])**2
            d2=(row_c.iloc[:,-1]-row_d.iloc[:,-1])**2
            d=np.sqrt(d1+d2)
            ED.append(d)
        X[i]=ED
        i=i+1

C=[]
for index,row in X.iterrows():
    min_dist=row[1]
    pos=1
    for i in range(K):
        if row[i+1] < min_dist:
            min_dist = row[i+1]
            pos=i+1
    C.append(pos)
X["Cluster"]=C
Centroids_new = X.groupby(["Cluster"]).mean()[[X.iloc[:,-1],"DATE_ID"]]
if j == 0:
    diff=1
    j=j+1
else:
    diff = (Centroids_new[:,-1] - Centroids[:,-1]).sum() + (Centroids_new['DATE_ID'] - Centroids['DATE_ID']).sum()
    print(diff.sum())
Centroids = X.groupby(["Cluster"]).mean()[[X.iloc[:,-1],"DATE_ID"]]

The error I am having:
---------------------------------------------------------------------------
IndexingError                             Traceback (most recent call last)
<ipython-input-24-19f3132fec6e> in <module>()
      9         for index2,row_d in XD.iterrows():
     10             d1=(row_c["DATE_ID"]-row_d["DATE_ID"])**2
---> 11             d2=(row_c.iloc[:,-1]-row_d.iloc[:,-1])**2
     12             d=np.sqrt(d1+d2)
     13             ED.append(d)

3 frames
/usr/local/lib/python3.7/dist-packages/pandas/core/indexing.py in _validate_key_length(self, key)
    790     def _validate_key_length(self, key: Sequence[Any]) -> None:
    791         if len(key) > self.ndim:
--> 792             raise IndexingError("Too many indexers")
    793
    794     def _getitem_tuple_same_dim(self, tup: tuple):

IndexingError: Too many indexers

The problem
How can I pass multiple columns in it? the 1st column I have is DATE_ID (it's in float format) and the other columns are sales of different stores (also in float format)
I'm trying to implement this code but the code mentioned in the link before is implemented on only 2 columns, whereas I have to implement it on multiple columns while keeping the DATE_ID column fixed.

A: Here's scikit learns' k-means:
from sklearn.cluster import KMeans
import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv('stack_overflow.csv')
X = df.iloc[:,1:]

plt.scatter(
   X['DATE_ID'], X.iloc[:, -1],
   c='white', marker='o',
   edgecolor='black', s=50
)
plt.show()

k = 3

km = KMeans(
    n_clusters=k, init='random',
    n_init=10, max_iter=300,
    tol=1e-04, random_state=0
)
y_km = km.fit_predict(X)
X['label'] = y_km

Output:

Now use the labels to graph the clusters:
import matplotlib.pyplot as plt
# plot the 3 clusters
plt.scatter(
    X[X['label'] == 0]['DATE_ID'], X[X['label'] == 0].iloc[:,-2],
    s=50, c='lightgreen',
    marker='s', edgecolor='black',
    label='cluster 1'
)

plt.scatter(
    X[X['label'] == 1]['DATE_ID'], X[X['label'] == 1].iloc[:,-2],
    s=50, c='orange',
    marker='o', edgecolor='black',
    label='cluster 2'
)

plt.scatter(
    X[X['label'] == 2]['DATE_ID'], X[X['label'] == 2].iloc[:,-2],
    s=50, c='lightblue',
    marker='v', edgecolor='black',
    label='cluster 3'
)

# plot the centroids
plt.scatter(
    km.cluster_centers_[:, 0], km.cluster_centers_[:, 1],
    s=250, marker='*',
    c='red', edgecolor='black',
    label='centroids'
)
plt.legend(scatterpoints=1)
plt.grid()
plt.show()

Output:


Q: Rails validate uniqueness between two models I'm still new to rails and I'm having trouble validating across models.
I have two models, Artists and Songs associated with a many to many relationship. I would like to have a validation in the song model that checks that song url_slug is unique for each artist.  I have tried using :scope but I don't seem to be able to call the associated artist id.
I'm pretty lost here so any help would be appreciated.
Thanks,
Here is my song model:
class Song< ActiveRecord::Base
 has_and_belongs_to_many:artists

 #creates Url Slug
 #before_create :generate_slug

 before_update :generate_slug

 validates_uniqueness_of :song_url_slug, :scope => self.artist.id

   protected
 def generate_slug
     self.song_url_slug = song_name.gsub(/\W+/, ' ').strip.downcase.gsub(/\ +/, '-')
 end

#def url_slug_uniqueness
  #artist_song = self.song_name.find(:artist_id])
     #if self.exists?(:conditions => {:song_name => artist_song})
      # errors.add(:song_name, :name_taken, :song_name=> "#{artist_song}1")
    #end
# end
#end

A: The first thing to do is try getting rid of the before_create :generate_slug and before_update :generate_slug lines and replace them with
  before_validation :generate_slug

Your uniqueness validation may work then.


Q: Regex Java word context what I want to achieve is that I want to obtain the context of an acronym. Can you help me pls with the regular expression?
I am looping over the text (String) and looking for dots, after match I am trying to get the context of the particular found acronym, so that I can do some other processing after that, but I cant get the context. I need to take at least 5 words before and 5 words after the acronym.
//Pattern to match each word ending with dot
    Pattern pattern = Pattern.compile("(\\w+)\\b([.])");

    Matcher matchDot = pattern.matcher(textToCorrect);
    while (matchDot.find()) {
        System.out.println("zkratka ---"+matchDot.group()+" ---");

        //5 words before and after tha match = context
     //   Matcher matchContext = Pattern.compile("(.{25})("+matchDot.group()+")(.{25})").matcher(textToCorrect);
        Pattern patternContext = Pattern.compile("(?:[a-zA-Z'-]+[^a-zA-Z'-]+){0,10}"+matchDot.group()+"(?:[^a-zA-Z'-]+[a-zA-Z'-]+){0,10}");
        Matcher matchContext = patternContext.matcher(textToCorrect);
        if (matchContext.find()) {
             System.out.println("context: "+matchContext.group()+" :");

    //       System.out.println("context: "+matchContext.group(1)+" :");
    //       System.out.println("context: "+matchContext.group(2)+" :");
        }

    }

Example:
input:
Some 84% of Paris residents see fighting pol. as a priority and 54% supported a diesel ban in the city by 2020, according a poll carried out for the Journal du Dimanche.
output:
1-st regex will find pol.
2-nd regex will find "of Paris residents see fighting pol. as a priority and 54%"
Another example with more text
I need to loop through this once and every time I match an acronym to get the context of this particular acronym. After that I am processing some datamining. Here's the original text

neklidná nemocná, vyš. je možné provést pouze nativně
Na mozku je patrna hyperdenzita v počátečním úseku a. cerebri media
  vlevo, vlevo se objevuje již smazání hranic mezi bazálními ganglii a
  okolní bílou hmotou a mírná difuzní hypointenzita v periventrikulární
  bílé hmotě. Kromě těchto čerstvých změn jsou patrné  staré
  postmalatické změny temporálně a parietookcipitálně vlevo. Oboustranně
  jsou patrné vícečetné vaskulární mikroléze v centrum semiovale bilat.
  Nejsou známky nitrolebního krvácení. skelet kalvy orientačně nihil tr.
Z á v ě r: Známky hyperakutní ischemie v povodí ACM vlevo, staré
  postmalatickéé změny T,P a O vlevo, vaskulární mikroléze v centrum
  semiovale bilat.
CT AG: vyš. po bolu k.l..
Po zklidnění nemocné se podařilo provést CT AG. Na krku je naznačený
  kinkink na ACC vlevo a ACI vlevo pod bazí. Kalcifikace  v karotických
  sifonech nepůsobí hemodynamicky významné stenozy. Intrakraniálně je
  patrný konický uzávěr operkulárního úseku a. cerebri media vlevo pro
  parietální lalok. Ostatní nález na intrakraniálním tepenném řečišti je
  v mezích normy.
Z á v ě r: uzávěr operkulárního úseku a. cerebri media vlevo.

Of course if it matches end of sentence is ok for me :-) The question is to find all the acronyms even if they are before new line (\n)

A: I would try this out:
(?:\w+\W+){5}((?:\w.?)+)(?:\w+\W+){5}

Though natural language processing with regular expressions cannot be accurate.

A: ((?:[\w!@#$%&*]+\s+){5}([\w!@#$%&*]+\.)(?:\s+[\w!@#$%&*]+){5})

Try this.See demo.
https://regex101.com/r/aQ3zJ3/9


Q: wsgi:alert daemon unable to change working directory of deleted folder I've been receiving a lot of errors in the error.log file with something like this:
[Sat Oct 07 10:18:06.262085 2017] [wsgi:alert] [pid 18183] (2)No such file or directory: mod_wsgi (pid=18183): Unable to change working directory to '/home/iredadmin'.
[Sat Oct 07 10:18:06.263508 2017] [wsgi:alert] [pid 18183] mod_wsgi (pid=18183): Failure to configure the daemon process correctly and process left in unspecified state. Restarting daemon process after delay.

Goes on and on.. Now, I recently deleted iredadmin and it's attached files, but as a newbie with working from the terminal, I'm not really sure how to solve this error, my website works as normal, but I would like to solve this error in the logs. Can someone guide me in the right direction?
Also I'm not entirely sure what this error means, so if someone could explain it, it would be appreciated.
Thanks.
Edit:
Tried to disable wsgi as George suggested, but when I tried to restart apache2 I got the following message.
Job for apache2.service failed because the control process exited with error code. See "systemctl status apache2.service" and "journalctl -xe" for details.

I then wrote "journalctl | tail" and got the following:
Oct 07 12:29:19 systemd[1]: apache2.service: Control process exited, code=exited status=1
Oct 07 12:29:19 systemd[1]: Failed to start LSB: Apache2 web server.
Oct 07 12:29:19 systemd[1]: apache2.service: Unit entered failed state.
Oct 07 12:29:19 systemd[1]: apache2.service: Failed with result 'exit-code'.
Oct 07 12:29:37 kernel: [UFW BLOCK] IN=eth0 OUT= MAC=hidden SRC=hidden DST=hidden LEN=434 TOS=0x00 PREC=0x00 TTL=51 ID=2843 DF PROTO=UDP SPT=5072 DPT=5060 LEN=414
Oct 07 12:30:01 CRON[19318]: pam_unix(cron:session): session opened for user www-data by (uid=0)
Oct 07 12:30:01 CRON[19319]: (www-data) CMD ([ -x /usr/share/awstats/tools/update.sh ] && /usr/share/awstats/tools/update.sh)
Oct 07 12:30:01 CRON[19318]: pam_unix(cron:session): session closed for user www-data
Oct 07 12:30:07 postfix/smtpd[19323]: connect from 246.red-79-148-239.staticip.rima-tde.net[79.148.239.246]
Oct 07 12:30:07 postfix/smtpd[19323]: disconnect from 246.red-79-148-239.staticip.rima-tde.net[79.148.239.246] helo=1 auth=0/1 quit=1 commands=2/3

I tried to enable the wsgi module again, and restart apache2, and that worked. So it seems apache2 cant restart if I disable wsgi.


Q: static ip network guide I have a fresh install of 13.10 and my networking works fine (cable model cloud router) via the standard network manager applet.
I'm trying to setup my box to a use static IP instead of dhcp and I'm trying to use your guide:
https://help.ubuntu.com/13.10/serverguide/network-configuration.html#ip-addressing
Basically, the settings via the networking applet seem to be conflicting with what I see on the command line.
a) The ifconfig -a shows eth0 with the inet address assigned via dhcp.
ifconfig -a

eth0      Link encap:Ethernet  HWaddr 44:87:fc:97:ed:24
      inet addr:192.168.1.100  Bcast:192.168.1.255  Mask:255.255.255.0
      inet6 addr: fe80::4687:fcff:fe97:ed24/64 Scope:Link
      UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
      RX packets:61170 errors:0 dropped:0 overruns:0 frame:0
      TX packets:41321 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:1000
      RX bytes:79517729 (79.5 MB)  TX bytes:4735861 (4.7 MB)

lo        Link encap:Local Loopback
      inet addr:127.0.0.1  Mask:255.0.0.0

.....
.....

b) However, the interfaces file does not have even eth0 defined.
cat /etc/network/interfaces
auto lo
iface lo inet loopback

c) I could not even do:
sudo ifdown eth0
ifdown: interface eth0 not configured

How is this possible or what am I basically missing ?
Will the steps in the link above for configuring a static IP work ?
Thanks,
Dinshaw

A: The instructions you have linked are for servers where Network Manager is not installed. In such cases, manual methods, in part /etc/network/interfaces, are the methods used to set up networking. On the other hand, in a desktop installation, one with the networking applet, Network Manager controls networking, not manual methods.
In such cases, in order to set a static IP, right-click the applet, also known as the Network Manager icon and select Edit Connections. Edit eth0, in your case, and select IPv4. Change the method to Manual. Fill in your selections and don't forget DNS nameservers. In most cases, the address of the router is sufficient for DNS. Also, be sure to use a static IP address outside the range used by the router for DHCP.
Please see: http://3.bp.blogspot.com/-zXKEt3vxNg4/T58h-Cm1HJI/AAAAAAAAAjs/uOC0tCLcS4w/s1600/ScreenHunter_02%2BApr.%2B30%2B16.37.gif

A: you need to set up a bridged connection at /etc/network/interfaces
Eg.
uto br0
iface br0 inet static

    address 192.168.0.10
    netmask 255.255.255.0
    broadcast 192.168.0.255
    gateway 192.168.0.1
    bridge_ports eth0
    bridge_stp off
    bridge_maxwait 5

Hope that helps
Larry Keenan


Q: imap function is not working for me with PHP I try to access my gmail account with PHP, but I get an error message in line 2. IMAP is enabled in Gmail, while POP is not enabled.
$mbox = imap_open("{imap.gmail.com:993/ssl}", "email@gmail.com", "password");

echo "
Mailboxes
\n";
$folders = imap_listmailbox($mbox, "{imap.gmail.com:993}", "*");

if ($folders == false) {
    echo "Call failed
\n";
}
else {
    foreach ($folders as $val) {
        echo $val . "
\n";
    }
}

echo "
Headers in INBOX
\n";
$headers = imap_headers($mbox);

if ($headers == false) {
    echo "Call failed
\n";
}
else {
    foreach ($headers as $val) {
        echo $val . "
\n";
    }
}

imap_close($mbox);

A: You need to enable imap in your php.ini.

I used the wamp menu to edit the php.ini. I enabled the php_imap.dll.

-> http://www.wampserver.com/phorum/read.php?2,23447,printview,page=1

A: I got the solution:
I am running Windows 7 64bit environment with WAMP server, it has two php.ini files:
1] C:\wamp\bin\apache\apache2.2.22\bin
   Enable php_imap.dll extension by removing ; at beginning of string

2] C:\wamp\bin\php\php5.3.13
   Enable php_imap.dll extension by removing ; at beginning of string

And it works now !


Q: Validation loss and accuracy has a lot of 'jumps' Hello everyone so I made this cnn model.
My data:
Train folder->30 classes->800 images each->24000 all together
Validation folder->30 classes->100 images each->3000 all together
Test folder->30 classes -> 100 images each -> 3000 all together
-I've applied data augmentation. ( on the train data)
-I got 5 conv layers with filters 32->64->128->128->128
each with maxpooling and batch normalization
-Added dropout 0.5 after flattening layers
Train part looks good. Validation part has a lot of 'jumps' though. Does it overfit?
Is there any way to fix this and make validation part more stable?
Note: I plann to increase epochs on my final model I'm just experimenting to see what works best since the model takes a lot of time in order to train. So for now I train with 20 epochs.

A:
Train part looks good. Validation part has a lot of 'jumps' though. Does it overfit?

the answer is yes. The so-called 'jumps' in the validation part may indicate that the model is not generalizing well to the validation data and therefore your model might be overfitting.

Is there any way to fix this and make validation part more stable?

To fix this you can use the following:

*

*Increasing the size of your training set

*Regularization techniques

*Early stopping

*Reduce the complexity of your model

*Use different hyperparameters like learning rate

A:
I've applied data augmentation (on the train data).

What does this mean? What kind of data did you add and how much? You might think I'm nitpicking, but if the distribution of the augmented data is different enough from the original data, then this will indeed cause your model to generalize poorly to the validation set.
Increasing your epochs isn't going to help here, your training loss is already decreasing reasonably. Training your model for longer is a good step if the validation loss is also decreasing nicely, but that's obviously not the case.
Some things I would personally try:

*

*Try decreasing the learning rate.

*Try training the model without the augmented data and see how the validation loss behaves.

*Try splitting the augmented data so that it's also contained in the validation set and see how the model behaves.


Q: Git delete stash by name/message As far as I know Git can not delete a stash by name/message (despite it can save it by name with git stash save "name"). However, I really like to have this option for a 'combined alias' that I want to create for my workflow (especially for colleagues that are not that familiar with git and should respect the workflow)
I know I can create a bash script myself but I was thinking maybe someone already has made such a script!? So that I can delete a stash by name...
My "update" alias is roughly like this:
git stash save -u "tempstash"
git fetch origin
[apply our workflow/update strategy]
git stash pop --index (should be: git stash delete "tempstash")

The problem with the current alias is that if there is nothing to stash, it will restore an old stash.
An other option would be to check if stashing is needed but I always wanted a git stash delete by name option so thats why im asking this.
PS: im using posh-git but bash commands should work within an alias.
Thanks

A: You can overcome the problem with checking whether there is anything to stash first. You can use one of the ways to check whether an index is dirty that are suggested in Checking for a dirty index or untracked files with Git
For instance this command will not output anything if there are no changes to stash:
git status --porcelain

Using this command, the script may look like this:
is_stashing=$(git status --porcelain)
test -n "$is_stashing" && git stash save -u
git fetch origin
[apply our workflow/update strategy]
test -n "$is_stashing" && git stash pop --index

A: A solution would be to search the git reflog stash using the name of the stash as a regexp and obtaining its name in the stash@{<number>} format.
Then you can create an alias in git for using it as a command.
A quick and dirty solution, that can be greatly improved, is something like:
[alias]
   sshow = "!f() { git stash show `git reflog stash | egrep $* | awk '{printf $2}' | sed 's/://' `; }; f"
   ssdrop = "!f() { git stash drop `git reflog stash | egrep $* | awk '{printf $2}' | sed 's/://' `; }; f"

By adding this two aliases in your .git/config you can see the files modified in the stash with:
git sshow <regexp matching the name of the stash>

and you can drop the stash with:
git ssdrop <regexp matching the name of the stash>

A: I found a way to drop a stash by name. You can do it like this:
git stash drop stash@{$((git stash list | grep -w NAME_OF_THE_STASH) | cut -d "{" -f2 | cut -d "}" -f1)}

Here is the breakdown of the script:

*

*I am using the standard git stash drop stash@{n} structure

*We need to get the n of the stash with the name you want to delete. So to do that we list the stashes and grep the item with the matching name. To do that I used the script: git stash list | grep -w NAME_OF_THE_STASH

*Out of that item we need to extract the index which is within brackets {}. We can extract that number by adding to the script in item 2 the following: | cut -d "{" -f2 | cut -d "}" -f1
I tested it and it works great for me.
By the way, if you enter a name that does not exist then nothing gets erased.
Also, only the exact name match will be erased. If you don't want an exact match necessarily then remove the -w after grep.


Q: Image on top of text changing it's color I'm trying to find out how to build something like this (see attachment).
I do not know how to when a image (assuming it's an svg) goes on top of a H1 or any text it changes the text color.
The attachment i print here has a breathing effect on the blob, i wont have that but still it would be great to know.
Thank you.
BlobText


Q: (ionic solution) Disable android hardware back button for specific view. Back button should work as expected for other views in app On the tap of hardware back button on a specific view, it should not do anything. By Default it nav pop the view but here I don't want to back navigate on click of hardware back button. I want it to stay on that page/view.
I checked all possible solution available but no luck. This is not a duplicate too.
Ionic 2 - Disabling back button for a specific view this is for nav back button. I want a solution for hardware back button.

A: You can Try this
*Simply Override Empty onBackPressed *
@Override
public void onBackPressed(){
// do nothing.

}

A: You can Try this
*Simply Override Empty onBackPressed *
@Override
public void onBackPressed(){
 // do nothing.}

A: You have to write an override method
@Override
public void onBackPressed() {
    \\you can do whatever you want to here.
    \\don't call **super**, if u want disable back button in current screen.
}

A: In your Activity you have to override method:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        return !disableBackKey ;
    }

    return super.onKeyDown(keyCode, event);
}

And make disableBackKey True/False depend upon your requirement.

A: If you are using Activity, please add below function to your activity
@Override
public void onBackPressed() {
    //super.onBackPressed();
}

if you are using Fragment, please add below function to your fragment
public boolean onKeyDown(int keyCode, KeyEvent event) {
    switch (keyCode) {
    case KeyEvent.KEYCODE_BACK:
       return true
    }
            return false;
}

A: Answer for Ionic 2 or 3
Call the below method at the end of constructor.
Registration in the below code is your class name of current page or component.
if you don't want to do anything on back button, simply remove the code in IF condition below.
overrideHardwareBackButton() {
            this.platform.ready().then(() => {
                this.platform.registerBackButtonAction(() => {
                    let activeView:ViewController = this.navCtrl.getActive();
                    if (activeView != null && ((<any> activeView).instance instanceof Registration)) {
                        console.log("Registration -> Home");
                        this.nav.setRoot(HomePage);
                    } else {
                        console.log("Somthing is wrong");
                    }
                });
            });
        }


Q: Angular best practice for sharing single API call between two active components I'm trying to figure out what the best practice is for the following situation:
I have two components A and B which are both are integrated on one page. Both components need access to data set C. Data set C is received by an API Call from the server. It should only be received initially and not twice for every component.
My first approach was using observables, but then the API call was done twice. So i switched to BehaviourSubjects, but when called from the controller the initial value was of course null. So i replaced it with ReplySubjects, which are working fine. But im struggling with the intial call. I got it working fine but im looking for the best pracice. Here is the code:
Component A and B are similar
getDataC(): void {
    this.dataCService.getData().subscribe(data=>{this.data = data})
}

I want to have the data in my service as well, so i can make a UPDATE on the API with the object to modify the data on the Server. My approach is working fine, but im not sure if i have to subscribe inside my service the this variable or keep it clean.
Then my Service:
import { Injectable } from '@angular/core';
import { DataCAPIService } from '../resources/resources.service'
import { Observable, of, BehaviorSubject, ReplaySubject } from 'rxjs';

@Injectable({
    providedIn: 'root'
})
export class DataCService {

    public dataC = new ReplaySubject<any>(1)
    dataCInsideService: any

    constructor(private dataCAPIService: DataCAPIService) {

    }

    getDataCAPICall() {
        if (this.dataC.observers.length < 2)
            this.dataCAPIService.getAll({}).subscribe(data => {
                this.dataC.next(data);
                this.dataC.subscribe(data => this.dataCInsideService = data)
            })
    }

    getData() {
        this.getDataCAPICall();
        return this.dataC;
    }

    saveDataC() {
        this.dataCAPIService.update(this.dataCInsideService, {}).subscribe(data => {
            this.dataC.next(this.dataCInsideService);
        })
    }
}

Thanks for any opinions or solutions to a better style.

A:
I have two components A and B which are both are integrated on one
page. Both components need access to data set C.

As long as they are being used in one page, why you are calling them from each components? I think you can call it from the page component and send it to children.
Children can get the data using @Input() decorator. You can send the data directly or you can send it as observable (it's fine if it is behavior subject or subject).
I hope this could help you.


Q: Regular expression in Python sentence extractor I have a script that gives me sentences that contain one of a specified list of key words. A sentence is defined as anything between 2 periods.
Now I want to use it to select all of a sentence like 'Put 1.5 grams of powder in'  where if powder was a key word it would get the whole sentence and not '5 grams of powder'
I am trying to figure out how to express that a sentence is between to sequences of period then space. My new filter is:
def iterphrases(text):
    return ifilter(None, imap(lambda m: m.group(1), finditer(r'([^\.\s]+)', text)))

However now I no longer print any sentences just pieces/phrases of words (including my key word). I am very confused as to what I am doing wrong.

A: if you don't HAVE to use an iterator, re.split would be a bit simpler for your use case (custom definition of a sentence):
re.split(r'\.\s', text)

Note the last sentence will include . or will be empty (if text ends with whitespace after last period), to fix that:
re.split(r'\.\s', re.sub(r'\.\s*$', '', text))

also have a look at a bit more general case in the answer for Python - RegEx for splitting text into sentences (sentence-tokenizing)
and for a completely general solution you would need a proper sentence tokenizer, such as nltk.tokenize
nltk.tokenize.sent_tokenize(text)

A: Here you get it as an iterator. Works with my testcases. It considers a sentence to be anything (non-greedy) until a period, which is followed by either a space or the end of the line.
import re
sentence = re.compile("\w.*?\.(?= |$)", re.MULTILINE)
def iterphrases(text):
    return (match.group(0) for match in sentence.finditer(text))

A: If you are sure that . is used for nothing besides sentences delimiters and that every relevant sentence ends with a period, then the following may be useful:
matches = re.finditer('([^.]*?(powder|keyword2|keyword3).*?)\.', text)
result = [m.group() for m in matches]


Q: R: Make a new column filled from value in a row I have multiple dataframes all structured as below but with thousands of observations.
(df <- data.frame(
col1 = c("Elem_A", "String", "String", "String", "Elem_A", "String", "String", "Elem_A", "String", "String", "String", "String"),
col2 = c("DOI_1", "String", "String", "String", "DOI_2", "String", "String", "DOI_3", "String", "String", "String", "String")))

#>     col1   col2
#> 1 Elem_A  DOI_1
#> 2 String String
#> 3 String String
#> 4 String String
#> 5 Elem_A  DOI_2
#> 6 String String
#> 7 String String
#> 8 Elem_A  DOI_3
#> 9 String String
#> 10 String String
#> 11 String String
#> 12 String String

I am wanting to structure it as below, pulling specifically the value that begins with "DOI" into a new column and filling that value down until it reaches the row with the next "DOI" value.
(df <- data.frame(
col1 = c("Elem_A", "String", "String", "String",
    "Elem_A", "String", "String", "Elem_A", "String", "String", "String", "String", "String", "String", "String"),
col2 = c("DOI_1",
    "String", "String", "String", "DOI_2", "String", "String",
    "DOI_3", "String", "String", "String", "String", "String", "String", "String"),
col3 = c("DOI_1", "DOI_1", "DOI_1", "DOI_1",
    "DOI_2", "DOI_2", "DOI_2", "DOI_3", "DOI_3", "DOI_3", "DOI_3", "DOI_3")))

#>     col1   col2  col3
#> 1 Elem_A  DOI_1 DOI_1
#> 2 String String DOI_1
#> 3 String String DOI_1
#> 4 String String DOI_1
#> 5 Elem_A  DOI_2 DOI_2
#> 6 String String DOI_2
#> 7 String String DOI_2
#> 8 Elem_A  DOI_3 DOI_3
#> 9 String String DOI_3
#> 10 String String DOI_3
#> 11 String String DOI_3
#> 12 String String DOI_3

I was thinking I should somehow incorporate str_detect but the issue is that sometimes "DOI" is also the beginning of some of the "Strings" values within the same column that the "DOI" values are in.

A: We can use str_detect with case_when/ifelse to retrieve the row element and then use fill to fill the NA values with the previous non-NA
library(dplyr)
library(tidyr)
library(stringr)
df <- df %>%
   mutate(col3 = case_when(str_detect(col2, "DOI_") ~ col2)) %>%
   fill(col3)

-output
df
 col1   col2  col3
1  Elem_A  DOI_1 DOI_1
2  String String DOI_1
3  String String DOI_1
4  String String DOI_1
5  Elem_A  DOI_2 DOI_2
6  String String DOI_2
7  String String DOI_2
8  Elem_A  DOI_3 DOI_3
9  String String DOI_3
10 String String DOI_3
11 String String DOI_3
12 String String DOI_3

If 'DOI_\\d+' is a substring, then use str_extract to extract the substring
df <- df %>%
        mutate(col3 = str_extract(col2, "DOI_\\d+")) %>%
        fill(col3)

-output
df
 col1   col2  col3
1  Elem_A  DOI_1 DOI_1
2  String String DOI_1
3  String String DOI_1
4  String String DOI_1
5  Elem_A  DOI_2 DOI_2
6  String String DOI_2
7  String String DOI_2
8  Elem_A  DOI_3 DOI_3
9  String String DOI_3
10 String String DOI_3
11 String String DOI_3
12 String String DOI_3

A: With Base R way
s <- unlist(gregexpr("DOI_\\d+" , df$col2))

df$col3 <- unlist(Map(\(x,y) rep(df$col2[x] ,length.out = y + 1) ,
                  which(s > -1) , rle(s)$lengths[which(rle(s)$values == -1)]))

*

*output

     col1   col2  col3
1  Elem_A  DOI_1 DOI_1
2  String String DOI_1
3  String String DOI_1
4  String String DOI_1
5  Elem_A  DOI_2 DOI_2
6  String String DOI_2
7  String String DOI_2
8  Elem_A  DOI_3 DOI_3
9  String String DOI_3
10 String String DOI_3
11 String String DOI_3
12 String String DOI_3


Q: trying to create a loop that returns a logo in the list images and the name cryptolist i have a Widget that is called CoinCard which shows a cyrptoLogo,name and price.
now instead of calling that widget 3 times and providing image and a name, i wanted to create a loop which will return a image from images and the name from cryptoList. code below:

List<String> images = [
  "Bitcoin.svg.png",
  "256px-Ethereum_logo_2014.svg.png",
  "litecoin-ltc-logo.png"
];
const List<String> cryptoList = ['BTC', 'ETH', 'LTC'];

class _HomePageState extends State<HomePage> {
  List<Widget> getCard() {
    List<CoinCard> cards = [];

    for (String image in images) {
      cards.add(
        CoinCard(
          cryptoname: "ggg",
          logo: image,
          price: "5001918556",
        ),
      );
    }
    return cards;
  }

A: you can use ListView.builder to create dynamic list
example :
class HomePage extends StatelessWidget {
  List<String> images = [
  "Bitcoin.svg.png",
  "256px-Ethereum_logo_2014.svg.png",
  "litecoin-ltc-logo.png"
];
  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount:images.length ,
      itemBuilder: (context, index) => CoinCard(
          cryptoname: "ggg",
          logo: images[index],
          price: "5001918556",
        ),
      );
  }
}


Q: how to print the line number 5 to 10 of multiple file which does not have same extension in a directory i have to print line number 5 to 10 of multiple file which does not have same extension in a directory but it should avoid all the sub-directories in the same directory.

A: Using zsh and GNU sed (for the -s option that treats each separate file as a separate stream to print):
zsh -c 'sed -s -n 5,10p ./*(.)'

Otherwise,
for f in ./*
do
  [ -f "$f" ] && sed -n 5,10p "$f"
done

(note that that one  processes symlinks to regular files in addition to regular files; add a && [ ! -L "$f" ] if you want to skip them, or change (.) to (-.) in the zsh solution to include them there)


Q: Showing openess in topology of point-wise convergence I want to check if the set
$$ P_{x_0}=\{f\in C([a,b])\mid f(x_0)=0\},\quad x_0\in[a,b] $$
is open in the topology of point-wise convergence.
I already have a problem with an intuitive picture of this topology. I know it is has the basis
$$ O(x_1,\ldots,x_n,t_1,\ldots,t_n,\varepsilon)=\{f\in C([a,b])\mid f(x_i)\in B_\varepsilon(t_i),\quad i=1,\ldots,n\}. $$
If I had to guess I would say $P_{x_0}$ is not open because the property in $O$ only needs a finite number of points, so I think there's a way to construct a function which lies in $O$ but has a non-zero "spike" at $x_0$.
Is my approach correct or am I wrong with the way I imagine this basis set?

A: $P_{x_0}$ is not open in $C([a,b])$, but it is closed, as it equals $e_{x_0}^{-1}[\{0\}]$ where $e_p: C([a,b]) \to \Bbb R$ is the evaluation map $e_p(f)=f(p)$ for any $p \in [a,b]$.
The point-wise convergence topology is the minimal topology that makes all $e_p$ continuous, by definition. And the inverse of a closed set under a continuous map is closed.
To see it $P_{x_0}$ is not open, note that $c_{\frac{1}{n}}$ (the constant map with value $\frac1n$), defines a sequence not in $P_{x_0}$ that converges point-wise to $c_0$ (the zero function) that is in the set. So $c_0$ is not an interior point of $P_{x_0}$.


Q: Modify/clean field values before applying a query filter in MongoDB like in SQL Server? I have a SQL Server query that I need to convert into a Mongo Query. As we all know that we can clean up fields in SQL before applying conditions to them e.g
In the 3rd line we are applying ltrim,rtrim on the clinics field before applying the like condition to it. Same with the reverse field in the query multiple times. If this was a single step query I would have done something maybe using aggregation but this is a multistep cleanup using replace, convert, ltrim, rtrim etc in different places.
Can someone please throw some light on how I could convert it. If someone is an expert in this domain and can convert it into Mongo, that would be great as well. Thanks :)
select rule from rules where
isnull(status,0) = '1' AND isnull(deleted,0) = '0'
AND (((ltrim(rtrim(isnull(clinics,'0'))) like '0%') OR
( ',' + replace(replace(isnull(clinics,'0'),' ','') ,' ','') + ','
like '%,' + convert(varchar,"""+category+""") + ',%')) AND
(',' + replace(replace(isnull(clinics,'0'),' ','') ,' ','') + ','
not like '%,-' + replace(convert(varchar,"""+category+"""),' ','') + ',%')) AND
((( (ltrim(rtrim(isnull(reverse,'0'))) like '0%') OR
(( ','+ replace(replace(isnull(reverse,'0'),' ','') ,' ','') + ','
like '%,' + convert(varchar,"""+primary+""") + ',%')))
AND (',' + replace(replace(isnull(reverse,'0'),' ','') ,' ','') + ','
not like '%,-' + replace(convert(varchar,"""+primary+"""),' ','') + ',%') ))


Q: Can I say "Please find my yesterday’s and today’s daily reports in the documents." Can I say "Please find my yesterday’s and today’s daily reports in the documents."?

A: No, you cannot say "Please find my yesterday’s and today’s daily reports in the documents."
You can say:

Please find yesterday’s and today’s daily reports in the documents. (as suggested by Steve Melnikoff)

Or, you can also say:

Please find my daily reports from yesterday and today in the documents. (as suggested by Bruno Rothgiesser)

A: No.
In general English disallows using two different direct possessives together in the some noun phrase. Using possessive my and possessive tomorrow's to modify the word reports results in a sentence that I find ungrammatical. One of the possessives must be demoted to a prepositional phrase, and since my cannot be so demoted (since *of me is ungrammatical for other reasons), you have to move tomorrow to a prepositional phrase:

Please find my daily reports from yesterday and today in the documents.

(This is the same corrected version that Bruno gave, but unlike Bruno I find the original to be ungrammatical, and the corrected version to be necessary, not just stylistically preferred.)

A: Yes, because:

*

*You can use a possessive pronoun followed by a word with 's (i.e. the saxon genitive). For example, "my last year's tax refund".

*You can use 's in more than one word in the same sentence. For example, "Here you can review yesterday's, today's and tomorrow's horoscope."
Having said that, I would reword your sentence to make it sound more natural:

Please find my daily reports from
  yesterday and today  in the documents.


Q: Boost serialization of class handling a possible null pointer I want to serialize the following class wrapping a pointer which can handle a null m_element as you can see when calling the default constructor. This follows this question.
Live MCVE on Coliru
template <typename T>
struct Ptr { // Ptr could use init constructor here but this is not the point
    Ptr() { m_elem = 0; }
    Ptr(const T* elem) {
        if (elem)
            m_elem = new T(*elem);
        else
            m_elem = 0;
    }
    Ptr(const T& elem)
    {
        m_elem = new T(elem);
    }
    Ptr(const Ptr& elem)
    {
        if (elem.m_elem)
            m_elem = new T(*(elem.m_elem));
        else
            m_elem = 0;
    }
    virtual ~Ptr() { delete m_elem; m_elem = 0; };

    const T& operator*() const { return *m_elem; };
    T& operator*() { return *m_elem; };

    const T* operator->() const { return m_elem; };
    T* operator->() { return m_elem; };

    T* m_elem;
};

namespace boost { namespace serialization {

    // Not sure about the approach to manage null m_elem here
    template<class Archive, class T>
    void save(Archive & ar, const Ptr<T> &ptr, const unsigned int version)
    {
        T elem = 0;
        if (ptr.m_elem != 0)
            ar& boost::serialization::make_nvp("data", *ptr.m_elem);
        else
            ar& boost::serialization::make_nvp("data", elem);
    }

    // How to implement load ?
    template<class Archive, class T>
    void load(Archive & ar, Ptr<T> &ptr, const unsigned int version)
    {
        ar& boost::serialization::make_nvp("data", *ptr.m_elem);
    }

    template<class Archive, class T>
    void serialize(Archive & ar, Ptr<T> &ptr, const unsigned int version)
    {
        boost::serialization::split_free(ar, ptr, version);
    }

}} // end namespace

int main()
{
    {
        Ptr<A> p;
        std::ostringstream oss;
        boost::archive::xml_oarchive oa(oss);
        oa << BOOST_SERIALIZATION_NVP(p);
        std::cout << oss.str() << std::endl;

        // segfault

        Ptr<double> po;
        std::istringstream iss;
        iss.str(oss.str());
        boost::archive::xml_iarchive ia(iss);
        ia >> BOOST_SERIALIZATION_NVP(po);

    }
    {
        Ptr<double> p(new double(2.0));
        std::cout << *(p.m_elem) << std::endl;

        std::ostringstream oss;
        boost::archive::xml_oarchive oa(oss);
        oa << BOOST_SERIALIZATION_NVP(p);
        std::cout << oss.str() << std::endl;

        // segfault

        Ptr<double> po;
        std::istringstream iss;
        iss.str(oss.str());
        boost::archive::xml_iarchive ia(iss);
        ia >> BOOST_SERIALIZATION_NVP(po);

    }
}

The serialization seems to work but the deserialization gives a segfault. I am working in C++0x.

*

*How can I provide safe save and load functions to serialize Ptr without changing Ptr if possible ?

*If I need to modify Ptr, what do you propose ?

Edit : thanks to Jarod42 comment I came up with the following save/load functions using a boolean to detect null pointer or not. Now I do not have a segfault anymore when m_elem is null but I have a one when it is not null.
template<class Archive, class T>
void save(Archive & ar, const Ptr<T> &ptr, const unsigned int version)
{
    bool is_null;
    if (ptr.m_elem != 0) {
        is_null = false;
        ar& boost::serialization::make_nvp("is_null", is_null);
        ar& boost::serialization::make_nvp("data", *ptr.m_elem);
    }
    else
    {
        is_null = true;
        ar& boost::serialization::make_nvp("is_null", is_null);
    }
}

template<class Archive, class T>
void load(Archive & ar, Ptr<T> &ptr, const unsigned int version)
{
    bool is_null;
    ar& boost::serialization::make_nvp("is_null", is_null);
    if (is_null == true) {
        ptr.m_elem = 0;
    }
    else
    {
        ar& boost::serialization::make_nvp("data", *ptr.m_elem);
    }
}

A: boost::archive's save and load methods understand the difference between pointers and object references. You don't need to specify *m_elem. m_elem will do (and work correctly). Boost will understand if the pointer is null and will simply store a value indicating a null pointer, which will be deserialised correctly.
(simplified) example:
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <iterator>

#include <boost/archive/xml_iarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/serialization/access.hpp>
#include <boost/serialization/nvp.hpp>
#include <boost/serialization/split_free.hpp>

struct A {
    A() : a(0) {}
    A(int aa) : a(aa) {}
    int a;
    template <class Archive>
    void serialize(Archive& ar, const unsigned int /*version*/)
    {
        ar& BOOST_SERIALIZATION_NVP(a);
    }
};

std::ostream& operator<<(std::ostream& os, const A& a) {
    os << "A{" << a.a << "}";
    return os;
}

template <typename T>
struct Ptr { // Ptr could use init constructor here but this is not the point
    Ptr()
    : m_elem(0)
    {}

    Ptr(T elem)
    : m_elem(new T(elem))
    {
    }

private:
    // no copies
    Ptr(const Ptr&);
    Ptr& operator=(const Ptr&);
public:
    // delete is a NOP when called with nullptr arg
    virtual ~Ptr() { delete m_elem; };

    T* get() const {
        return m_elem;
    }

    T& operator*() const {
        return *m_elem;
    }

    template <class Archive>
    void serialize(Archive& ar, const unsigned int /*version*/)
    {
        ar& BOOST_SERIALIZATION_NVP(m_elem);
    }

private:
    T* m_elem;
};

template<class T>
std::ostream& operator<<(std::ostream& os, const Ptr<T>& p) {
    if (p.get()) {
        os << *p;
    }
    else {
        os << "{nullptr}";
    }
    return os;
}

int main()
{
    std::string payload;

    {
        Ptr<A> p;
        std::cout << p << std::endl;
        std::ostringstream oss;
        boost::archive::xml_oarchive oa(oss);
        oa << BOOST_SERIALIZATION_NVP(p);
        payload = oss.str();
//        std::cout << payload << std::endl;

        Ptr<A> p2(A(6));
        std::cout << p2 << std::endl;
        oa << BOOST_SERIALIZATION_NVP(p2);
        payload = oss.str();
//        std::cout << payload << std::endl;
    }
    {

        Ptr<A> po;
        std::istringstream iss(payload);
        boost::archive::xml_iarchive ia(iss);
        ia >> BOOST_SERIALIZATION_NVP(po);
        std::cout << po << std::endl;

        Ptr<A> po2;
        ia >> BOOST_SERIALIZATION_NVP(po2);
        std::cout << po2 << std::endl;
    }
}

expected output:
{nullptr}
A{6}
{nullptr}
A{6}

A: Thanks to Jarod42 comment,

You should serialize a boolean to know if pointer is nullptr or not
  (and if not, serialize also its content). for loading, retrieve this
  boolean and allocate a default element when needed that you load.

we came with the following save and load functions :
template<class Archive, class T>
void save(Archive & ar, const Ptr<T> &ptr, const unsigned int version)
{
    bool is_null = !ptr.m_elem;
    ar & boost::serialization::make_nvp("is_null", is_null);
    if(!is_null) ar & boost::serialization::make_nvp("data", *ptr.m_elem);
}

template<class Archive, class T>
void load(Archive & ar, Ptr<T> &ptr, const unsigned int version)
{
    bool is_null;
    ar & boost::serialization::make_nvp("is_null", is_null);

    if (!is_null) {
        ptr.m_elem = new T;
        ar& boost::serialization::make_nvp("data", *ptr.m_elem);
    }
}

Live on Coliru
Had an issue in the load function when is_null is false. A storage is indeed needed for ptr in this case.


Q: I want to dynamically query WHERE clause using string builder I want to dynamically build the WHERE clause for my query using string builder.
private void btnquery_Click(object sender, EventArgs e)
{
    StringBuilder strQuery = new StringBuilder();
    StringBuilder strWhereClass = new StringBuilder();
    strQuery.Append("SELECT * FROM [dbo].[poi5] ");

    if (namecb.Checked)
    {
        if (string.IsNullOrEmpty(nametxt.Text))
        {   MessageBox.Show("Please enter the name!!!");
            nametxt.Focus();
            return;
        }
        else
        {
            if (strWhereClass.Length == 0)
            { strWhereClass.Append("WHERE [Name_POI] ='" + nametxt.Text + "';");
            } else{ trWhereClass.Append(" AND [Name_POI]] ='" + nametxt.Text + "';");
            }
        }
    }

    if (versioncb.Checked)
    {
        if (string.IsNullOrEmpty(versiontxt.Text))
        {  MessageBox.Show("Please enter the version!!!");
            versiontxt.Focus();
            return;
        }
        else
        {
            if (strWhereClass.Length == 0)
            {
                strWhereClass.Append("WHERE [Version] = '" versiontxt.Text + "'");
            }
            else
            {
                strWhereClass.Append(" AND [Version] = '" + versiontxt.Text + "'");
            }
        }
    }

    con = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=POIFINALLY;Integrated Security=True;");

    cmd = new SqlCommand(strQuery.ToString() + strWhereClass.ToString(), con);
    con.Open();
    da = new SqlDataAdapter(cmd);
    da.Fill(ds);
    dataGridView1.DataSource = ds.Tables[0];
}

A: Write a stored Procedure that takes the filter query dynamically according to cases
    Create procedure GetPoi (@Name nvarchar (100),@Version nvarchar (100))
    as
    begin
    declare @Command nvarchar(max)
    set @Command = 'select * from tablename where name ='''+@Name+''' and Version='''+@Version+''''
    exec sp_executeSql @Command
    end

Also you have to make a test to check if the Parameters provided are empty strings and modify your where clause accordingly.
Check Dynamic SQL for more info


Q: Does github limit the number of personal access tokens per user Using Github Enterprise, I have a service/bot account where I'd like to generate a number of Personal Access tokens and provide to a number of teams.
Is there any limit in how many Personal Access Tokens can be generated per user?

A: As far as I'm aware, there is no limit, but if you want to be sure, you should ask either the GitHub support team or on the GitHub community forums.
GitHub itself has such a bot account and PATs are frequently used there, but do be aware that the UI may be a little (or, depending on how many tokens you issue, very) slow, since it isn't designed for people to have huge numbers of PATs.
You may find it more desirable to use deploy keys if you're accessing a repo, since these have a smaller scope (one repository) and won't have the UI problems mentioned above, but of course that won't work for the API.


Q: How to add textFileds in Dropdown Reactjs I want to add textField - autocomplete in Dropdown? Could you help me how to do it?

The source code in here: Source Code in Sanbox

A: Since you are using Material-UI, you can use their autocomplete component with a TextField as input, have a look at the "Combo box" here:
https://material-ui.com/components/autocomplete/#combo-box


Q: Sprint Wireless Toolkit 3.3.2 vs Sun Wireless Toolkit Anyone know the diference between Sprint Wireless Toolkit 3.3.2 and Sun Wireless Toolkit?

A: AFAIK both are same. But I feel some differents between Sprint toolkit and Sun toolkit. These are,
Sprint toolkit having Nokia, Samsung, LG emulators. But Sun java toolkit having their own toolkit.
Sprint support touch emulators. Sun toolkit doesn't have touch emulators.
Zooming emulator screen supports Sprint. Sun toolkit doesn't support.


Q: Javascript displaying text in quotes. How do I remove it? Edit: Turns out the api produces the quotes.
Excuse me, as I have pretty much no knowledge of js/jquery, but I found a code I wanted to use. It uses tumblr's api. http://www.tumblr.com/docs/en/api/v1.
Now, the problem is titles[i] shows text wrapped in quotes. So instead of

This is the titles i. I want this.
,
it shows

"This is the titles i. I don't want the quotes!"

in the html. I don't want that (for reasons not worth explaining).
Can somebody help me remove the quotes?
Here's the full code.
(function() {
var config = new Object();
var titles = [];
var links = [];
var images = [];
var items = [];
var types = [];
var $j = jQuery.noConflict()

var scripts = document.getElementsByTagName('script');
var this_script = scripts[scripts.length - 1];
var params = this_script.src.replace(/^[^\?]+\??/,'').split('&');

var url_base = ((typeof(config.url) == 'undefined') ? ('http://' + document.domain + '/') : ('http://' + config.url + '/'));

for(var i=0; i<params.length; i++) {
    var tmp = params[i].split("=");
    config[tmp[0]] = unescape(tmp[1]);
}

if(typeof(config.tags)=='undefined'){ error(0); return; }
if(typeof(config.num)=='undefined'){ config.num=8; }
if(typeof(config.len)=='undefined'){ config.len=60; }
if(typeof(config.title)=='undefined'){ config.title='Related Posts:'; }
if(typeof(config.type)=='undefined'){ config.type=''; }

switch(config.css) {
case ('simple'):
  document.write('<link rel="stylesheet" type="text/css" ' +
  'href="http://example.com/resource/simple.css" media="screen" />');
break;
case ('complete'):
  document.write('<link rel="stylesheet" type="text/css" ' +
  'href="http://example.com/resource/complete.css" media="screen" />');
break;
case ('light'):
  document.write('<link rel="stylesheet" type="text/css" ' +
  'href="http://example.com/resource/light.css" media="screen" />');
break;
case ('dark'):
  document.write('<link rel="stylesheet" type="text/css" ' +
  'href="http://example.com/resource/dark.css" media="screen" />');
break;}

  document.write(
    '
' +
        '

' +
        '

'+
        '

' +
        '' +
    '
'
);

var tags = config.tags.slice(0,-1).split(',');

$j(document).ready(function() {
    function getRelated() {
        var req;
        for(var i=0; i<tags.length; i++){
            req=$j.getJSON(url_base+'api/read/json?callback=?&filter=text&num='+config.num+'&start=0&type='+config.type+'&tagged='+escape(tags[i]), function(data) {
                $j(data.posts).each(function(i, post) {
                    var text='';
                    if(post.type=='regular') text=post['regular-title']+''+post['regular-body'];
                    else if(post.type=='link') text+=post['link-text'];
                    else if(post.type=='quote') text+=post['quote-text'];
                    else if(post.type=='photo') text+=post['photo-caption'];
                    else if(post.type=='conversation') text+=post['conversation-title'];
                    else if(post.type=='video') text+=post['video-caption'];
                    else if(post.type=='audio') text+=post['audio-caption'];
                    else if(post.type=='answer') text+=post['question'];
                    if(text.length>config.len){ text=text.slice(0,config.len); text+='...';}
                    var image ='';
                    if(post.type=='photo') image+=post['photo-url-100'];
                    else if(post.type=='link') image+=['link-text'];
                    else if(post.type=='quote') image+=['quote-text'];
                    else if(post.type=='photo') image+=['photo-caption'];
                    else if(post.type=='conversation') image+=['conversation-title'];
                    else if(post.type=='video') image+=['video-caption'];
                    else if(post.type=='audio') image+=['audio-caption'];
                    else if(post.type=='answer') image+=['question'];
                    titles.push(text);
                    links.push(post['url-with-slug']);
                    images.push(image);
                    types.push(post['type'])
                });

            }).complete(getList);
        }

    }
    function getList(){
        for(var i=0; i<titles.length; i++){
            var regex = new RegExp('('+links[i]+')');
            var html = $j("#inlink-list").html();

            if(links[i]!=document.location&&!html.match(regex)){
                if(config.num--<=0) return;

                var item='

'+titles[i]+'

';
                $j("#inlink-list").append(item);
            }
        }
        $j("#inlink-title").html('
'+config.title+'
');
        $j("#inlink-loading").html('');
    }
    getRelated();

});

function getError(e){
    var msg="error: ";
    switch(e){
        case 0: msg+='no tags defined'; break;
        case 1: msg+='tumblr API problem'; break;
    }
    $j("#inlink-loading").html(msg);
}})();

A: I am going to assume the quotes are coming from the Tumblr API. In this case, you just need to strip the quotes:

'+titles[i].substring(1, titles[i].length - 2)+'

substring(1, titles[i].length - 2) will remove the first character (index 0) and the last character (index length - 1) from the string.
Docs


Q: Create bitmap of a DOMElement Objective C I have a Webkit DOMElement, a div for example.
Now I want a renderized NSImage or NSBitmapImageRep of it.
It's like a screenshot of a DOMElement.

A: Public API choices:
-[NSView cacheDisplayInRect:toBitmapImageRep:]
-[NSBitmapImageRep initWithFocusedViewRect:]

Private WebKit method:
-[DOMElement renderedImage]


Q: SQL help to identify the Missing Data I have the following COMPANY_TABLE table
SOURCE  UNIQUE_COMPANY_D    RECORD_STATE    SUB_COMPANY_ID  PARENT  PRIMARY_PARENT
ABC 111 Secondary   123     999
XYZ 111 Primary     456
YYY 222 Secondary   895     888        888
TTT 222 Primary     902                888
VVV 333 Primary     101     777        777
RRR 333 Secondary   187                777

IN WHERE UNIQUE_COMPANY_ID = '111' is the issue.
PRIMARY_PARENT IS NOT POPULATED, It should populate based on PARENT. If the PARENT field has Value it should Populate for both rows. if null it has to grab the value from secondary row and populate PRIMARY_PARENT Value. I have like 10 million rows where I need to find the scenarios where Parent is populated and Primary parent is not populated. based on the above criteria. (If the PARENT field has Value it should Populate for both rows. if null it has to grab the value from secondary row and populate PRIMARY_PARENT Value) I want to identify all the error records from 10 million rows.
And I created the SQL below :
SELECT * FROM COMPANY_TABLE WHERE PARENT IS NOT NULL AND PRIMARY_PARENT IS NULL;

But all its showing me single row. I need something which can get me two rows in order and able to differentiate the issue.

A: You have missed one of the conditions. You also want whenever PARENT is NULL the Value of PRIMARY_PARENT be equal to the value of PARENT in the next row. You can take care of it this way:
SELECT * FROM
(SELECT *, LEAD(PARENT) OVER(Order BY (SELECT NULL)) as LeadParent FROM     COMPANY_TABLE) T
WHERE PARENT IS NOT NULL AND PRIMARY_PARENT IS NULL
     OR ((PARENT IS NULL) AND LeadParent != PRIMARY_PARENT);

A: As Kumar stated, you could try and test to see if the values Parent and Primary_Parent by default are NULL's or blanks.
Did you try:
SELECT * FROM COMPANY_TABLE WHERE PARENT <> '' AND PRIMARY_PARENT <> ''


Q: Put a Variable in List Name Essentially, I want to create and fill a list based on the contents of a variable. The relevant data is being read from a (JSON) text file.
#Check if a game was won, and assign a variable to `outcome`
if game['stats']['win'] == True:
                outcome = "victory"
            else:
                outcome = "defeat"

#put the no. objectives taken in that game in a 'wins' or 'losses' list
objectives_in_(outcome).append(game['stats']['objectives_taken'])

So outside of a useful for-loop, I would want something a result which looks something like this:
print(objectives_in_victory)

7

In case my question remains unclear, I am reading a file that will contain data on whether a match was won, and how many objectives were secured. If the game was won, the number of objectives in that game will be assigned to a 'win list' and visa versa for losses.
I tried using a dictionary which was suggested elsewhere on SO for approaching similar tasks, but matches which have the same outcome and no. objectives are not duplicated making averaging impossibe and causing data to be excluded. It took me a long time to realise this..

A: You could use a dict of lists that looks like this:
objectives_in = {"victory": [], "defeat": []}

You can use it similar to what you have in your example:
objectives_in[outcome].append(game['stats']['objectives_taken'])

# Example stats:
count = len(objectives_in["victory"])
print("Number of victories:", count)
print("Average objectives:", sum(objectives_in["victory"]) / count)


Q: How to melt and plot multiple datasets over different ranges on the same set of axis? This is my first time posting here, I hope my question is clear and appropriate. I have a set of data the head of which looks like this:
   wl     ex421  wl     ex309  wl      ex284  wl      ex347
1 431 0.6168224 321 0.1267943 301 0.06392694 361 0.15220484
2 432 0.6687435 322 0.2416268 302 0.05631659 362 0.08961593
3 433 0.6583593 323 0.4665072 303 0.05327245 363 0.13134187
4 434 0.6832814 324 0.3576555 304 0.00000000 364 0.32432432
5 435 0.6427830 325 0.2194976 305 0.12328767 365 0.50308203
6 436 0.7393562 326 0.1866029 306 0.08675799 366 0.34660977

and so on. The 'wl' columns represent wavelength, and there are four different ranges. The other four columns represent measurements (normalized) taken over the 'wl' ranges. The ranges are of different lengths, too. All of them partially overlap somewhere in the middle of the dataset.
What I need to achieve is a plot showing all four sets of 'ex###' data on the same set of axis and plotted over their respective ranges. The x-axis needs to accommodate all four 'wl' ranges. However, I haven't yet succeeded.
When I had to plot multiple sets of data like this in the past I just melted the data and it always worked. Something like this:
df_melt <- melt(df, id.var = 'wl')

And then I'd plot it like this:
fluor_plt <- ggplot(fluor_ref2_melt, aes(x=wl,y=value,color=variable)) +
geom_point(shape = 1, fill = NA) + geom_path(data = fluor_ref2_melt,size = 1) +
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) +
  scale_colour_manual(values = colvec)

However, because I have multiple columns with the name 'wl', which also have different ranges, what happens is that R only takes the first 'wl' column and discards all the other ones. It then basically shifts all the 'ex###' values into that range by using the row index... so I get a plot of the frame below:
   wl     ex421    ex309    ex284      ex347
1 431 0.6168224 0.1267943 0.06392694 0.15220484
2 432 0.6687435 0.2416268 0.05631659 0.08961593
3 433 0.6583593 0.4665072 0.05327245 0.13134187
4 434 0.6832814 0.3576555 0.00000000 0.32432432
5 435 0.6427830 0.2194976 0.12328767 0.50308203
6 436 0.7393562 0.1866029 0.08675799 0.34660977

Needless to say, this is entirely wrong...
So one way I tried to circumvent the issue is going into Excel and manually moving columns up and down, so that in the dataframe each row corresponds to one 'wl' value, whether there are any measured values associated with it or not. This got rid of the values being 'shifted', but R still discards the 'wl' columns after the first one. Instead of getting an entirely wrong plot, I get a section of the right one. The first set of observations (ex421) is plotted over its entire range; pieces of the other ones are seen where ranges overlap.
I've looked at some similar cases which were asked about here in the past, like this -  Reshape data frame from wide to long with re-occuring column names in R.
But I'm new to R and I don't think I could fully understand the proposed solutions. I didn't succeed in reshaping my data in the way I want it to be reshaped (keeping different 'wl' ranges for different sets) and I had no idea which arguments to give to ggplot afterwards. I've tried using data.table, but then I don't know what to give it for value.name and variable.name.
To reiterate, what I want to achieve is what one would get from plotting the four datasets in the spreadsheet by making a single Scatter plot in Excel and adding four different series to it.
Any input would be greatly appreciated!

A: I can think of this solution:
# data:
dt <- structure(list(wl = 431:436,
     ex421 = c(0.6168224, 0.6687435, 0.6583593, 0.6832814, 0.642783, 0.7393562),
     wl = 321:326,
     ex309 = c(0.1267943, 0.2416268, 0.4665072, 0.3576555, 0.2194976, 0.1866029),
     wl = 301:306,
     ex284 = c(0.06392694, 0.05631659, 0.05327245, 0, 0.12328767, 0.08675799),
     wl = 361:366,
     ex347 = c(0.15220484, 0.08961593, 0.13134187, 0.32432432, 0.50308203, 0.34660977)),
   row.names = c(NA,     -6L),
   class = c("data.table", "data.frame"))

# get vectors with wl names
wls <- grep("wl", names(dt))

# get vectors with ex_numbers names
exs <- grep("ex", names(dt))

# reformat the data:
newDt <- cbind(stack(dt, select = wls), stack(dt, select = exs))

# Assign reasonable names:
names(newDt) <- c("wlNumber", "wlInd", "exValue", "exNumber")

Now the data is ready to be plotted with any command:
ggplot(newDt, aes(x = wlNumber, y = exValue, color = exNumber))+geom_point()+geom_line()

The main advantage of this approach is that you can have the table spread into many columns. It doesn't matter, as long as their name has "wl" on it ("ex" for the other variables).

A: Here I load a data frame with your data, making sure to allow repeated names with check.names = F, otherwise it would rename the wl columns to be distinct:
df <- read.table(
  header = T, check.names = F,
  stringsAsFactors = F,
  text = "   wl     ex421  wl     ex309  wl      ex284  wl      ex347
 431 0.6168224 321 0.1267943 301 0.06392694 361 0.15220484
 432 0.6687435 322 0.2416268 302 0.05631659 362 0.08961593
 433 0.6583593 323 0.4665072 303 0.05327245 363 0.13134187
 434 0.6832814 324 0.3576555 304 0.00000000 364 0.32432432
 435 0.6427830 325 0.2194976 305 0.12328767 365 0.50308203
 436 0.7393562 326 0.1866029 306 0.08675799 366 0.34660977")

Then here's a way to reshape, by just stacking subsets of the data. Since there weren't too many column pairs, I thought a semi-manual method would be ok. It preserves the distinct column headers so we can gather those into long form and map to color like in your plot.
library(tidyverse)
df2 <- bind_rows(
  df[1:2],
  df[3:4],
  df[5:6],
  df[7:8]
) %>%
  gather(variable, value, -wl) %>%
  drop_na()

ggplot(df2, aes(x=wl,y=value,color=variable)) +
  geom_point(shape = 1, fill = NA) +
  geom_path(size = 1) +
  theme(panel.grid.major = element_blank(),
        panel.grid.minor = element_blank())


Q: Unable to find Artifactory Project in Visual Studio Extensions and Updates I am using Visual Studio 2017. I am trying to add JFrog Artifactory Project to push artifacts to Artifactory.
To add Artifactory project I need to install it from tools--> Extensions and Updates--> search for Artifactory. But the search results is zero.
So how can i install JFrog Artifactory in Visual Studio 2017. It is working fine with Visual studio 2015.