text:
Q: Delete / remove an attribute from a mixin The following .scss code:
@mixin div-base {
  width: 100px;
  color: red;
}

#data {
  @include div-base;
}

will produce:
#data {
  width: 100px;
  color: red; }

I would like to do something like:
#data {
  @include div-base;
  remove or delete: width right here
}

to produce:
#data {
  color: red;
}

Is it even possible to do something along these lines?

A: The best way to do this is using arguments on your mixin:
@mixin div-base($width: 100px, $color: red) {
  @if $width != false { width: $width; }
  @if $color != false { color: $color; }
}

#data {
  @include div-base($color: false);
}

A: You can achieve the same effect by setting back the width to the default value (set it to auto):
@mixin div-base {
  width: 100px;
  color: red;
}

#data {
  @include div-base;
  width: auto;
}


text:
Q: I get no such file or directory when moving dist folder contents from gitlab to aws server instance I am new to Gitlab CI/CD and trying to fix this all day long but nothing works. I am trying to move the dist folder generated by gitlab runner after build stage to aws ec2-instance folder location. I am currently implementing CI/CD pipeline using Gitlab and this is how my .gitlab-ci.yml looks like:
# Node Image for docker on which code will execute
image: node:latest

# This is the stages / task to perfom in jobs
stages:
  - build
  - deploy

# caching for reuse
cache:
  key: "$CI_COMMIT_REF_SLUG"
  paths:
  - node_modules/

# This command is run before the execution of stages
before_script:
  - npm install

# Job One for making build
build_testing_branch:
  stage: build
  script:
    - node --max_old_space_size=4096 --openssl-legacy-provider ./node_modules/@angular/cli/bin/ng build --configuration=dev-build --build-optimizer
  only: ['testing']

# Job Two for deploy build to server
deploy_testing_branch:
  stage: deploy

  before_script:
        - 'which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )'
        - eval $(ssh-agent -s)
        # - echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add -
        - mkdir -p ~/.ssh
        - chmod 700 ~/.ssh
        - echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config
        # - apt-get update -y
        # - apt-get -y install rsync

  artifacts:
    paths:
      - dist/

  script:
    - ssh-add <(echo "$SSH_PRIVATE_KEY")
    - ssh -p22 ubuntu@$SERVER_IP "rm -r /usr/share/nginx/user-host/ui-user-host/dist/; mkdir /usr/share/nginx/user-host/ui-user-host/dist/"
    - scp -P22 -r  $CI_PROJECT_DIR/dist/ ubuntu@$SERVER_IP:/usr/share/nginx/user-host/ui-user-host/dist/

  only: ['testing']

The build process works just fine with success confirmation, but the deployment stage fails because I get:
$scp -P22 -r  $CI_PROJECT_DIR/dist/ ubuntu@$SERVER_IP:/usr/share/nginx/user-host/ui-user-host/dist/
/builds/user-live/ui-user-host/dist: No such file or directory
Cleaning up project directory and file based variables

So, I dont understand why its not able to locate dist folder in above location. If i correctly understand this should be available on the gitlab runner's filesystem. Is it because scp command is not right?
EDIT:
I also tried with
- scp -P22 -r  dist/ ubuntu@$SERVER_IP:/usr/share/nginx/user-host/ui-user-host/dist/

and
- scp -P22 -r  dist/* ubuntu@$SERVER_IP:/usr/share/nginx/user-host/ui-user-host/dist/

but no luck!

A: You are building your dist folder in build_testing_branch job and trying to access it in deploy_testing_branch for this to work you have to give the dist folder as artifact in build_testing_branch job (since dist is created there) and not in deploy_testing_branch.

redpajama_set_name: RedPajamaStackExchange


text:
Q: MySQL SUM with GROUP BY producing long decimals So, I have no idea why this is happing. I know I can fix it with rounding, but I'd like to know why I even need to. I am selecting a set of double, grouping them by a common factor, and applying SUM to them. In the results, I get very long decimals, at times a rounded repeating. An example might be 185708.90000000002 or 199959.34999999998.
I have no idea how this could happen. The most precise my numbers are before summing is 10^2. It's important to note also, that this does not happen all the time, just occasionally. In most cases the numbers look correct.

A: I have found the answer to this question, thanks to a comment. Floats and Doubles are not stored as exact numbers internally. Converting the columns to Decimal solves most issues.


text:
Q: after networkx library update nx.connected_component_subgraphs(G), this error genarated gen=(G1.subgraph(c) for c in nx.connected_components(G1))

G1_LCC=max((G1.subgraph(c) for c in nx.connected_components(G1)),key=len)

G2_LCC=max((G2.subgraph(c) for c in nx.connected_components(G2)),key=len)

plt.figure()
nx.draw(G1_LCC,node_color="red",edge_color="grey",node_size="20")
plt.savefig("vill1.pdf")

what's wrong with it? this is showing error.

TypeError: ufunc 'sqrt' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

A: You get a TypeError because node_size is supposed to be either a scalar or an array but you are passing a string (docs).
Changing the value of node size to a scalar will solve the issue.
nx.draw(G1_LCC, node_color="red", edge_color="grey", node_size=20)

A: Yes, a 'size' value is not a string. Try with int or float.
nx.draw(G1_LCC, node_color="red", edge_color="grey", node_size=20)


text:
Q: Jquery append html weird behavior i have the following ajax:
$.ajax({
    type: 'POST',
    url: myBaseUrl + 'Products/ajax_get_subcategories',
    dataType: 'json',
    data: {
        id: id
    },
    success: function (data) {
        var length = data.length;
        var div_subcategory = $('#subcategory');
        div_subcategory.html('');
        div_subcategory.append(
            "<select id='subcategory' name='data[Product][subcategory_id]'>"
        );
        for (var i = 0; i < length; i++) {
            var id = data[i]['Subcategory']['id'];
            var name = data[i]['Subcategory']['name'];
            $('#subcategory').append(
                "<option value=''+id>" + name + "</option>"
            );
        }
        div_subcategory.append("</select>");
    }
});

Now as you can see it appends a select into a div block.
But! there is a catch here is the output of the HTML after the ajax has been called:
    div id="subcategory" class="subcategory">
<select id="subcategory" name="data[Product][subcategory_id]"></select>
<option +id="" value="">Telte</option>
<option +id="" value="">Toilet</option>
<option +id="" value="">Service</option>
<option +id="" value="">Borde</option>
<option +id="" value="">Stole</option>
<option +id="" value="">Lyd og lys</option>
</div>

As you can see it closes the select tag before adding the options.
Can anyone tell me why this is happening?

A: Try
change your success code
success: function (data) {
    var length = data.length;
    var div_subcategory = $('#subcategory');
    div_subcategory.html('');
    var select_append = "<select id='subcategory' name='data[Product][subcategory_id]'>";
    for (var i = 0; i < length; i++) {
        var id = data[i]['Subcategory']['id'];
        var name = data[i]['Subcategory']['name'];
        select_append += "<option value=''" + id + ">" + name + "</option>";
    }
    select_append += "</select>"
    div_subcategory.append(select_append);
}

create a variable select_append and concatenate all your code in that and append that variable in the end.

A: Try
$(div_subcategory).find('select').append(...)

A: When you write:
div_subcategory.append("<select id='subcategory' name='data[Product][subcategory_id]'>");

jQuery will insert
<select id='subcategory' name='data[Product][subcategory_id]'></select>

And becasue div_subcategory will have the same id as the select you will be matching the div instead.
Instead I would write this by creating the html in a string and injecting it all at once.
    var html += "<select id='subcategorysel' name='data[Product][subcategory_id]'>";
    for (var i = 0; i < length; i++) {
        var id = data[i]['Subcategory']['id'];
        var name = data[i]['Subcategory']['name'];
        html += "<option value=''+id>" + name + "</option>";
    }
    html += "</select>";
    div_subcategory.append(html);

This snippet updates your code to use different ids and appends the html all in one go which should be quicker.

A: when you write this syntex
div_subcategory.append(
        "<select id='subcategory' name='data[Product][subcategory_id]'>"
    );

DOM automatically detects an HTML element like this
<select id='subcategory' name='xxx'></select>

and then you are appending other option elements after this
so solution is first make a string of an HTML and then append like
var html = "<select id='subcategory' name='data[Product][subcategory_id]'>";
    for (var i = 0; i < length; i++) {
        var id = data[i]['Subcategory']['id'];
        var name = data[i]['Subcategory']['name'];
        html += "<option value='' + id>" + name + "</option>";
    }
    div_subcategory.append(html);


text:
Q: Maven check latest version, only release not snapshot How could I check latest release version of application?
I can check version with: mvn help:evaluate -Dexpression=project.version.
But this returns snapshot version, is there way to check release versions only?
I'm using Nexus repository for the artifact repository, and Nexus offers API for checking artifacts (this needs credentials). But I would like to know what would be the Maven way for this.
This is for Jenkins pipeline.

A: This can be achieved using the enforcer goal:
mvn clean install enforcer:enforce -Drules=requireReleaseDeps

ref: https://maven.apache.org/enforcer/maven-enforcer-plugin/enforce-mojo.html


text:
Q: Validation code produces error InteropServices.COMException (0x800A03EC): Exception from HRESULT: 0x800A03EC I want to add validation code to a cell in an Excel workbook using Python and the Excel Object Model library. My code is as:
valid = config.optionsSheet.Range('A2').Validation
valid.Delete()
valid.Add(XlDVType.xlValidateList, XlDVAlertStyle.xlValidAlertStop, \
    XlFormatConditionOperator.xlBetween, "=R20C4:R21C4", None)

The last line above fails with the following error: any help appreciated.
EnvironmentError: System.Runtime.InteropServices.COMException (0x800A03EC): Exception from HRESULT: 0x800A03EC

Server stack trace:
   at Microsoft.Scripting.ComInterop.ComRuntimeHelpers.CheckThrowException(Int32 hresult, ExcepInfo& excepInfo, UInt32 argErr, String message)
   at CallSite.Target(Closure , CallSite , Object , Object , Object , Object , String , Object )
   at System.Dynamic.UpdateDelegates.UpdateAndExecute6[T0,T1,T2,T3,T4,T5,TRet](CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5)
   at CallSite.Target(Closure , CallSite , CodeContext , Object , Object , Object , Object , String , Object )
   at System.Dynamic.UpdateDelegates.UpdateAndExecute7[T0,T1,T2,T3,T4,T5,T6,TRet](CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6)
   at Microsoft.Scripting.Interpreter.DynamicInstruction`8.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.LightLambda.Run2[T0,T1,TRet](T0 arg0, T1 arg1)

A: You're getting an exception because of the wrong formula.
I suggest you manually create data validation first and correct it until it starts to work properly, I always do it that way. The most common message from Excel when manually typing a wrong formula (in a data validation using lists scenario) is:

The list source must be a delimited list or a reference to a single row or column.

Take a look at these tutorials, they might help you understand the concept of validation using lists in Excel:
Apply data validation to cells - office.microsoft.com
Excel Data Validation Introduction - contextures.com


text:
Q: How to group records by day using timestamp as a field in mongodb and nodejs I would like to group records by day for certain period. I have tried so far using this code added into the aggregate function:
 {
    $group : {
         _id : {  day: { $dayOfMonth: "$timestamp" }},
         count: { $sum: 1 }
      }
 }

And this is how a document looks like:
{
"_id" : ObjectId("ec9cddd50e08a84cd3f4cccb"),
"orgid" : "5c48500d84430a3a4b828e85",
"timestamp" : ISODate("2019-03-28T14:00:00.000Z"),
"apiid" : {
    "zxczxczxczxczxc" : {
        "errortotal" : 6,
        "hits" : 6,
        "humanidentifier" : "Feedback",
        "identifier" : "663cfc345e42401c6443cfd635301f8f",
        "lasttime" : ISODate("2019-03-28T14:58:07.355Z"),
        "success" : 0,
        "totalrequesttime" : 0.0,
        "requesttime" : 0.0
    }
},
"apikeys" : {
    "00000000" : {
        "errortotal" : 3,
        "hits" : 3,
        "humanidentifier" : "",
        "identifier" : "00000000",
        "lasttime" : ISODate("2019-03-28T14:55:10.438Z"),
        "success" : 0,
        "totalrequesttime" : 0.0,
        "requesttime" : 0.0
    },
    "cae81afc" : {
        "errortotal" : 3,
        "hits" : 3,
        "humanidentifier" : "EE5RqcXMTqcWEx8nZv3vRATLspK2",
        "identifier" : "cbe81afc",
        "lasttime" : ISODate("2019-03-28T14:58:07.355Z"),
        "success" : 0,
        "totalrequesttime" : 0.0,
        "requesttime" : 0.0
    }
}

Any idea how can I achieve this?
Result I get is: [ { _id: { day: null }, count: 3 } ], it seems wrong for me since I have two documents with the same date and another document with different timestamp
UPDATE:
I also have this inside aggregate fuction:
  // Project things as a key/value array, along with the original doc
                {
                    $project: {
                        array: {$objectToArray: '$apikeys'},
                        doc: '$$ROOT',
                    }
                },

                // Match the docs with a field value of 'x'
                {$match: {'array.v.humanidentifier': {$in: trialCustomerUsers}}},

If I comment this part it will work fine the grouping, but the thing is I would also do some where statement in cases where I also dont know what woudl be the key, that's why I had to add this piece of code

A: Just accumulate the records in a new field with the $push operator
{
    $group : {
         _id : {  day: { $dayOfMonth: "$timestamp" }},
         records: { $push: "$$ROOT" }
      }
 }

A: Change this line
_id : {  day: { $dayOfMonth: "$timestamp" }}

to
_id : {  day: { $day: "$timestamp" } }

or you can do something like this
$group : {
   _id : null,
   day: '$timestamp',
   count: { $sum: 1 }
}

A: You have $projected your all the root document in the doc field using $$ROOT. Now your aggregation should be as followed
db.collection.aggregate([
  { "$project": {
    "array": { "$objectToArray": "$apikeys" },
    "doc": "$$ROOT"
  }},
  { "$match": { "array.v.humanidentifier": { "$in": trialCustomerUsers }}},
  { "$group" : {
    "_id" : { "day": { "$dayOfMonth": "$doc.timestamp" }},
    "count": { "$sum": 1 }
  }}
])


text:
Q: What is a proper way of implementing a server-side domain-scope global variable in a Vue.js application? I'm learning Vue.js while trying to write an app that will need server-side state machine objects(to share some resources between clients and distribute client tasks to them). For this, I need some (domain-wide or at least process-scope)global variables such that a client writes to it, another client can see it by requesting something. But I'm going to need this on http requests.
I guess code-behind part is main.js, with nano main.js this is the environment:
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

This doesn't look like multithread-ing. Does the new mean that each client creates a new instance or is it just one instance and it serves all clients? Should I use "global" variables in this scope or somewhere else in App object? In src folder, there is router folder but no App folder but a file App.vue. This file includes a script
<script>
export default {
  name: 'App'
}
</script>

Am I supposed to use only local(per client) variables here or any global is allowed too?
I added a variable in main.js as "myGlobal" as
...
import router from './router'
var myGlobal = 3.14;
...

and on client side
 console.log({{myGlobal}});

returns an error on building phase.
Syntax Error: Unexpected token (158:21)

> 158 |         console.log({{myGlobal}});

OS: Ubuntu 18.04


text:
Q: iOS In-App Purchases - Download or unlock new content? In my game, I'm planning to add IAPs for different level packs that the player will be able to buy and play in the game. But after reading documentations on IAPs, there's still one question I'm wondering : Is it better to download the new content from Apple's server, or unlock it in the game with NSUserDefaults?
The problem is that if I chose option 2, the content will be easily hackable, and the app will need an update for each DLC I'm adding.
And the problem with option 1 is that the new content will be downloaded in the Documents folder, but my app search the list of levels in the resource folders (I know it's not hard to implement, but I'm just saying the pros and cons)
Anyone can tell me which one is the best practice, and why?
Thanks in advance!

A: Well, I think both options are good. Whats the size of these packs? If you have numerous iaps all consisting of new levels, id recommend to have them downloadable, imagine shipping the app without the extra levels, quite a network-loadoff.
As you are stating, option nr 1 gives you the ability to add levels dynamically. This is convenient since apple are quite slow when it comes to uploading of new builds. Come to think of it, they are not super fast when it comes to revising your DLC either.
Due to the hacking risk and initial reduction of app-filesize, I would definately go with option one but if possible, i'd provide the actual content from a private FTP server. That way, the new content is available directly.


text:
Q: How to vertically align links and a button in a div? Thanks for the wonderful opportunity.
I have a problem I facing hard time to solve right now due to my limited front end dev skills : I am trying to vertically align links with a button.
HTML here :

Get Help

Contact Us

Suggestions

<button>test</button>

CSS here:
.header_info{
    position: relative;
    margin: 0 10px;
    color: #7E7E7E;
    font-weight: bold;
    cursor: pointer;
    padding-left: 0;
    padding-right: 0;
    list-style:none;
    float: left;
}

.header_info ul{
     display: inline-block;
     list-style: none;
}

.header_info li{
    display: inline;
    margin-right:11px;
}

.header_info li :hover{
    color: #F98866;
}

.header_info a{
    color: #7E7E7E;
}

As you can see , the links and the buttons aren't on the same line and I would like to fix this so it can look neat and professional.
I would appreciate any help/enhancements of my code.
Thanks.
JSFIDDLE ==> https://jsfiddle.net/5nzvwwjx/5/

A: You can use display: flex; align-items: center; on nav

nav {
  display: flex;
  align-items: center;
}

.header_info {
  position: relative;
  margin: 0 10px;
  color: #7E7E7E;
  font-weight: bold;
  cursor: pointer;
  padding-left: 0;
  padding-right: 0;
  list-style: none;
  float: left;
}

.header_info ul {
  display: inline-block;
  list-style: none;
}

.header_info li {
  margin-right: 11px;
  display: inline;
}

.header_info li:hover {
  color: #F98866;
}

.header_info a {
  color: #7E7E7E;
}

Get Help

Contact Us

Suggestions

      <button>test</button>

Or alternatively, you can make .header_info and #header-login display: inline-block; and that will center them currently, though if you add more content, using vertical-align: middle; will keep them aligned.

.header_info {
  position: relative;
  margin: 0 10px;
  color: #7E7E7E;
  font-weight: bold;
  cursor: pointer;
  padding-left: 0;
  padding-right: 0;
  list-style: none;
}

nav > div {
  display: inline-block;
  vertical-align: middle;
}

.header_info ul {
  display: inline-block;
  list-style: none;
}

.header_info li {
  margin-right: 11px;
  display: inline-block;
  vertical-align: middle;
}

.header_info li:hover {
  color: #F98866;
}

.header_info a {
  color: #7E7E7E;
}

Get Help

Contact Us
second line

Suggestions

      <button>test</button>

A: You can just move the button into the ul list like so:

Get Help

Contact Us

Suggestions

<button>test</button>

I've also moved the classes onto the li if you still needed them for styling.

A: I forked your fiddle here: https://jsfiddle.net/yyb7p8o9/
I cleaned up the HTML, which had a few small issues.  Then, I added a 0px margin to style for "header_info ul" in the CSS:
.header_info ul{
     display: inline-block;
     list-style: none;
   margin: 0px
}


text:
Q: A bizarre scenario with Observable which leads observers to miss items in OnNext I have an application which keeps track of milk price fluctuation by states, users when they see milk price at their local grocery store can come to a website and submit that price (much like GasBuddy).
When they submit the price, I receive it in my Observable<MilkPrice>, here is milk price implementation
class MilkPrice {
    string State {get;set;}
    decimal Price {get;set;}
 }

When I receive the price, I maintain a list of MilkPriceTracker object each of an State, If object for particular state doesn't exist, I add it to my List object, MilkPriceTracker is a view model which takes IObservable in the constructor and this is how I construct the Tracker object
if (!_statesTracker.Any(s => s.State.Equals(receivedInOnNext.State)) {
      _statesTracker.Add(new MilkPriceTracker (mainObservable.Where(s.State.Equals(receivedInOnNext.State));
     }

I don't add all 50 states to my list by default because, I only like to have states that have any price reported, Now here is the fun part, say 1 thousand users from Virginia starts reporting prices at the same time....
When first guy reports, he will construct the new Tracker object and his message will be missed because that has already been consumed, I could try passing Observable.Concat(Observable.Return(alreadyReceivedObj), mainObservable.Wher.....)) to the constructor
I tried it but because of the high frequency of messages, some are still missed by the time mainObservable's subscription.OnNext is handled and new Tracker is constructed.
How do I "pause" the mainObservable and tell it to "DVR" it or "Buffer" it until I resume ? so I don't miss any messages.
If I am not clear enough, feel free to tell me
Thanks.

A: It doesn't sound bizzare, more like a lack of understanding of Reactive Programming. ;-)
Try using GroupBy.

A: I feel like dancing. Thanks to the nicest guy in the world Lee Campbell
I wrote the following code to solve my issue.
mainObservable
            .GroupBy(k => k.State)
            .Select(g => new MilkPriceTracker(g.Key, g))
            .ObserveOnDispatcher(DispatcherPriority.DataBind)
            .Subscribe(_statesTrackers.Add);


text:
Q: nested if statement I need an if-statement that creates a field called "part_ID".  This field  takes the field "p.ID" and looks it up in "a.Part_ID".  If the part_ID is not null in "a.Part_ID", then  the part ID should remain unchanged and just be "a.Part_ID".  If the part ID is null, then it should lookup the part ID in "b.Part_ID_Not_cataloged" and if the part ID is listed, then it should substitute it with "b.related_Part_ID_in_catalog".
   SELECT a.Part_ID, p.ID, b.Part_ID_Not_cataloged, b.related_Part_ID_in_catalog
     FROM (SYSADM_PART AS p
LEFT JOIN tbl_concatenated_data_view_only AS a ON p.ID = a.Part_ID)
LEFT JOIN tbl_Part_ID_Not_in_catalog_entry AS b ON p.ID = b.Part_ID_Not_cataloged;

A: You will need to use IIF


text:
Q: How to dynamically change input type On my vue page I have three different inputs:
<input
  id="id"
  class="flex-grow bg-white p-4 text-sm items-center focus:outline-none"
  type="text"
  name="id"
  v-model="id"
  placeholder="Enter your email or phone number..."
/>

<input
  v-show="phone"
  id="phone"
  class="flex-grow bg-white p-4 text-sm items-center focus:outline-none"
  type="tel"
  name="phone"
  v-model="phone"
  required
  placeholder="Enter your phone number..."
/>

<input
  v-show="email"
  id="email"
  class="flex-grow bg-white p-4 text-sm items-center focus:outline-none"
  type="email"
  name="email"
  v-model="email"
  required
  placeholder="Enter your email..."
/>

Now the first id field is the default field that shows on my page.  When the user starts typing I have a watcher to watch the value of "id".  If it's a string then it swaps the default text field for the email field.
If it's numeric then it swaps it for the tel field.
This is the watcher:
watch: {
  id(newVal, oldVal) {
    if (this.startsWithLetter(newVal)) {
      this.$nextTick(() => {
        this.phone = null
        this.email = newVal
        this.$el.querySelector('#email').focus()
      })
    } else {
      this.$nextTick(() => {
        this.email = null
        this.phone = newVal
        this.$el.querySelector('#phone').focus()
      })
    }
  },
},

Now this works however I've realised the focus simply does not work when the new field is swapped in.  The new field doesn't get focus and the soft keyboard hides itself.

A: I'm not sure exactly of what you're trying to achieve here. Seems a bit hard to understand for me.
Meanwhile, here is a simple example on how to have a dynamic input type depending of the content of the input.
<template>

input: <input v-model="userInput" :type="phoneOrText" />

</template>

The input will be text if the input contains only text and will swap to tel if it contains any numbers thanks to the /\d\ regex (any digit). I've chosen password for the screenshots because it is more visual but it can be anything. tel is working great on phone too and does not require any focus() or selection.
Not sure if it helps but right now, it seems a bit too cryptic for me to help you more.


text:
Q: Sequentially firing multiple random timeouts in JavaScript I know at first glance (due to the title) this looks like one of the "Did you try searching Google before posting?" questions, but I can't seem to find an answer for the specific issue I'm experiencing.  Sorry if I'm a noob....  still learning :)
I need to simulate a pause in javascript, but the setTimeout(function_call, timeout) function is not working for me.  Reason being... when that setTimeout function is called, it then makes the function call asynchronously.
A little background:
I'm trying to simulate text being typed into a div at randomly timed intervals.  I want it to appear as if a person is actually typing a message while the user is viewing the page.  Since the timeout is a random interval and the function call is made asynchronously, the text ends up being printed in a random order.
Here is a snippet of what I have thus far:
typeString: function(s)
{
    for(var i=0;i<s.length;i++)
    {
        var c = s.charAt(i);
        var temp = setTimeout("MessageType.typeChar('" + c + "')", this.genRandomTime());
    }
}

Thanks in advance for your help.
CJAM

UPDATE: By adding the timer delay to a varialbe, it enabled me to offset timeOut for the asynchronous calls.  Thank you all for your quick responses.  Here is the updated code:
typeString: function(s)
{
    var delay = 0;

    for(var i=0;i<s.length;i++)
    {
        var c = s.charAt(i);
        setTimeout("GoogleTyper.typeChar('"+c+"')", delay += this.genRandomTime());
    }
}

A: Have you tried cumulatively setting the timeout?  Stick a variable outside of your loop and initialize it to 0.  Let's call it timeout for now.  Add a random amount of time to this variable at the beginning of each iteration of your loop, and make the timeout work off of that.  This way, you are ensured that functions are being called in order.

A: Your problem is you are using one all your times are delayed starting from now - the next timer needs to be fired after the previous. Simply add the previous timer delay to the new timer.
typeString: function(s)
{
    var delay = 0;
    for(var i=0;i<s.length;i++)
    {
        var c = s.charAt(i);
        delay = delay + this.genRandomTime();
        var temp = setTimeout("MessageType.typeChar('" + c + "')", delay );
    }
}

A: Instead of passing to each timer event that character to be displayed, let each event handler grab the next character off of a queue (array, list whatever), so the order is maintained.


text:
Q: Physical coupling as a measurable quantity I have a question about Preskill's quantum field theory note. He want to argue that the renormalized coupling is something measurable.
First let me introduce some backgroud. Suppose the Lagrangian can be written as,
\begin{align}
\mathcal{L}=&\frac{1}{2}\partial_\mu\phi_{ B}\partial^\mu \phi_{ B}
-\frac{1}{2}m_0^2\,\phi_{ B}^2-\frac{1}{3!}\lambda_0\,\phi_{ B}^3 \nonumber\\[5pt]
=&\frac{1}{2}\partial_\mu\phi_{ R}\partial^\mu \phi_{R}
-\frac{1}{2}m^2\phi_{ R}^2-\frac{1}{3!}\lambda_{ R}\phi_{ R}^3 +\mathcal{L}_{\rm ct}
\end{align}
where the counterterms are
\begin{align}
\mathcal{L}_{\rm ct}=\frac{1}{2}(Z-1)\big(
\partial_\mu\phi_{R}\partial^\mu \phi_{ R}-m^2\phi_{R}^2\big)
-\frac{1}{2}Z\delta m^2\phi_{R}^2-\frac{1}{3!}\delta\lambda\phi_{R}^3
\end{align}
The renirmalized couplimh is defined as
\begin{align}
\Gamma(m^2,\,m^2,\,m^2)=\lambda_{R}
 \end{align}

In order to argue $\lambda_R$ is measurable, he consider the 2-2 scattering process,

This amplitude with external legs on shell has the form,

so $-i\lambda_{R}^2$ is the exact residue of each pole. The poles occur for physical values of the momenta, so their residues can be determined only by a continuation of the measured amplitude away from physical momenta. I do not quite understand this last argument. The amplitude $i\mathcal{M}$ is observable has pole structure with residue $-\lambda_R^2$. Why do we need analytical continution away from physical momentum? Away from physical momentum,  $i\mathcal{M}$ is no longer obserable, and the 3-pt 1PI diagram is no longer $\lambda_R$. For me, it is also strange we can measure some divergent quantity (pole structure). How can we read pole structure from machine? Sorry I do not no particle experiments.


text: Q: Tomboy in the indicator bar in Ubuntu 16.04 Once (with the old ubuntu 12.04lts and old gnome) I had Tomboy as a icon in what I think was called indicator bar (top bar). Now with gnome 3 no icon is shown in the top bar, how can I have Tomboy on that bar as before?


text:
Q: Automatically updating a userform label I'm new to VBA and programming in general, so bear with me. I have so far 6 labels, and a simple useform where one enters a value corresponding to each label. However, the label name can change (say if new labels are added) and I wanted a way to automatically change the label name. This is what I have so far:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)

Update_invest.Invest1.Caption = Sheet1.Range("A12").Value
Update_invest.Invest2.Caption = Sheet1.Range("A13").Value
Update_invest.Invest3.Caption = Sheet1.Range("A14").Value
Update_invest.Invest4.Caption = Sheet1.Range("A15").Value
Update_invest.Invest5.Caption = Sheet1.Range("A16").Value
Update_invest.Invest6.Caption = Sheet1.Range("A17").Value

End Sub

Now this works: if I change a label it will update the userform. However, if I just open the new worksheet and don't click on say cell A12, it will not update the userform and will leave the label name as it's default name. How do I make it actually save the label name, so that if a user opens the workbook the userform will already have the current cell value (without first having to click on the cell for the userform to update)?
I have this code currently on sheet1.

A: Solution 1
You can put your code in Worksheet_Activate which is run when the user select the sheet or in Workbook_Open which is run when the user open the workbook. Currently, your are using Worksheet_SelectionChange which is only run when the user change the selection, hence the need to click on another cell.
NOTE : if you chose to use Workbook_Open, you will need to put the sub in the ThisWorkbook file and not in the worksheet itself.
Solution 2
If you instead want to make the changes permanant and not have code to always update it, you will need to go through the designer
Here is an exemple
Sub exa1()
    Dim i As Long, n As Long
    n = 12
    With ThisWorkbook.VBProject.VBComponents("Update_invest").Designer
        For i = 1 To .Controls.Count
            If TypeName(.Controls(i - 1)) = "Label" Then
                .Controls(i - 1).Caption = Sheet1.Cells(n, 1).Value
                n = n + 1
            End If
        Next i
    End With
End Sub

source


text:
Q: How can I launch gnome-terminal with unique titles for multiple tabs? I've seen various posts about launching gnome-terminal with multiple tabs and the script below is working for me.  That is to say, this script will launch gnome-terminal with various working directories or profiles. . .
#!/bin/sh
gnome-terminal \
--tab --working-directory=$HOME/notes  \
--tab --working-directory=$HOME/puppet \
--tab --profile=root-beamish           \
--tab --profile=odyssey                \
--tab --profile=root

... but I'd like to set a unique title for each tab.
In the case where a tab has its own profile I can change the title from within gnome-terminal with Edit | Profiles | (NAME) | Edit | Title and Command and then change "Initial Title" to what I want and "When terminal commands set their own titles" from "Replace initial title" to "Keep initial title".  However, I'd rather not create a unique profile for every tab.  I'd like a generic solution.
I've tried adding --title='MyTitle' but it doesn't seem to help.  I'm using GNOME 2.28.2 on CentOS 6.

A: Use the -t option. (see gnome-terminal --help-terminal-options)
gnome-terminal \
--tab -t "notes" --working-directory=$HOME/notes  \
--tab -t "puppet" --working-directory=$HOME/puppet \
--tab -t "beamish" --profile=root-beamish           \
--tab -t "odyssey" --profile=odyssey                \
--tab -t "root" --profile=root

-------- updated at 2011-11-15 22:00:00 --------
So... that worked for me on Solaris 11 Express, with gnome-terminal 2.30.2.
Since then, I've been able to test it on Ubuntu 11.04 (Natty), which uses 2.32.1, and found exactly the same behavior as you.
In the case of Ubuntu, I was able to track it to the ubuntu .bashrc file.  In particular, the section that looks like:
# If this is an xterm set the title to user@host:dir
case "$TERM" in
xterm*|rxvt*)
    PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"
    ;;
*)
    ;;
esac

In this case, the PS1 variable is being expanded for terminal types matching xterm* and rxvt*.
PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"

specifically the part between PS1="\[\e]0; and \a\].   Those get turned into the window title.
Once I commented out that whole case statement, the behavior of gnome-terminal with the -t option worked as expected.  I'll see if I can find a CentOS 6 box to test this with, too.

-------- updated at 2017-11-1 09:38:00 --------
So it looks like more recent versions of Gnome-Terminal have made away with some useful features, like the simple -t option to set terminal titles.
It is still possible to set terminal titles at runtime, it's just ugly as hell now.  You can use printf or echo in the command to effect a title.
For example:
To start a terminal window with 1 tab, titled 'My Fancy Title' using printf:
gnome-terminal --tab -e 'bash -c "printf \"\e]2;My Fancy Title\a\"; bash -i"'

To start a terminal window with 2 tabs, one running top, and one with a title, using echo:
gnome-terminal \
--tab -e 'bash -c "echo -ne \"\033]0;my tab running top\007\"; top"' \
--tab -e 'bash -c "echo -ne \"\033]0;My Fancy Title\007\"; bash -i"'

This does at least offer an option for setting the terminal title at runtime.
See this post for an option to put a simple function in your ~/.bashrc to allow for setting and resetting the title at will.

A: When I did a

$ gnome-terminal -t "MyTitle"

The new terminal had "MyTitle" as the title for a moment and immediately was replaced by the default title.
I went to

Edit | Profiles | (Default) | Edit | Title and Command

And changed "When terminal command set their own titles:" to "Keep initial title", the above command launched a terminal with "MyTitle" as the title.

A: GNOME Terminal 3.28.2 (Ubuntu 18.04)
using VTE 0.52.2 +GNUTLS -PCRE2
To make a tab in a directory with a title (running the default shell):
gnome-terminal --tab --working-directory "$SOME_DIR"  --title "Some Title"

If you want multiple tabs, just run this command multiple times.
To run a 0 argument command append  -- cmd. e.g
gnome-terminal --tab --title "CALC" -- python

No idea what you do if you want arguments. Note:
man gnome-terminal is out of date. gnome-terminal --help is of more help.

A: This creates two tabs, each opened to a directory "foo" or "bar", with tab titles "foo" and "bar"
gnome-terminal --tab -t foo -e 'sh -c "cd foo; sh"' --tab -t bar -e 'sh -c "cd bar; sh"'


text:
Q: We have $n$ identical objects, and we want to distribute them to $3$ different children $A$, $B$, $C$.
We have $n$ identical objects, and we want to distribute them to $3$ different children A, B, C. In how many ways can this assignment be done?

Please note that for example if we had $6$ objects, if A gets $4$, B gets $2$ and C gets $0$, it's different from A gets $4$, B gets $0$ and C gets $2$. Compute the general formula and then find the correct answer if $n=9$.

Answer: 84

No matter what, I still don't get the correct answer. I tried as such: I lined up the $n$ objects , (let's draw them as $0$s). Now I want to separate them into $3$ teams. I am going to throw randomly two sticks ( imagine them as $1$s) . Where they fall, they will form the limits of each child's objects. For example $01 0 0 01 0 0 0 $ : Now take a look at left if the first stick: That's going to be how many objects A gets ( here is 1), between the first stick and the second it's what B gets, and what remains goes to C. If we had : $1 0  0 0 0 0 0 0 1$ A gets $0$, B gets everything, C gets $0$, if we had $ 110  0 0 0 0 0 0$ ** A gets $0$, B gets $0$, C gets it all** and so on... So, we actually need to compute how to throw 2 identical sticks into $(n-1) + 2 = (n+1)$ holes, which can be done in $C(n+1 + 2 -1, 2)=C(n+2,2)$ which for $n=9 \rightarrow C(11,2)=55$. What am I missing?

A: The number of ways how to distribute $n$ identical objects among $k$ persons is identical to the number of $k$-tuples of non-negative integers that sum to $n$. By stars and bars this number is given by
$$
\binom{n+k-1}{k-1} = \binom{9+3-1}{3-1} = \binom{11}{2} = 55.
$$
Your answer is correct, the given answer is wrong. (It coincides with $\binom{9}{3}$ by the way.)


text:
Q: What is the proper way to do the strong and em elements together? I keep "getting end tag for element "EM" which is not open
end tag for element "STRONG" which is not open" in the validator and I can't seem to figure out how to implement this correctly.
I have tried moving around the tags, also I have checked and there is 1 opening and 1 closing of each so I am a tad bid confused. Line 34 & 35.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<title>  Restaurant Information </title>

Restaurant Information

 TYPE OF CUISINE: Italian and Continental

PRICE RANGE: Lunch Entrees $9 to $14, Dinner $12 to $21

ATMOSPHERE: Elegant but casual, Cozy, Romantic, Fun & Festive, Like your second home.

APPEALS TO: Appeals to everyone, from Tourists to Couples and especially to Business Groups

DRESS CODE: Elegant but casual

MEALS SERVED: Lunch, Dinner

Contact Us:

 ADDRESS:

 Cafe Townsend

 600 Townsend

 San Francisco, CA 94103

PHONE: (415) 555-1234

FAX: (415) 555-1235

Email Us

DIRECTIONS: Directions Via Link to Google Map.

HOURS: Cafe Townsend is open seven days a week for dinner and Monday thru Friday for lunch.

 LUNCH:  Monday thru Friday 11:30am - 2:00pm

DINNER:Sunday thru Thursday 5:30pm - 10:00pm

Friday and Saturday 5:30pm - 11:00pm

CREDIT CARDS ACCEPTED: Visa, Mastercard, American Express, Discover, Diners Club

Awards and Recognition:

Best New Restaurant

Restaurant News, 1994

Best Veal in California

California Magazine, February 2002

SPECIAL FEATURE: Cafe Townsend serves only the very highest quality meats, authentically prepared for your dining pleasure. A specialty at Cafe Townsend is the signature dishes that are presented tableside. Dine in our elegantly casual atmosphere at our convenient San Francisco location.

Cafe Townsend Is Proud To Offer The Following Services:

BANQUET FACILITIES / PRIVATE ROOM: We can accommodate your party of up to 34 (50 for standing receptions) in our private dining room with Roman motif and gold and peach accents. This room offers soundproof doors and lighting that will adjust from candlelight to reading luminance. In addition, we have semi-private accommodations, seating up to 50, in one section of our main dining room that can be separated by curtains. For groups of 100 to 120 our main dining room is available. Cafe Townsend will also consider closing the restaurant for a minimum charge to provide the space you need to accommodate your largest parties. Read about our Special Events.

BAR: Cafe Townsend offers a full service bar. In addition, we have three frozen specialty drinks. For a special occasion, try the Belini, a combination of peach nectar, champagne and Bacardi.

CATERING: Both on and off premise catering is available. See the Special Events page for more details.

DELIVERY / TAKE-OUT: Our full menu is available for take-out. Cafe Townsend does not offer delivery.

ENTERTAINMENT: Enjoy our new red Digital Surround Sound Baby Grand Concert Master "Digital" Piano.

RESERVATIONS: Recommended

SEATING CAPACITY: 200

SMOKING CHOICE: Our restaurant is proud to be a non-smoking establishment.

A: HTML tags are not valid inside a STYLE block (as Chris hints in his comment). The text content inside the STYLE tags must be CSS, not HTML, which is why the HTML validator does not like it. (When used in this way the STYLE element is effectively a way of embedding a style sheet directly in the HTML.)
The validator is not really telling you that directly though -- and it could certainly be giving us a more helpful error message in this instance.
The validator is complaining about this:
Line 34, Column 33: end tag for element "EM" which is not open
    stuff typed

because (I assume) it did not parse the opening EM tag on the very same line, because it was not expecting it to be there, because it is in a STYLE block and therefore should not be HTML content.
However a subsequent validator rule did parse the closing tag and so the error is thrown. A more useful error message would be "HTML elements are not valid children of a STYLE element".
But, because of your DOCTYPE:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

...you are checking against a very old version of the validation rules, and therefore probably an old version of the validator. You probably should be using an HTML5 doctype like this instead:
<!DOCTYPE html>
And with that DOCTYPE, you get a much more useful error message:
Error: CSS: Parse Error.

From line 35, column 21; to line 36, column 1

A: You have a couple issues with your CSS.
You have HTML in your CSS, remove stuff typed  .  You are also missing a semicolon after strong em {font-size: .9em.
Replace your CSS with the below.


text:
Q: python boto 'NoneType' object has no attribute 'stop_isntances' i am learning python boto module and i am trying to stop a running instance .
import boto.ec2
conn = boto.ec2.connect_to_region("us-west-2")
conn.stop_instances(instance_ids=['i-0aa5ce441ef7e0e2a'])

but i am getting  error which says:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'stop_instances'

i gave AWS_access keys for boto.
can anyone please help me to fix this error ?

A: As @kindall points out, your conn object is not initialized (it's NoneType). I also see that you're using boto in the example, but I thought that I would provide an example of this using boto3:
import boto3

boto3_session = boto3.Session(profile=some_profile_you_configured)
boto3_client = boto3_session.client('ec2', region_name='us-west-2')

response = boto3_client.stop_instances(InstanceIds=['i-0aa5ce441ef7e0e2a'])


text:
Q: How do you save a Tensorflow dataset to a file? There are at least two more questions like this on SO but not a single one has been answered.
I have a dataset of the form:
<TensorSliceDataset shapes: ((512,), (512,), (512,), ()), types: (tf.int32, tf.int32, tf.int32, tf.int32)>

and another of the form:
<BatchDataset shapes: ((None, 512), (None, 512), (None, 512), (None,)), types: (tf.int32, tf.int32, tf.int32, tf.int32)>

I have looked and looked but I can't find the code to save these datasets to files that can be loaded later. The closest I got was this page in the TensorFlow docs, which suggests serializing the tensors using tf.io.serialize_tensor and then writing them to a file using tf.data.experimental.TFRecordWriter.
However, when I tried this using the code:
dataset.map(tf.io.serialize_tensor)
writer = tf.data.experimental.TFRecordWriter('mydata.tfrecord')
writer.write(dataset)

I get an error on the first line:

TypeError: serialize_tensor() takes from 1 to 2 positional arguments but 4 were given

How can I modify the above (or do something else) to accomplish my goal?

A: TFRecordWriter seems to be the most convenient option, but unfortunately it can only write datasets with a single tensor per element. Here are a couple of workarounds you can use. First, since all your tensors have the same type and similar shape, you can concatenate them all into one, and split them back later on load:
import tensorflow as tf

# Write
a = tf.zeros((100, 512), tf.int32)
ds = tf.data.Dataset.from_tensor_slices((a, a, a, a[:, 0]))
print(ds)
# <TensorSliceDataset shapes: ((512,), (512,), (512,), ()), types: (tf.int32, tf.int32, tf.int32, tf.int32)>
def write_map_fn(x1, x2, x3, x4):
    return tf.io.serialize_tensor(tf.concat([x1, x2, x3, tf.expand_dims(x4, -1)], -1))
ds = ds.map(write_map_fn)
writer = tf.data.experimental.TFRecordWriter('mydata.tfrecord')
writer.write(ds)

# Read
def read_map_fn(x):
    xp = tf.io.parse_tensor(x, tf.int32)
    # Optionally set shape
    xp.set_shape([1537])  # Do `xp.set_shape([None, 1537])` if using batches
    # Use `x[:, :512], ...` if using batches
    return xp[:512], xp[512:1024], xp[1024:1536], xp[-1]
ds = tf.data.TFRecordDataset('mydata.tfrecord').map(read_map_fn)
print(ds)
# <MapDataset shapes: ((512,), (512,), (512,), ()), types: (tf.int32, tf.int32, tf.int32, tf.int32)>

But, more generally, you can simply have a separate file per tensor and then read them all:
import tensorflow as tf

# Write
a = tf.zeros((100, 512), tf.int32)
ds = tf.data.Dataset.from_tensor_slices((a, a, a, a[:, 0]))
for i, _ in enumerate(ds.element_spec):
    ds_i = ds.map(lambda *args: args[i]).map(tf.io.serialize_tensor)
    writer = tf.data.experimental.TFRecordWriter(f'mydata.{i}.tfrecord')
    writer.write(ds_i)

# Read
NUM_PARTS = 4
parts = []
def read_map_fn(x):
    return tf.io.parse_tensor(x, tf.int32)
for i in range(NUM_PARTS):
    parts.append(tf.data.TFRecordDataset(f'mydata.{i}.tfrecord').map(read_map_fn))
ds = tf.data.Dataset.zip(tuple(parts))
print(ds)
# <ZipDataset shapes: (<unknown>, <unknown>, <unknown>, <unknown>), types: (tf.int32, tf.int32, tf.int32, tf.int32)>

It is possible to have the whole dataset in a single file with multiple separate tensors per element, namely as a file of TFRecords containing tf.train.Examples, but I don't know if there is a way to create those within TensorFlow, that is, without having to get the data out of the dataset into Python and then write it to the records file.

A: To add on Yoan's answer:
the tf.experimental.save() and load() API works well. You also need to MANUALLY save the ds.element_spec to disk to be able to load() later / within a different context.
Pickling works well for me:
1- Saving:
tf.data.experimental.save(
    ds, tf_data_path, compression='GZIP'
)
with open(tf_data_path + '/element_spec', 'wb') as out_:  # also save the element_spec to disk for future loading
    pickle.dump(ds.element_spec, out_)

2- For loading, you need both the folder path with the tf shards and the element_spec that we manually pickled
with open(tf_data_path + '/element_spec', 'rb') as in_:
    es = pickle.load(in_)

loaded = tf.data.experimental.load(
    tf_data_path, es, compression='GZIP'
)

A: I have been working on this issus as well and so far I have written the following util (as to be found in my repo as well)
def cache_with_tf_record(filename: Union[str, pathlib.Path]) -> Callable[[tf.data.Dataset], tf.data.TFRecordDataset]:
    """
    Similar to tf.data.Dataset.cache but writes a tf record file instead. Compared to base .cache method, it also insures that the whole
    dataset is cached
    """

    def _cache(dataset):
        if not isinstance(dataset.element_spec, dict):
            raise ValueError(f"dataset.element_spec should be a dict but is {type(dataset.element_spec)} instead")
        Path(filename).parent.mkdir(parents=True, exist_ok=True)
        with tf.io.TFRecordWriter(str(filename)) as writer:
            for sample in dataset.map(transform(**{name: tf.io.serialize_tensor for name in dataset.element_spec.keys()})):
                writer.write(
                    tf.train.Example(
                        features=tf.train.Features(
                            feature={
                                key: tf.train.Feature(bytes_list=tf.train.BytesList(value=[value.numpy()]))
                                for key, value in sample.items()
                            }
                        )
                    ).SerializeToString()
                )
        return (
            tf.data.TFRecordDataset(str(filename), num_parallel_reads=tf.data.experimental.AUTOTUNE)
            .map(
                partial(
                    tf.io.parse_single_example,
                    features={name: tf.io.FixedLenFeature((), tf.string) for name in dataset.element_spec.keys()},
                ),
                num_parallel_calls=tf.data.experimental.AUTOTUNE,
            )
            .map(
                transform(
                    **{name: partial(tf.io.parse_tensor, out_type=spec.dtype) for name, spec in dataset.element_spec.items()}
                )
            )
            .map(
                transform(**{name: partial(tf.ensure_shape, shape=spec.shape) for name, spec in dataset.element_spec.items()})
            )
        )

    return _cache

With this util, I can do:
dataset.apply(cache_with_tf_record("filename")).map(...)

and also load directly the dataset for later use with only the second part of the util.
I am still working on it so it may change later on, especially to serialize with the correct types instead of all bytes to save space (I guess).

A: Tensorflow 2.10 moved the save method from tf.data.experimental to tf.data.Dataset.  Used with the load method, this is the easiest way to, well, save and load a model.
Tensorflow 2.6 introduced the snapshot method (previously an "experimental" feature).  Tensorflow RFC-193 goes into detail on the motivation and details of the feature.
From the docs:

The snapshot API allows users to transparently persist the output of their preprocessing pipeline to disk, and materialize the pre-processed data on a different training run.
This API enables repeated preprocessing steps to be consolidated, and allows re-use of already processed data, trading off disk storage and network bandwidth for freeing up more valuable CPU resources and accelerator compute time.

A: An incident was open on GitHUb and it appears there's a new feature available in TF 2.3 to write to disk :
https://www.tensorflow.org/api_docs/python/tf/data/experimental/save
https://www.tensorflow.org/api_docs/python/tf/data/experimental/load
I haven't tested this features yet but it seems to be doing what you want.

A: You can use tf.data.experimental.save and  tf.data.experimental.load like this:
Code to save it:
tf_dataset = get_dataset()    # returns a tf.data.Dataset() file
tf.data.experimental.save(dataset=tf_dataset, path="path/to/desired/save/file_name")
with open("path/to/desired/save/file_name" + ".pickle")), 'wb') as file:
    pickle.dump(tf_dataset.element_spec, file)   # I need this for opening it later

Code to open:
element_spec = pickle.load("path/to/desired/save/file_name" + ".pickle", 'rb'))
tensor_data = tf.data.experimental.load("path/to/desired/save/file_name", element_spec=element_spec)


text:
Q: Getting elements from xml and storing it in array using shell script I have my xml like :
<URLS xmlns:"http://www.example.com">
    <Service>
        <forwardUrl>
            <value>http://www.example1.com:80</value>
            <value>http://www.example2.com:80</value>
            .
            .
            .
       </forwardUrl>
    </Service>
</URLS>

I want to store all the forward urls in an array.
I tried doing this :
let urlcount=$(sed -e "s/xmlns/ignore/" /tmp/in.xml | xmllint --xpath "count(//forwardUrl/value)"  -)
declare -a urls=()

for((i=1; i <= $urlcount; i++)); do
    echo $i
    urls[$i]=$(sed -e "s/xmlns/ignore/" /tmp/in.xml | xmllint --xpath '//forwardUrl/value["$i"]/text()' -)
done

But when I do echo ${urls[7]}, it prints all the values.
I want to store different urls in different indexes. Please help me with this.

A: try this
$ urls=($(sed -nr 's_<value>(.*)</value>_\1_p' file)); echo ${urls[1]}
http://www.example2.com:80
$ echo ${urls[0]}
http://www.example1.com:80

obviously doesn't care about the xml structure so assumes "value" tag is used only for urls.
UPDATE: if the context is important awk to the rescue!
$ awk -F'[<>]' -v RS="</?forwardUrl>" 'NR==2{for(i=3;i<=NF;i+=4) print $i}' file

http://www.example1.com:80
http://www.example2.com:80

the rest is the same
$ urls=($(awk ... ))

note that this regex RS is gawk specific and may not be supported in other awks.

A: How about something like this using only sed:
$ cat file1
<URLS xmlns:"http://www.example.com">
    <Service>
        <forwardUrl>
            <value>http://www.example1.com:80</value>
            <value>http://www.example2.com:80</value>
            <value>http://www.example3.com:80</value>
            <value>http://www.example4.com:80</value>
       </forwardUrl>
    </Service>
</URLS>
$ declare -a array=($(sed -n '/\s*<forwardUrl>/,/<\/forwardUrl>/p' file1 | sed -e 's/<[^>]*>//g' -e '/^\s*$/d' -e 's/\s*//g'))
$ echo "${array[0]}"
http://www.example1.com:80
$ echo "${array[1]}"
http://www.example2.com:80
$ echo "${array[2]}"
http://www.example3.com:80
$ echo "${array[3]}"
http://www.example4.com:80
$ echo "${array[@]}"
http://www.example1.com:80 http://www.example2.com:80 http://www.example3.com:80 http://www.example4.com:80
$

Expression breakdown:
declare -a array=($(sed -n '/\s*<forwardUrl>/,/<\/forwardUrl>/p' file1 | sed -e 's/<[^>]*>//g' -e '/^\s*$/d' -e 's/\s*//g'))

*

*sed -n '/\s*<forwardUrl>/,/<\/forwardUrl>/p' file1 to print lines in between lines that match <forwardUrl> and at </forwardUrl>(both inclusive)

*sed -e 's/<[^>]*>//g' -e '/^\s*$/d' -e 's/\s*//g' 1st expression deletes all tags, 2nd deletes all empty lines(having spaces) and last expression just removes all spaces

Edit 1:
$ cat file1
<URLS xmlns:"http://www.example.com">
    <Service>
        <forwardUrl>
            <value>http://www.sun.com:80</value>
            <value>http://www.example2.com:80</value>
            <value>http://www.example3.com:80</value>
            <value>http://www.example4.com:80</value>
       </forwardUrl>
    </Service>
</URLS>
$ declare -a array=($(sed -n '/\s*<forwardUrl>/,/<\/forwardUrl>/p' file1 | sed -e 's/<[^>]*>//g' -e '/^\s*$/d' -e 's/\s*//g'))
$ echo "${array[0]}"
http://www.sun.com:80
$ echo "${array[@]}"
http://www.sun.com:80 http://www.example2.com:80 http://www.example3.com:80 http://www.example4.com:80
$


text:
Q: Error in recoding function from package epicalc I am trying to use recode function for demarcation of value in a variable but am not able to do so with a specific variable only where as it is working fine for another variable.
recode(age, age > 60, NA)

Error in recode.default(age, age > 60, NA) : object '.data' not found

What to do?

A: I think you could just do
age[age>60] <- NA

Note that epicalc is somewhat obsolete .... It looks like epicalc operates by default on a data frame called .data, which could make things difficult ...


text:
Q: Eclipse compareEditor showing change line by line I am using the following code to show the difference between two input in String format
protected Object prepareInput(IProgressMonitor monitor)
        throws InvocationTargetException, InterruptedException {

    CompareItem left = new CompareItem(text1);
    CompareItem right = new CompareItem(text2);
    diffNode= new DiffNode(left, right);
    return diffNode;
}

For input like
line1          testline
line2          line1
line3          line2
               line3

it's showing all lines are different, instead of showing only first line is different.
The way I am calling compare editor is by
CompareUI.openCompareDialog(new MyCompare(configuration, ((MyEditor)
    editorPart).originalText(), ((MyEditor) editorPart).currentConverted()) );

Thanks for any help.

A: This :
CompareConfiguration configuration = new CompareConfiguration();
CompareUI.openCompareDialog(new CompareEditorInput(configuration) {
    @Override
    protected Object prepareInput(final IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
        String text1 = "line1\nline2\nline3\n";
        String text2 = "testline\nline1\nline2\nline3\n";

        CompareItem left = new CompareItem("1", text1);
        CompareItem right = new CompareItem("2", text2);
        DiffNode diffNode = new DiffNode(left, right);
        return diffNode;
    }
});

Works perfectly for me on Kepler.

So I thinks you're not giving us enough data.

A: Maybe you should notice this parameter "Differencer.CHANGE"
CompareEditorInput input = new CompareEditorInput(config) {
    StringCompareItem left = new StringCompareItem("left", leftContent);
    StringCompareItem right = new StringCompareItem("right", rightContent);

    @Override
    protected Object prepareInput(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
        return new DiffNode(null, Differencer.CHANGE, null, left, right);
    }

};


text:
Q: tabItem in shinydashboard not updating I am new to shinydashboards and trying to get my UI
I have two tabs but the content of both are visible when i run the tab and the content in the body does not change when switching between tabs...
This is a "textbook" example, so I am totally puzzled... i am counting all my brackets which I see is the common issue ... I am stuck!
This is my ui.r and nothing i have the default server.r
library(shiny)
library(shinydashboard)

#--------
#--------
#individual components

#--------
#sidebar

sidebar<-dashboardSidebar(
  sidebarMenu(
    menuItem("1", tabName="Item1"),
    menuItem("2", tabName="Item2")

  )#sidebarMenu
)#dashboardSidebar

#--------

#body

body<- dashboardBody(
  tabItem(tabName='Item1',
          h2("item1 content")
          ),#tabItem

  tabItem(tabName="Item2",
          h2("item2 content")
          )#tabItem

)#dashboardBody

#--------
#--------
#MAIN

# Define UI for application
shinyUI(

dashboardPage
(
  dashboardHeader(title="hi there"),
  sidebar,
  body

) #dashboardPage

) #shinyUI

A: and mm... stupid me missing.. tabItems
body<- dashboardBody(
  tabItems( #THIS!!!
  tabItem(tabName='Item1',
          h2("item1 content")
          ),#tabItem

  tabItem(tabName="Item2",
          h2("item2 content")
          )#tabItem

  )#tabItems <- THIS!!!

)#dashboardBody

#--------
#--------
#MAIN

# Define UI for application
shinyUI(

dashboardPage
(
  dashboardHeader(title="hi there"),
  sidebar,
  body

) #dashboardPage

) #shinyUI


text:
Q: Can't change properties of ControlTemplate at runtime I have a custom 3 state Button that is supposed to cycle between 3 different states (colours) as it is clicked.  However the click handler I've written doesn't have any effect on the background colour of the Border within the ControlTemplate.
I'm probably missing something very simple, but I'd really appreciate a fresh pair of eyes to spot what it may be.
The ControlTemplate and Button.Click handler are below:
<Style x:Key="FilterButtonStyle"  TargetType="{x:Type local:FilterButton}"
           BasedOn="{StaticResource {x:Type Button}}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Border x:Name="ButtonBackground" BorderThickness="0" Padding="0"
                    Margin="0" CornerRadius="6"
                    Background="{StaticResource blueShader}" >
                    <ContentPresenter HorizontalAlignment="Center"
                        VerticalAlignment="Center"/>
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Effect" Value="{StaticResource glowShadow}">
                        </Setter>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Setter Property="Foreground" Value="{StaticResource textBrush}"/>
    <Setter Property="Margin" Value="4,4,0,4"></Setter>
    <Setter Property="Padding" Value="4"></Setter>
    <Setter Property="Height" Value="55"></Setter>
    <Setter Property="Width" Value="55"></Setter>
    <Setter Property="FontSize" Value="10"/>
    <Setter Property="FontWeight" Value="Normal"/>
    <Setter Property="TextBlock.TextWrapping" Value="Wrap"></Setter>
    <Setter Property="HasDisabledState" Value="True"></Setter>
    <Setter Property="OnColour" Value="{StaticResource greenShader}"></Setter>
    <Setter Property="OffColour" Value="{StaticResource blueShader}"></Setter>
    <Setter Property="DisabledColour" Value="{StaticResource redShader}"></Setter>
</Style>

private void FilterButton_Click(object sender, RoutedEventArgs e)
{
    if (!this.CanChangeState) { return; }

    // Get child border element.
    Border border = this.Template.LoadContent() as Border;

    // Cycle through button states.
    switch (this.ButtonState)
    {
        case ButtonStates.Off:
            this.ButtonState = ButtonStates.On;
            border.Background = this.OnColour;
            break;

        case ButtonStates.On:
            if (this.HasDisabledState)
            {
                this.ButtonState = ButtonStates.Disabled;
                border.Background = this.DisabledColour;
            }
            else
            {
                this.ButtonState = ButtonStates.Off;
                border.Background = this.OffColour;
            }
            break;

        case ButtonStates.Disabled:
            this.ButtonState = ButtonStates.Off;
            border.Background = this.OffColour;
            break;
    }
}

A: Never mind, I found that a better way of handling this was to use ControlTemplate triggers to change the Button colour based on the ButtonState property.
    <Style x:Key="FilterButtonStyle"  TargetType="{x:Type local:FilterButton}"
       BasedOn="{StaticResource {x:Type Button}}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Border x:Name="ButtonBackground" BorderThickness="0" Padding="0" Margin="0" CornerRadius="6"
                    Background="{StaticResource blueShader}" >
                    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Effect" Value="{StaticResource glowShadow}">
                        </Setter>
                    </Trigger>
                    <Trigger Property="local:FilterButton.ButtonState" Value="On">
                        <Setter TargetName="ButtonBackground" Property="Background" Value="{StaticResource greenShader}"></Setter>
                    </Trigger>
                    <Trigger Property="local:FilterButton.ButtonState" Value="Off">
                        <Setter TargetName="ButtonBackground" Property="Background" Value="{StaticResource blueShader}"></Setter>
                    </Trigger>
                    <Trigger Property="local:FilterButton.ButtonState" Value="Disabled">
                        <Setter TargetName="ButtonBackground" Property="Background" Value="{StaticResource redShader}"></Setter>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Setter Property="Foreground" Value="{StaticResource textBrush}"/>
    <Setter Property="Margin" Value="4,4,0,4"></Setter>
    <Setter Property="Padding" Value="4"></Setter>
    <Setter Property="Height" Value="55"></Setter>
    <Setter Property="Width" Value="55"></Setter>
    <Setter Property="FontSize" Value="10"/>
    <Setter Property="FontWeight" Value="Normal"/>
    <Setter Property="TextBlock.TextWrapping" Value="Wrap"></Setter>
    <Setter Property="HasDisabledState" Value="True"></Setter>
</Style>


text:
Q: call API in IBM Data Science Experience from Postman I am calling the API generated after deploying the model in IBM data science Experience.
But while I am calling the API using POST then it is giving error "Authentication failed".
Now problem is, I have used the credentials available in service of IBM Watson machine learning as the model does not provide any credential as such.
Can some one please help me how to proceed in this case?

A: You need to generate a token using your Watson ML Service credentials and use that token when POSTing to your score URL. You can generate a token like so (note: username, password, and service_path are in your Watson ML Service credentials):
import urllib3, requests, json

headers = urllib3.util.make_headers(basic_auth='{}:{}'.format(username, password))
url = '{}/v3/identity/token'.format(service_path)
response = requests.get(url, headers=headers)
mltoken = json.loads(response.text).get('token')

When you hit your scoring URL you need to use this token as the Authorization header:
header = {'Authorization': 'Bearer ' + mltoken}

There is an example in the docs under Reference / Sample notebooks @ https://console.bluemix.net/docs/services/PredictiveModeling/index.html#WMLgettingstarted


text:
Q: ScriptControl seems to block UI thread I'm currently writing an application in C# and would like to allow external VB scripts to manipulate the WPF based GUI of the application in some way. Those scripts should be allowed to run very long and to pause the thread they are running in (it's a little slide-show like application where the VBScripts determine the content of the view at runtime). To accomplish this, I referenced the ScriptControl COM component and made my classes ComVisible. The selected script will be executed by a ScriptingHost like this:
public void Run(Action callback)
{
  var thread = new Thread(() =>
  {
    _ScriptControl.Run("Execute", new object[] { }); // _ScriptControl is the COM component
    callback();
  });
  thread.Start();
}

To display an image in my application, I use the following method in my view model (invoked from VBScript):
public void ShowPicture(string path)
{
  BitmapImage bmImage = new BitmapImage();

  bmImage.BeginInit();
  bmImage.UriSource = new Uri(path, UriKind.Absolute);
  bmImage.EndInit();

  bmImage.Freeze();

  _CurrentImage = bmImage;

  RaisePropertyChanged("CurrentImage");

  // System.Windows.Forms.Application.DoEvents();
}

The property CurrentImage returns the newly created BitmapImage (_CurrentImage) and is bound to an image control on my view.
When I run a script which will pause the scripting thread (to give the user some time to watch the picture) with Thread.Sleep(), the image control will still fetch the CurrentImage property after the event has been raised, but the picture will not be displayed. If I add a DoEvents call or a MessageBox.Show somewhere, the GUI will update properly.
I tried to display an image invoking the ShowPicture method in a seperate thread followed by a Thread.Sleep() and this works well (without the ScriptControl COM component).
Does the ScriptControl COM component use the UI thread in some way (I already set AllowUI to false) or is there some other mysterious COM stuff going on?
Example script:
Function Execute()
    For Each picture In Source.GetPictures(False)
        Canvas.ShowPicture(picture)
        Host.Wait(5) ' Thread.Sleep(5000)
    Next
End Function


text:
Q: Jing video continuous play I have downloaded Jing video capture tool and captured a video of an application.
It creates a swf video file.
Our requirement is to allow the video to play continuously.
Please let me know how to achieve this.
Thanks
vish

A: What do you mean by continuous play? If you mean continuous recording, I'd try Camtasia out.


text:
Q: Installing Windows 7, UBuntu 12.04 and Fedora 18 (19) in triple boot with SWAP and Files space in HDD I'm new... but, i want you to help me...
I want a Triple-boot, Windows 7, Ubuntu 12.04 and Fedora 18.. or 19...and i found this post (question...(?)
How do I triple-boot Ubuntu, Fedora and Windows 7?
and it is great, BUT i think it would be better if i dedicate some space to the SWAP... I have a 1TB HDD...so, here is my plan:
I want 200GB for Windows 7, another 200GB for Ubuntu 12.04, other 200GB for Fedora 18 (or 19, whichever is more stable) AND the other 400GB -pay attention- to use as my files space... i mean, use those 400GB to save my files, music, images and so i can use them in any of the 3 O.S. do you follow me?... so, when i play games in Windows i can see my photos of the last Christmas, and when i'm working on Ubuntu y can see the SAME photos of the last Christmas, and when experimenting with fedora (18 or 19 lol) i can see the SAME photos of the last Christmas.
BUT i want to tell me that if it is a good idea to give some space to the SWAP... i read in the same link (How do I triple-boot Ubuntu, Fedora and Windows 7?) at the end that it is possible to have the SAME swap for Ubuntu and Fedora, but i don't really understand because i understood that it is convenient to have the DOUBLE SWAP space of your RAM memory, i mean, i have 4 GB of RAM, so, it is recommendable to have 8GB in SWAP...
So, are 2 things:
1 - The partition of my HDD to work fine with the 3 O.S and the space for my files.
2 – The specifications for the SWAP memory...
I want to accentuate that the space its not a problem, remember that i have a 1TB HDD, so i can give a lot to the SWAP, but i don't really know how much it is correct, maybe if i give it a lot of space it would be an error and the system(s) crash... i dunno.
So, please help me... i'm very eager to install them.. ALL THE 3 S.O.

A: the 400gb partition you want use, format it as ntfs only and add mount entries of that partition in /etc/fstab of both ubuntu and fedora . assuming 400gb partition no as 5
/dev/sda5   /home/username/pictures   ntfs   defaults  0 0 (you can change mountpt as you want)
swap should be twice of ram if ram is less than 4gb if greater than 4gb then swap space 4gb is enough


text:
Q: Probability with $2$ colored balls and one box: $1/3$ or $1/4$? We have $2$ balls in a box, each of them can be either black or white.
What is the probability that both balls are black?
$1\over 3$ or $1\over 4$?

$1\over 3$ because :
we have $3$ nonrecurring cases:
1) white white (ww)
2) white black (wb)
3) black black (bb)
So, it's $1\over 3$

A: $\frac{1}{4}$ as there are 4 cases: WW, WB, BW, BB where each is equally likely.
If necessary, consider adding extra balls and see if your theory would hold. If there were 4 balls, are there 16 cases or just 5? I see 16 as each ball could be either colour while you'd claim that order doesn't matter really.
4 color case where order doesn't matter: WWWW, WWWB, WWBB, WBBB, BBBB (This is your 5 case scenario.)
4 color cases where order matters:
WWWW
WWWB, WWBW, WBWW, BWWW
WWBB, WBWB, BWBW, WBBW, BWWB, BBWW
BBBW, BBWB, BWBB, WBBB
BBBB

A:
Emil Terman

I don't know, people say that there is no difference between BW and WB, they mean that the order doesn't matter.

Yeah, this is a source of much confusion among new students.
When we say "order doesn't matter" what we actually mean is "some of these outcomes are indistinguishable except by order so we consider them to be the same event".   In this case, two balls are placed in a box where they roll around so that we can not tell which was placed in first.

"When one ball is black and one is white, we can't tell which is first, so we say order doesn't matter."

What we don't mean by "order doesn't matter" is that these distinct events are a set of equally probable outcomes.   $\{\textsf{Both White}, \textsf{Both Black}, \textsf{Different coloured}\}$ is a set of three distinct outcomes, because "order doesn't matter", but these distinct outcomes are not equally probable.   That is important.
To measure probability as a ratio of counts of distinct outcomes (favoured versus total) we need all of the distinct outcomes to have be equally probable (ie: to have the same probability weighting).
We actually have the partitioned set: $\{\{WW\}, \{BB\}, \{BW, WB\}\}$.   This model helps us obtain a more meaningful measure of probability.

too long/didn't read: Sometimes "order doesn't matter" for identifying distinct events, but it still often does matter for weighing probabilities.


text:
Q: iOS Emulator for Windows Is there any iOS emulator for Windows? I need one instead of the buying a macbook, just for that.I would like my tester to use it instead of buying a macbook.
Sorry for the noob question.

A: Hackintosh will help you :)
However if you are going to do programming on iOS/Mac: buy Mac ;)
http://www.hackintosh.com

A: Nope, the only official way is to buy an Mac for development. There's a thing called hackintosh, but I do not recommend installing software without licence for using it. Piracy is bad. Buy a Mac.


text:
Q: Express App using PassportJS and dynamoDB locates to login page without error I have a problem regarding my Express Login App. The whole app runs so far and i get the login page. This is not a dynamodb query problem. I posted my login.js file below and can add more files if needed. The problem is that i don't get any errors which could help me debugging. It "should" log errors to the console which it does not so i really can't figure out where the problem might be. Thanks for your help!  This is the login.js file:
const LocalStrategy = require("passport-local").Strategy;
const User = require("../models/user");
const bCrypt = require("bcrypt-nodejs");

const AWS = require("aws-sdk");
const dynamodb = new AWS.DynamoDB({
  apiVersion: "2012-08-10",
  //testing purposes
   "region": "us-west-2",
  "accessKeyId": "abcde",
  "secretAccessKey": "abcde",
  "endpoint": "http://localhost:8001"
});

module.exports = function(passport) {

  passport.use("login", new LocalStrategy({
      passReqToCallback: true
    },
    function(req,username,password,done) {
      var queryParams = {
    TableName: "users",
    KeyConditionExpression: "username = :user",
    ExpressionAttributeValues: {
      //username entered in jade form
      ":user":{"S": username}
           }
      };
      //querying dynamodb for username
      dynamodb.query(queryParams,
    function(err,data) {
      if(err)
        console.error(err,err.stack);
        return done(err);

      //if no users with said username in db
      if(data.Count < 1) {
        console.error(username + " not found in db");
        return done(null, false, req.flash("message" , "user not found"));
      }
      //too many entries (admin's fault)
      if(data.Count > 1){
        console.error("error, more than one user with " + username + " in db");
        return done(null,false,req.flash("message", "more than version of the username in the db"));
      } else {
        //only one user exists in db, query for username was successful
        data.Items.forEach(function(item){
        //checking if entered password is wrong
        if(!isValidPassword(item.username, item.password)) {
        console.error("invalid username - password combination");
        return done(null,false,req.flash("message","invalid user-password combination"));
      }
      //successful login - user and password match
      console.log("login successful");
      return done(null,user);
      });
     }
    });
  }
));

  var isValidPassword = function(user, password) {
    return bCrypt.compareSync(password,user.password);
  }
}

A: This looks like it's missing some brackets:
if(err)
  console.error(err,err.stack);
  return done(err);

I assume it needs to be:
if (err) {
  console.error(err,err.stack);
  return done(err);
}


text:
Q: Dynamic Images for email such as countdown clocks (in light of gmail image caching) What I am trying to do: A dynamic countdown clock in the body of an email
What is causing me pain: Google's decision to cache images for users of the gmail client
I implemented an email countdown clock for my company last November using this technique:
Countdown Timer Image GIF in Email
Worked like a charm, however in December, a major monkey wrench was thrown by Google when they decided to cache all images for people using Gmail clients.
http://kickdynamic.com/update-on-the-gmail-image-change/
So the problem affects all people on gmail clients that open an email a second time. They will see a cached image. For something like a countdown clock, this would cause a lot of harm.
Admittedly this is somewhat of a blind distress call, but has anyone figured out how to do a email countdown clock that is unaffected by google's image caching?

A: I had the same problem. So with the following headers, I disabled image caching and it works in Gmail too (therefore Gmail Image Proxy respects the cache headers):
header('Content-Type: image/jpeg');
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

Credits to this library note.


text:
Q: Refactor javascript code more elegantly, not using nested ternary expression or let I have this simplified code, quite simple:
export const OwnRedirect = () => {
  const { pipelineType, ticketId, productId } = useParams<{
    pipelineType?: string;
    ticketId?: string;
    productId?: string;
  }>();
  let path = '';
  if (pipelineType) {
    path = `/pipeline/${pipelineType}`;
  } else if (ticketId) {
    path = `/ticket/${ticketId}`;
  } else if (productId) {
    path = `/product/${productId}`;
  } else {
    path = '/pipeline/local';
  }
  return <Redirect to={path}/>;
};

But I found it not readable enough. Anybody has an idea how to refactor this code not using if or switch or let or nested ternary operator?

A: To make it easier to read, you can take advantage of short-circuit evaluation with && and ||. To make things cleaner and easier to test, I also like creating really small functions that only do one thing, but do it well. It avoids mixing logic (which path to choose) and functionality (building those paths):
export const OwnRedirect = () => {
  const { pipelineType, ticketId, productId } = useParams<{
    pipelineType?: string;
    ticketId?: string;
    productId?: string;
  }>();

  const path = (
    (pipelineType && buildPipelinePath(pipelineType)) ||
    (ticketId     && buildTicketPath(ticketId)      ) ||
    (productId    && buildProductPath(productId)    ) ||
    `/pipeline/local`
  );

  return <Redirect to={path} />;
};

function buildPipelinePath(pipelineType) {
  return `/pipeline/${Number(pipelineType) === 1 ? 'local' : 'global'}`;
}

function buildTicketPath(ticketId) {
  return `/ticket/${ticketId}`;
}

function buildProductPath(productId) {
  return `/product/${productId}`;
}

A: sometimes just separating it into a function
helps with readability.
const toUrl = ({ pipelineType = '', ticketId = '', productId = '' }) => {
  if (pipelineType) {
    return `/pipeline/${pipelineType}`;
  }

  if (ticketId) {
    return `/ticket/${ticketId}`;
  }

  if (productId) {
    return `/product/${productId}`;
  }

  return '/pipeline/local';
}

export const OwnRedirect = () => {
  const params = useParams<{
    pipelineType?: string;
    ticketId?: string;
    productId?: string;
  }>();

  return <Redirect to={toUrl(params)}/>;
};

A: You may use a tagged sum. For example:

// Generic functions
// B is the function compose combinator
const B = g => f => x => g (f (x))

const taggedSum = xs => Object.fromEntries (
  xs.map(tag => [tag, value => ({ tag, value })])
)

const cata = matches => ({ tag, value }) => matches[tag] (value)
/////////////////////////

const Kind = taggedSum (['pipeline', 'ticket', 'product', 'local' ])

const path = cata ({
    pipeline: x => `/pipeline/${x}`,
    ticket: x => `/ticket/${x}`,
    product: x => `/product/${x}`,
    local: () => `/pipeline/local`
})

const output1 = B (path) (Kind.pipeline) (1)
const output2 = B (path) (Kind.ticket) (14)
const output3 = B (path) (Kind.product) (3421)
const output4 = B (path) (Kind.local) (0)

console.log ('pipeline:', output1)
console.log ('ticket:', output2)
console.log ('product:', output3)
console.log ('local:', output4)


text:
Q: Using XPath to get an element in SVG I am trying to get an element in an SVG file using XPath. I have tried the following code, but singleNodeValue is null. The doc seems to be correct, so I guess either evaluate() arguments or the XPath is wrong, but I cannot find anything wrong. Why doesn't it work?
JavaScript
fetch('test.svg')
.then(response => response.text())
.then(data=>{
    const parser = new DOMParser();
    const doc = parser.parseFromString(data, "text/xml");
    console.log(doc);
    const res = doc.evaluate("//symbol[@label='square']", doc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
    console.log(res.singleNodeValue);
})

SVG
<?xml version="1.0" encoding="UTF-8" standalone="no"?>

<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">

    <symbol label ="square">
        <rect y="5" x="5" width="90" height="90" stroke-width="5" stroke="#f00" fill="#f00" fill-opacity="0.5" />
    </symbol>

</svg>

After some testing, I have discovered that it works if I remove xmlns="http://www.w3.org/2000/svg". I searched the web and found an answer: Why XPath does not work with xmlns attribute

A:

var data = '<?xml version="1.0" encoding="UTF-8" standalone="no"?><svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"><symbol label ="square"><rect y="5" x="5" width="90" height="90" stroke-width="5" stroke="#f00" fill="#f00" fill-opacity="0.5" /></symbol></svg>';
const parser = new DOMParser();
const doc = parser.parseFromString(data, "text/xml");

const res = doc.querySelector("symbol[label=square]");
console.log(res);

A: You can make use of a namespace resolver in XPath 1 and with the evaluate function and even of an XPath default namespace in XPath 2 and later such as supported by Saxon-JS 2:

const svgString = `<?xml version="1.0" encoding="UTF-8" standalone="no"?>

<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"
    xmlns:dog = "http://dog.com/dog">

    <symbol dog:label="square">
        <rect y="5" x="5" width="90" height="90" stroke-width="5" stroke="#f00" fill="#f00" fill-opacity="0.5" />
    </symbol>
    <symbol dog:label="cat">
        <rect y="5" x="5" width="90" height="90" stroke-width="5" stroke="#f00" fill="#f00" fill-opacity="0.5" />
    </symbol>
</svg>`;

const doc = new DOMParser().parseFromString(svgString, 'application/xml');

const result = doc.evaluate(`//svg:symbol[@dog:label='cat']`, doc, function(prefix) { if (prefix === 'svg') return 'http://www.w3.org/2000/svg'; else if (prefix === 'dog') return 'http://dog.com/dog'; else return null; }, XPathResult.FIRST_ORDERED_NODE_TYPE, null);

console.log(result.singleNodeValue);

const result2 = SaxonJS.XPath.evaluate(`//symbol[@dog:label = 'cat']`, doc, { xpathDefaultNamespace : 'http://www.w3.org/2000/svg', namespaceContext : { 'dog' : 'http://dog.com/dog' } });

console.log(result2);
<script src="https://www.saxonica.com/saxon-js/documentation/SaxonJS/SaxonJS2.rt.js"></script>


text:
Q: MySQL select from 2 tables and replace value There are my 2 tables: (Only the columns that interest us)
Table1:
   ID   |  NAME
________|_______
   0    |  null
   1    |  Fire
   2    |  Rock
Table2:
   ID   |  NAME  |  TYPE  |  TYPE2
________|________|________|_________
   1    |  El1   |   1    |    0
   2    |  El2   |   2    |    1

So, my table2 contains some elements, and they can have 2 types that match the id of the first table
For example:

*

*El1 is Fire only

*El2 is Rock + Fire

And I need a request that select ID, NAME, TYPE, TYPE2 but replace TYPE & TYPE2 by their NAME in the Table1.
I was looking for INNER JOIN but I don't understand how must I use it for this result...
The result I would like is : (for the Table2 first row)
$el->ID // give me 1
$el->NAME // give me El1
$el->TYPE // give me Fire
$el->TYPE2 // give me null

But I have no idea how to do this and it's been 2 days I'm looking for how to do :(

A: I think you just need two inner joins here.  Each of the two joins will bring in the name from the first table, for one of the type columns in the second table.
SELECT
    t2.ID,
    t2.NAME,
    a.NAME,
    b.NAME
FROM Table2 t2
INNER JOIN Table1 a
    ON t2.TYPE = a.ID
INNER JOIN Table1 b
    ON t2.TYPE2 = b.ID;

Demo


text:
Q: Creating a user in the standard users folder using command line (Windows Server 2012) Information
Let's say that I have a server on the domain "domain.com". In the active directory, I have the OU Finance, in that OU, I have the OU Users.
If I want to create a user in this folder, using command line it would be:
dsadd user CN=user01,OU=Users,OU=Finance,DC=domain,DC=com

This is excluding the parameters of course.
Question
Every server has a "Users" folder, which contains the standard-users such as the Administrator.
How would I create a user in that standard folder, using the commandline? And how would I add that user to a group that is inside of the "Built-in" folder?
Let's say that the username would be user01 and the group "Administrators"

A: The trick is that the built-in Users folder isn't an OU, it's a "Container" (i.e. the objectClass is "container" rather than "organizationalUnit"). So the distinguished name of that container is prefixed by CN= rather than OU=.
So try this:
dsadd user CN=user01,CN=Users,DC=domain,DC=com


text:
Q: Rails: link_to and session I create simple CRUD in my web.
index.html.erb
 <% @diots.each do |diot| %>

        <%= diot.id %>
        <%= image_tag(diot.something, width: '50', height: '50') %>
        <%= link_to session[:is_checked] ? "Running" : "Stop", (session[:is_checked] ? drive_diot_path(diot) : drive_stop_diot_path(diot)) %>
        <%= link_to 'Edit', edit_diot_path(diot) %>
        <%= link_to 'Destroy', diot, method: :delete, data: { confirm: 'Are you sure?' } %>

    <% end %>

When I click one of the "Running", will go drive.html.erb, but I go back index.html.erb, they all change "Stop".
How can I do when I click one of the "Running", back index.html.erb, only the one change to "Stop"?
Thanks

A: You can do this by storing a value in the session for each diot:
session[:"is_checked#{diot.id}"]
Giving you: (Note that :"string" gives a valid symbol)
<% @diots.each do |diot| %>

     <%= diot.id %>
     <%= image_tag(diot.something, width: '50', height: '50') %>
     <%= link_to session[:"is_checked#{diot.id}"] ? "Running" : "Stop", (session[:"is_checked#{diot.id}"] ? drive_diot_path(diot) : drive_stop_diot_path(diot)) %>
     <%= link_to 'Edit', edit_diot_path(diot) %>
     <%= link_to 'Destroy', diot, method: :delete, data: { confirm: 'Are you sure?' } %>

 <% end %>


text:
Q: Accessing a Record from API Source with Power Query (Custom Connector) This is a follow up to my issue at API Pagination in JSON Body (not Header) - How to Access with Power Query in Custom Connector?
I have built a custom connector for an API that sends its pagination data back in the body of the response, rather than the header. The way to use GetNextLink using header is documented in the GitHub custom connector example:
https://github.com/microsoft/DataConnectors/blob/master/samples/Github/github.pq
GetNextLink = (response, optional request) =>
    let
        // extract the "Link" header if it exists
        link = Value.Metadata(response)[Headers][#"Link"]?,
        links = Text.Split(link, ","),
        splitLinks = List.Transform(links, each Text.Split(Text.Trim(_), ";")),
        next = List.Select(splitLinks, each Text.Trim(_{1}) = "rel=""next"""),
        first = List.First(next),
        removedBrackets = Text.Range(first{0}, 1, Text.Length(first{0}) - 2)
    in
        try removedBrackets otherwise null;

Getting to the pagination data from the body of the response should be easier than the header, I've learned. But I am stumped.  In the images, you can see the record I am trying to access that comes back through Web.Contents()

This is my code for the GetNextLink function. I am trying to get the "next" record above.
GetNextLink = (response) =>
// response is data already run through Web.Contents()

let
   Source = Lines.FromBinary(response),
   nextPage = Record.Field(Source[paging], "next")
in
   try nextPage otherwise null;

I get the error back "We cannot convert a value of type Record to type Text". I feel like I am not getting the 'Source" correctly? I could certainly use help as I am a PowerQuery newbie!
Thanks!

A: GetNextLink = (response) =>
// response is data already run through Web.Contents()
let Source = Lines.FromBinary(response),
nextpage = try Source[paging][next] otherwise null
in nextpage

or
GetNextLink = (response) =>
// response is data already run through Web.Contents()
let  Source = Lines.FromBinary(response)
nextpage = try Record.Field(Source[paging],"next") otherwise null
in nextpage


text:
Q: Bootstrap add space between columns I'm stuck with a spacing problem. Here's the code:

.border {
  border: 1px solid red;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />

.......

.......

.......

Without the border, it looks find. But add the border, and they touch one another. Looks very ugly. Adding margin-left and right doesn't help. The last column will be dumped on the next row. Compensating the margin with a negative padding doesn't work either.
I'm out of options. What do I need to do to add some space between the columns?

A: Apply your rules to the content inside the column, not the column itself/
.border {
    border: 1px solid red;
}

Content>/div>

Example:

body {
  padding-top: 60px;
}
.border {
  border: 1px solid red;
  padding: 10px;
  background-color: aliceblue;
}
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

Hello

Hello

Hello

A: Just remove right border from all element except last one for example
.border:not(:last-child) {
  border-right: none;
}

Demo


text:
Q: Vuetify autocomplete not showing dropdown when using mutiple prop I am using v-autocomplete component of vuetify and the issue I am facing here is, when I add the prop multiple to autocomplete then the dropdown doesn't show and when I remove multiple then the dropdown shows. Below is how I am implementing it. Please help me find where I am going wrong. I am using vuetify version 2.3.10 .
<v-autocomplete
 ref="office_locations"
 :items="locations"
 v-model="office.location_ids"
 label='Office Locations'
 item-text='name'
 item-value='id'
 multiple
 attach
 required>
</v-autocomplete>

Locations data is as follows.
locations: [{id: 1, name: "Toronto", label: "Toronto"},
{id: 2, name: "New York", label: "New York"},
{id: 3, name: "San Jose", label: "San Jose"},
{id: 4, name: "Vancouver", label: "Vancouver"}]

Update 1
I tried inspecting the v-autocomplete component and v-menu is empty


text:
Q: Script to uninstall a folder from within C:\ProgramData\folder (GUID) I'm hoping to find a script to uninstall a folder from within the ProgramData folder ie.. C:\ProgramData\folder (GUID). As you can see the folder also has a GUID string this is what I have:
rmdir /s /q "%programdata%\Folder (asterisk)

I've tried a wildcard like this.. (*), I've searched Google.. but I'm guessing my search is not phrased correctly as I cannot find a solution for the removal of the folder with the GUID string included. Any help would be greatly appreciated.
Most of the machines this is for will be Windows 7 Pro x86/x64 and a few Vista same flavors.


text:
Q: Code not deleteing all record from multiple tables I created a delete.php where I want to delete records from three tables called person, address and cv... By getting their ID I want to delete their records how ever the code only deletes all records from the person table and not from address and CV.
<?php
$servername = "localhost";
$username = "root";
$password = "usbw";
$dbname = "persons";

// CREATE A CONNECTION WITH THE DATABASE
// CONNECTIE MAKEN MET DATABASE
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// GET ID FROM person_id
// PAK ID VAN person_id
$person_id = (isset($_GET['person_id']) ? $_GET['person_id'] : null);

// CREATE PREPARE STATMENT FOR DELETING RECORDS FROM person_id
// MAAK EEN STATEMENT OM WAARDES TE VERWIJDEREN VAN person_id
$stmt = $conn->prepare('DELETE FROM `person` WHERE person_id = ?');
$stmt->bind_param('s', $person_id);

// EXECUTE STATEMENT AND IF RESULT IS FALSE SHOW ERROR
// VOER STATEMENT UIT EN ALS VALS IS GEEF ERROR AAN
$result = $stmt->execute();
if ($result === FALSE) {
    die("Error: " . $stmt->error);
}

$address_id = (isset($_GET['address_id']) ? $_GET['address_id'] : null);

$stmt = $conn->prepare('DELETE FROM `address` WHERE address_id = ?');
$stmt->bind_param('s', $address_id);

// EXECUTE STATEMENT AND IF RESULT IS FALSE SHOW ERROR
// VOER STATEMENT UIT EN ALS VALS IS GEEF ERROR AAN
$result = $stmt->execute();
if ($result === FALSE) {
    die("Error: " . $stmt->error);
}

$cv_id = (isset($_GET['cv_id']) ? $_GET['cv_id'] : null);

$stmt = $conn->prepare('DELETE FROM `cv` WHERE cv_id = ?');
$stmt->bind_param('s', $cv_id);

// EXECUTE STATEMENT AND IF RESULT IS FALSE SHOW ERROR
// VOER STATEMENT UIT EN ALS VALS IS GEEF ERROR AAN
$result = $stmt->execute();
if ($result === FALSE) {
    die("Error: " . $stmt->error);
}
// AFTER CLICKING DELETE GO TO LINK
// NA HET DRUKKEN VAN DELETE GA NAAR LINK
header("Location: http://localhost:8080/Website/admin.php");

// CLOSE CONNECTION AND STATEMENT
// SLUIT CONNECTIE EN STATEMENT
$stmt->close();
$conn->close();
?>

EDIT:
My tables

A: You're deleting from those 2 tables based on the address id and cvid  if I understand your table structure correctly you should be deleting based on person ID from all 3 tables.

A: Based on the understanding I get from your table structure, you should have a person_id in the address table and the CV table respectively.
This means that, you should delete from the address and the CV tables based on the person_id
<?php
$servername = "localhost";
$username = "root";
$password = "usbw";
$dbname = "persons";

// CREATE A CONNECTION WITH THE DATABASE
// CONNECTIE MAKEN MET DATABASE
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// GET ID FROM person_id
// PAK ID VAN person_id
$person_id = (isset($_GET['person_id']) ? $_GET['person_id'] : null);

// CREATE PREPARE STATMENT FOR DELETING RECORDS FROM person_id
// MAAK EEN STATEMENT OM WAARDES TE VERWIJDEREN VAN person_id
$stmt = $conn->prepare('DELETE FROM `person` WHERE person_id = ?');
$stmt->bind_param('s', $person_id);

// EXECUTE STATEMENT AND IF RESULT IS FALSE SHOW ERROR
// VOER STATEMENT UIT EN ALS VALS IS GEEF ERROR AAN
$result = $stmt->execute();
if ($result === FALSE) {
    die("Error: " . $stmt->error);
}

$address_id = (isset($_GET['address_id']) ? $_GET['address_id'] : null);

$stmt = $conn->prepare('DELETE FROM `address` WHERE person_id = ?');

$stmt->bind_param('s', $address_id);

// EXECUTE STATEMENT AND IF RESULT IS FALSE SHOW ERROR
// VOER STATEMENT UIT EN ALS VALS IS GEEF ERROR AAN
$result = $stmt->execute();
if ($result === FALSE) {
    die("Error: " . $stmt->error);
}

$cv_id = (isset($_GET['cv_id']) ? $_GET['cv_id'] : null);

$stmt = $conn->prepare('DELETE FROM `cv` WHERE person_id = ?');

$stmt->bind_param('s', $cv_id);

// EXECUTE STATEMENT AND IF RESULT IS FALSE SHOW ERROR
// VOER STATEMENT UIT EN ALS VALS IS GEEF ERROR AAN
$result = $stmt->execute();
if ($result === FALSE) {
    die("Error: " . $stmt->error);
}
// AFTER CLICKING DELETE GO TO LINK
// NA HET DRUKKEN VAN DELETE GA NAAR LINK
header("Location: http://localhost:8080/Website/admin.php");

// CLOSE CONNECTION AND STATEMENT
// SLUIT CONNECTIE EN STATEMENT
$stmt->close();
$conn->close();
?>

It would be great if you actually make person_id a foreign key on the address and CV tables. You may not necessarily need to write a different delete for the two tables (CV and address)