text:
Q: How to disable special dates using angular ui datepicker I am using angular ui datepicker. I am disabling weekends. Along with that how can disable special dates.
My Special dates are (MM/dd/yyyy):

*

*03/30/2017

*04/28/2017

*etc.

Below is my HTML

              <input id="dt-date" name="dt-date" class="form-control"
                type="text" size="10" ng-model-options="{updateOn: 'default'}"
                required required-err-message="Date is Required"
                uib-datepicker-popup="{{TestVm.datePickerFormat}}"
                ng-model="TestVm.date"
                is-open="TestVm.dateDatePicker.isOpen"
                datepicker-options="TestVm.datePickerOptions"
                close-text="Close" alt-input-formats="TestVm.datePickerAltInputFormats" />

                   <button type="button" ng-model-options="{updateOn: 'default'}" class="btn btn-default" ng-click="TestVm.dateDatePicker()">

                   </button>

Datepicker options in Angular Controller
TestVm.datePickerOptions = {
                formatYear: 'yy',
                startingDay: 1,
                showWeeks: false,
                dateDisabled: myDisabledDates
            };

Function which disables weekends
function myDisabledDates(dateAndMode) {

        return (dateAndMode.mode === 'day' && (dateAndMode.date.getDay() === 0 || dateAndMode.date.getDay() === 6)) ;
    }

i already tried this but doesn't work also
function myDisabledDates(dateAndMode) {
var holidays = [ new Date(2017, 3, 30), new Date(2017, 3, 31), ];
return (dateAndMode.mode === 'day' && (dateAndMode.date.getDay() === 0 || dateAndMode.date.getDay() === 6 || holidays.indexOf(dateAndMode.date) != -1)); }


text:
Q: Getting Javascript critical error in IE11 I have a piece of code in my web application, When I include it, it works well in chrome but in IE11, it throws an critical error.

This is the code which is causing the error. If I comment it out, there is no error. That's why I'm pretty sure this code has some issue. and I couldn't find it.
JS Code
var inputs = document.querySelectorAll("input, select, textarea");
for(var el of inputs) {
   el.oldValue = el.value + el.checked;
}

debugger

even the debugger is pointing there. I don't know whats wrong in this code.

A: for ... of is not supported by IE as shown here in the Browser compatibility section

redpajama_set_name: RedPajamaStackExchange


text:
Q: Vue.js Lazy Loaded Routes with Hot Module Replacement (HMR) I'm trying to lazily load my Vue.js routes using vue-router and Webpack dynamic import statements like so:
const routes = [
  {
    component: () => import("./components/home.vue"),
    name: "home",
    path: "/",
  },
  {
    component: () => import("./components/child.vue"),
    name: "child",
    path: "/child",
  }
};

This correctly causes Webpack to split my JavaScript bundle by route, I end up with main.js and a series of 0.js, 1.js files. I've also noted that these are requested in the Chrome dev tools.
However, I cannot seem to get this to work with Hot Module Replacement (HMR). I using ASP.NET Core for my server side. When my page loads, I just see an empty page. When using Vuex with HMR, I had to follow this documentation to enable Vuex stores to be reloaded. Is there something similar I need to do for lazy loaded routes? Here is my webpack.config.js file if it helps:
import * as BrotliPlugin from "brotli-webpack-plugin";
import * as CompressionPlugin from "compression-webpack-plugin";
import * as ExtractTextPlugin from "extract-text-webpack-plugin";
import * as ForkTsCheckerWebpackPlugin from "fork-ts-checker-webpack-plugin";
import * as path from "path";
import * as StyleLintPlugin from "stylelint-webpack-plugin";
import * as SpriteLoaderPlugin from "svg-sprite-loader/plugin";
import * as webpack from "webpack";
import { BundleAnalyzerPlugin } from "webpack-bundle-analyzer";

const configurationBuilder = (env) => {
  const isDevBuild = !(env && env.prod);

  const cssDirectoryName = "css";
  const jsDirectoryName = "js";

  const wwwRootDirectory = "./wwwroot";
  const jsDirectory = `./wwwroot/${jsDirectoryName}`;

  const configuration = {
    stats: { modules: false },
    context: __dirname,
    resolve: {
      extensions: [".js", ".ts", ".vue"],
      alias: {
        vue$: "vue/dist/vue.common.js",
      },
    },
    entry: { main: "./ClientApp/Boot.ts" },
    module: {
      rules: [
        {
          test: /\.vue$/,
          include: /ClientApp/,
          loader: "vue-loader",
          options: {
            preserveWhitespace: isDevBuild, // Ignore white space in HTML
          },
        },
        {
          test: /\.ts$/,
          include: /ClientApp/,
          loader: "ts-loader",
          options: {
            appendTsSuffixTo: [/\.vue$/],
            silent: true,
            transpileOnly: true,
          },
        },
        {
          test: /\.scss$/,
          use: isDevBuild ? getSassLoaders() : ExtractTextPlugin.extract({ use: getSassLoaders() }),
        },
        {
          test: /\.svg$/,
          oneOf: [
            {
              resourceQuery: /inline/,
              use: getSvgUrlLoaders(),
            },
            {
              use: getSvgSpriteLoaders(),
            },
          ],
        },
        {
          test: /\.(png|jpg|jpeg|gif)$/,
          loader: "url-loader",
          options: {
            limit: 25000,
          },
        },
      ],
    },
    output: {
      path: path.join(__dirname, wwwRootDirectory),
      filename: "js/[name].js",
      chunkFilename: "js/[name].js",
      publicPath: `${jsDirectoryName}/`, // Needs a trailing slash for hot module replacement to work
    },
    plugins: [
      new ForkTsCheckerWebpackPlugin({
        tslint: true,
        vue: true,
      }),
      new webpack.DefinePlugin({
        "process.env": {
          NODE_ENV: JSON.stringify(isDevBuild ? "development" : "production"),
        },
      }),
      new StyleLintPlugin({
        configFile: ".stylelintrc.json",
        files: ["ClientApp/css/**/*.scss"],
      }),
      new SpriteLoaderPlugin(),
      new webpack.DllReferencePlugin({
        context: __dirname,
        manifest: require(`${jsDirectory}/vendor-manifest.json`),
      }),
    ].concat(isDevBuild ? [
      new webpack.SourceMapDevToolPlugin({
        filename: "[file].map",
        moduleFilenameTemplate: path.relative(jsDirectory, "[resourcePath]"),
      }),
    ] : [
        // Plugins that apply in production builds only
        new webpack.optimize.UglifyJsPlugin({
          comments: false,
        }),
        new ExtractTextPlugin(
          `${cssDirectoryName}/[name].css`),
        new CompressionPlugin({
          minRatio: 0.9,
          test: /\.(css|js|json|svg)$/,
        }),
        new BrotliPlugin({
          minRatio: 0.9,
          test: /\.(css|js|json|svg)$/,
        }),
        new BundleAnalyzerPlugin({
          analyzerMode: "static",
          openAnalyzer: false,
          reportFilename: "../bin/main-webpack-bundle-report.html",
        }),
      ]),
  };
  return configuration;
};

export default configurationBuilder;

A: Include a webpack directive in your import to indicate which chunk the component is in. I am doing exactly this is a large project and it is working fine.
import(/* webpackMode: "lazy", webpackChunkName: "/js/modules" */ 'modules/users')

I have setup aliases in my webpack configuration say my chunks have meaningful names instead 0.js, 1.js, etc.

A: You need to add these two plugins into your "dev"* plugins + set the devServer option with "hot" = true OR use --hot param when you run your webpack command.
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin(),

Why NamedModulesPlugin?

NamedModulesPlugin to make it easier to see which dependencies are
being patched

More info:

*

*https://webpack.js.org/guides/hot-module-replacement/

*https://webpack.js.org/concepts/hot-module-replacement/

*https://webpack.js.org/plugins/hot-module-replacement-plugin/

*https://webpack.js.org/plugins/named-modules-plugin/

* HMR is not intended for use in production, meaning it should only be used > in development. See the building for production guide for more information.


text:
Q: Custom function to replace values in R I'm trying to create a function to replace outliers in a variable:
outlier_upper_replace <- function(x, level=1.5) {
  lowerq = quantile(x, na.rm=TRUE)[2]
  upperq = quantile(x, na.rm=TRUE)[4]
  iqr = upperq - lowerq
  outlier_upper = (iqr * level) + upperq
  x[x > outlier_upper] <- outlier_upper
}

I can't understand why outlier_upper_replace(prod$varname) is not replacing the value.
If I run the following code, which is a particular case of the above function, the value is replaced:
level = 1.5
lowerq = quantile(prod$varname, na.rm=TRUE)[2]
upperq = quantile(prod$varname, na.rm=TRUE)[4]
iqr = upperq - lowerq
outlier_upper = (iqr * level) + upperq
prod$varname[prod$varname > outlier_upper] <- outlier_upper

Any insights about why this is happening?
EDIT: Example
set.seed(1)
x <- rnorm(100)
x <- c(-10, x, 10)

boxplot(x, main="start boxplot")

#function to bin-in upper outliers
outlier_upper_replace <- function(x, level=1.5) {
  lowerq = quantile(x, na.rm=TRUE)[2]
  upperq = quantile(x, na.rm=TRUE)[4]
  iqr = upperq - lowerq
  outlier_upper = (iqr * level) + upperq
  x[x > outlier_upper] <- outlier_upper
  return(x)
}

outlier_upper_replace(x)

boxplot(x, main="end boxplot")

A: Add
return(x)

to the end of your function.
The return value of an R function is the result of the last expression in the function body. Since you modify the vector in the last expression there is no result and you have to explicitly return the result.


text:
Q: It is possible to have an combobox with two stores in Ext js 4.2? I have to make a live search , and after hours spent on google I decided to ask here if anyone have an ideea how can I make an live search( using or not combobox) in Ext JS  but (the triky part). I have 2 data sets . One data set from one URL and and second from another URL.
I dont know how to start or how can I make the request when I type something in my search box to return small data set first and when is completly loaded second  data set ( is much bigger).
Something like when I type "computer" in search field in first block to show me some things related to computers (first request that have few data) after that in second block to show me more thing related to computer when request is over( second request lot of data).
I need this thing because in one of my request i have over 10 k product and i dont want to let user w8 until the request is done, and to show the other request that have fewer data. until the first is done.
I forgot to mention that i want to make both request in the same time and asynchronous.

A: My solution for exactly this kind of problem was:
Creating a store dedicated only for the combobox content.
When one of the two "source" stores loads data, they push the records into the combo-store.
You also have the reference between the records automatically, so if a record in source-store 1 or 2 is removed, it also disappears in your combostore- and so in your combobox, like magic! Here is the key, for pushing data on load in another store:
http://serversideguy.com/2012/01/31/ext-js-4-merging-store-data/
best regards, hope that helps, write if you need further sugggestion / info on this solution.

A: If the data is really vital, you can try loading up on memory when the application starts.
Create the stores you need on launch() of the app, load the data and the use it everywhere you want. You can do this on your controller launch() too, to your controller references and granulate this as you wish.
Ext.application({
    name: 'Blog',
    models: ['Post', 'Comment'],
    controllers: ['Posts', 'Comments'],

    launch: function() {
     Ext.define('User', {
         extend: 'Ext.data.Model',
         fields: [
             {name: 'firstName', type: 'string'},
             {name: 'lastName',  type: 'string'},
             {name: 'age',       type: 'int'},
             {name: 'eyeColor',  type: 'string'}
         ]
     });

     Ext.create('Ext.data.Store', {
         model: 'User',
         storeId: 'userStore',
         proxy: {
             type: 'ajax',
             url: '/users.json',
             reader: {
                 type: 'json',
                 root: 'users'
             }
         },
         autoLoad: true
     });    }

});


text:
Q: Leer Array e imprimirlo en HTML Tengo un array En base de datos que lo almacene de la siguiente manera
["valor1","valor2"]

para traerlo solo hago un select con eloquent y me trae toda la información. de toda la fila que quiero.
Quisiera saber como puedo imprimir solo valor1 o valor2
lo intente de la siguiente manera
{{$valor->valor[1]}}

pero me imprime solamente "

A: Según lo que hablamos en los comentarios, en $valor->valor tienes un string con este valor ["valor1","valor2"] y no un array php.
Entonces, lo primero sería decodificar el string de JSON en un array, lo cuál puedes lograrlo con json_decode.
Luego tendrás que iterar sobre el array resultante para imprimir los valores que tiene en cada elemento, ya que no puedes imprimir directamente un array php en el html.
Entonces creo que lo puedes resolver con un código así en la vista:
@foreach(json_decode($valor->valor, true) as $key => $val)
    {{$val}}
@endforeach


text:
Q: ARKit draw using addChild Node I am trying to draw the using ARKit add child node while transmitting the into webrtc. If drawing more annotations app gets freezes. Can anyone please guide me to overcome this issue?
This is the code I used to transfer the frame in webrtc:
guard let currentFrame = localArView.session.currentFrame else {
return }

guard let sceneImage: CGImage = self.localArView.snapshot().cgImage else { return }

let rtcPixelBuffer = RTCCVPixelBuffer(pixelBuffer: self.getCVPixelBuffer(UIImage(cgImage: sceneImage).cgImage!)!)
let timeStampNs: Int64 = Int64(currentFrame.timestamp * 1000000000)
let videoFrame = RTCVideoFrame(buffer: rtcPixelBuffer, rotation:  RTCVideoRotation._0, timeStampNs: timeStampNs)

self.webRTCClient.didCaptureLocalFrame(videoFrame)


text: Q: Specifying initial database version when using SQLDelight We're migrating from the Android platform SQLiteDatabase/SQLiteOpenHelper to use SQLDelight. Our first public database version was 17. By default, the SQLDelight Schema returns 1 for version. The only way I've been able to find to force version to 17 is to provide an empty 16.sqm migration file. Is this the correct way to do this, or is there a better way?


text:
Q: Trying to understand foreign key syntax Just starting out with SQL.  I understand the idea of foreign keys just fine, but I'm trying to learn the syntax of how to implement them and reading the sqlite page just gives me more questions than answers.  Is there any difference in the following two lines?
CREATE TABLE child(x REFERENCES parent(id));
CREATE TABLE child(FOREIGN KEY x REFERENCES parent(id));

Also, from my understanding, columns are specified by the "table.column" format, so I'd want to type "parent.id" above, but it seems all the reading I've done says "parent(id)".  What's the difference between the two and why use parent.id sometimes and parent(id) others?
Are we not supposed to bind any kind of affinity (I think I'm using the terminology correctly) to the foreign keys because it should just use whatever the parent key uses?
I have more questions, but this is a good start.  Thanks in advance for any help!

A: The difference between:
CREATE TABLE child(x REFERENCES parent(id));

and
CREATE TABLE child(FOREIGN KEY x REFERENCES parent(id));

is that the first creates a table with one column named x and a foreign key constraint.  The second creates a table without any columns but only a foreign key constraint.  The second statement should fail, since it references an unknown column x.
You have to declare a foreign key separately if it consists of multiple columns.  For one column,
column1 references parent(column1)

works fine.  For multiple columns, you need:
column1, column2, foreign key (column1, column2) references parent(column1, column2)

This also explains why the table.column format does not suffice.  It does not provide a way to specify multiple columns.


text:
Q: How do I create a string of blanks in C++? I need to create a string of blanks in c++, where the number of spaces is a variable, so I can't just type it in.
How do I do this without looping ?
Thanks!

A: #include <string>
std::string mystring(5,' ');

A: #include <string>
.....
//i is your variable length
string s_blanks_length_i( i, ' ' );

A: 5 spaces to standard output:
std::cout << std::string( 5, ' ' ) << std::endl;

A: size_t size = 5; // size_t is similar to unsigned int ‡
std::string blanks(size, ' ');

See: http://www.cplusplus.com/reference/string/string/string/
‡ See the question on size_t if this isn't clear.


text:
Q: Euler characteristic of a holomorphic homogeneous vector bundle Let $G/B$ be a compact homogeneous complex manifold, and let $E = G \times_{\rho} V$ be a hololmorphic homogeneous vector bundle over $G/B$. Does there exist a presentation of the Euler characteristic of $E$ in terms of the inducing representation $V$?
I am also interested in the question of how the $G$-module of holomorphic sections of $E$ relates to $V$, that is, the first cohomology group of $E$.

A: In the case $G$ is a complex semisimple Lie group and $P$ its parabolic subgroup, the answer is given by Kostant's version of Borel-Bott-Weil theorem [K]. Any homogeneous vector bundle is given by a associated bundle construction from some $P$-representation $\mathbb{F}$. In general, one can consider also $P$-representations which do not have highest weight $\lambda$, but let's stick to those that do are actually highest weight representations $\mathbb{F}_\lambda.$ In the case when $\lambda$ is $\mathfrak{g}$-integral and $\mathfrak{g}$-dominant, the cohomology of $E \simeq G\times_P\mathbb{F}_\lambda$ is calculated by Lie algebra cohomology of the nilradical $\mathfrak{u}$ of $\mathfrak{p} = \mathfrak{l} \oplus \mathfrak{u}$ and its $k$-th degree is given by
$$\bigoplus_{w \in W^\mathfrak{l}, l(w) = k} \mathbb{F}_{w\cdot \lambda}$$
where $W^\mathfrak{l}$ is the subset of minimal coset representatives of $W/W_{\mathfrak{l}}$ and $w\cdot \lambda = w(\lambda + \rho) - \rho.$
There are some generalization for weights which are not of this type. Look for "Kostant modules"
[K] Kostant, Bertram
Lie algebra cohomology and the generalized Borel-Weil theorem.
Ann. of Math. (2) 74 (1961), 329–387.


text:
Q: How do I create a ReactJS chrome extension that can open a new tab from a popup? I am creating a chrome extension using ReactJS. I essentially want to have two pages - One for the popup and a second page to be opened in a new tab by clicking a button on the popup.

A: Firstly I suggest following this tutorial for the basics.
https://medium.com/@gilfink/building-a-chrome-extension-using-react-c5bfe45aaf36
This would help a ton with the basics. A general summary is that you want to change the manifest.json in the public folder to what a chrome extension manifest.json would look like. Within that manifest.json, you want to add the index.html (also in the public folder) to be called wherever you want it to be called really.
Example here below:
{
     "manifest_version": 2,
     "short_name": "XXX",
     "name": "XXX",
     "version": "1.0.2",

     "browser_action": {
         "default_popup": "index.html", //popup page occurs when you click on the favicon
         "default_title": "Open the popup"
     },

     "chrome_url_overrides": {
         "newtab": "index.html" //registers an override page (index.html) to the newtab page.
     }
}

Overriding other pages:
https://developer.chrome.com/extensions/override
NOTE: Make sure that after building it with npm run build and when choosing the chrome extension in "Load Unpackaged" that you are picking the build folder and not the public folder.


text:
Q: In python: how to create new column with value of column and value of another between brackets. New column= column1(column2) I have a data frame with counts in a column and percentages in another. I want to create new column in this data frame presenting counts(percentages).
example data:
df=pd.DataFrame({'count': [1,2,3],
    'percent': [30,35,35]})
print(df)

while I want the result like this:
df=pd.DataFrame({'count': [1,2,3],
    'percent': [30,35,35], 'count(percent)': ['1(30)', '2(35)', '3(35)']})
print(df)

A: You can use this line:
  df["count(percent)"] = df["count"].astype(str) +'('+df["percent"].astype(str)+')'


text:
Q: How to know whether writing to stream would result in java.io.IOException: write failed: EBADF (Bad file number) I know there are a number of posts here on the java.io.IOException: write failed: EBADF (Bad file number) exception, but non of them seems to answer my particular question:
Suppose my activity is called with Intent.ACTION_VIEW and I got a Uri via                 Uri uri = intent.getData() that starts with content:// from which I read some data (for example a pdf file). Now I want to find out whether I can also write to that Uri to decide whether a "save" button should be shown to the user, or just a "save as" button.
Suppose further that I can successfully open first a ParcelFileDescriptor and finally a FileOutputStream as in
ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "w");
FileOutputStream fileOutputStream = new FileOutputStream(pfd.getFileDescriptor());

such that fileOutputStream != null.
Depending on the Uri it can now happen that if I try to write to fileOutputStream I get the exception:
Exception=java.io.IOException: write failed: EBADF (Bad file number)

I would like to know in advance whether this will happen without actually touching/changing the file. One would think that it should be possible to find out whether I can write to a given Uri or not before trying.
How can I achieve that?
Additional observations:
I suppose that the above happens when I don't have permission to write to that particular file/uri, but then why does Android let me open a FileOutputStream in the first place?
For testing I use attachments in emails received with Kaiten mail on an ICS device. If I my app opens after I click on "save" in Kaiten mail uri matches content://media/external/file/[0-9]* and everything works, if I however clicked on "open" uri matches content://com.kaitenmail.attachmentprovider/[-0-9a-f]*/[0-9]*/VIEW and I run into the above error.

A: There are apparently two methods:

*

*One can call
Context.checkCallingUriPermission(Uri uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION)

to check whether the calling process is allowed to write to a given Uri.
For the cases I could check, on API level < 19 this seems to result in PackageManager.PERMISSION_DENIED whenever the writing to an output stream pointing to uri fails and in PackageManager.PERMISSION_GRANTED in all other cases.
For API level >= 19 it however yields PackageManager.PERMISSION_DENIED even if one has previously taken a persisted write permission with getContentResolver().takePersistableUriPermission(Uri uri, int takeFlags). In that case however one can use
context.getContentResolver().getPersistedUriPermissions()

to get a list of all previously taken permissions and then look through them so see if one has permission to write to a given Uri.

*If one got he Uri via an Intent intent one can check its flags via intent.getFlags() and see whether Intent.FLAG_GRANT_WRITE_URI_PERMISSION is set. This also seems to be a way to "predict the future".
Obviously, neither of the above methods can be an excuse to not properly handle exceptions that can occur while writing to the stream.

A: The correct way to test whether any resource is available is to try to use it, and handle the exceptions or errors that result when you can't.
Anything else amounts to fortune-telling. You might

*

*test the wrong thing

*test the right thing but get an answer that is correct for the time of the test but not for the time of the actual use. This can work two ways, both bad: the test says you can't, but later you could: or the test says you can, but later you can't.

Don't try to predict the future. Coping with the present is difficult enough.


text:
Q: OpenACC unresolved extern function I am trying to optimize a problem using OpenACC, however, there are some basic functions that are set as routines. The main problem I am facing is with the calloc function where it shows the following error at the end:

ptxas fatal : Unresolved extern function 'calloc'

The command for compiling used is:
pgcc acc.c -acc -Minfo=accel -ta=nvidia:cc60,nordc -o acc

I previously tried without the nordc flag, however, there was this error:

nvlink error : Undefined reference to 'calloc' in '/tmp/pgccqWXdW9NTZXUL.o'
nvlink error : Undefined reference to 'rand' in '/tmp/pgccqWXdW9NTZXUL.o

A: Many system calls are not available on the device.  While you could replace 'calloc' with 'malloc' which is available, I would highly advise not allocating within device code.  Besides being very slow, the device heap is quite small (~32MB).  You'll be better off if you can refactor your algorithm to not dynamically allocate data on the device.
For "rand", you'll want to call 'cuRand'.  If you are using PGI, we ship examples on how to call cuRand under the "$PGI/2018/examples/CUDA-Libraries/curand" directory.  Note that 'rand' is not thread safe so should not be used in a parallel context, host or device.


text:
Q: How to use public IPs from remote network in my local network The image shows the current remote setup and proposed local network
I have 2 networks at different locations. For your better understanding one network I named remote network and another is local network. Both network have 1 linux box (CentOS 6.10) each.
Remote Network scenario:
The remote Linux have Public IP on its eth0 (IP 202.52.151.58, Subnet 255.255.255.224, GW 202.52.151.58). The Linux box connected to a Router(IP 202.52.151.62). The router have 202.52.151.32/27 IP Block aasigned.
Local Network scenario:
The Local Linux eth0 is connected to the internet router with private IP 192.168.1.127. The Linux eth1 is connected to 2 Hosts (1 Windows PC and 1 Voip Gateway) through a Switch. I want to assign the remote network's Public IP for the the hosts at the local network.
Please help me to do so.

A: Implement IPv6. Give each site a generous allocation, in an address plan that fits your organization. At least a /56, which is a couple hundred /64 subnets. Every device gets public IPs.
Yes, you will still have to maintain IPv4 for things. And there are ways design this with v4.  But why share a meager count of IP addresses and deal with NAT, when you can connect everything via the v6 internet?


text:
Q: Creating a user defined transformation in SAS DIS to produce work table I have code which produces some job specific variables in SAS DIS, and rather than having to copy this code into a User written code block for every job I write, I would like to have a predefined transformation to do this which I would drag from the transformations pane into any given job.
When creating a new transformation, in the SAS Code component of the dialogue, I paste some simple code. Let's say it looks like this:
DATA CREATE_JOB_SPECIFIC_VARS;
    job_name = "&etls_jobName";
    job_date = date();
RUN;

I don't need any prompts, so I select "Next" on the Options component of the dialogue, and I don't need any inputs so I set the minimum and maximum number of inputs to 0. I need 1 output (the work table I create with the code) so I leave the associated values as they are. I select "Next" and "Finish".
When I try to bring the transformation into a job and run it, two unexpected things occur:

*

*The output table of the transformation cannot be viewed, and attempting to do so yields the error:

Error accessing metadata: Table has no columns
  2. Running the transformation causes another transformation in the job to be connected to the input end of the newly created transformation (which should not accept any inputs).

I am mainly concerned with issue #1 (#2 is a curiosity which is of secondary importance). I'm guessing the issue arises since the software wants the columns of the output table to be specified somewhere other than the code block, but I see nowhere else that this can be done.
Is what I want to do possible? Must I create the job specific variables as macro variables (it is desirable to avoid this)?
Much gratitude!

A: For any custom written code dumping result in output table of the transformation would ideally show this error if the metadata of the output table is not defined. Just define the metadata by right clicking the table -> Properties -> Column tab and then you would stop getting the 1st error. Also, I'm assuming that you have altered the physical name of the output table (right clicking the output table -> Properties -> Physical Storage tab ) to CREATE_JOB_SPECIFIC_VARS since you are using "DATA CREATE_JOB_SPECIFIC_VARS;".
For the 2nd issue, if 2 or more separate flows are created within a single job flow then when the job flow is executed for the 1st time a dash line ( - - - ) is automatically generated which connects the separate flow in the order of control flow section. This is merely a way of showing user, the execution order of the job flow when it's executed. I think it's great that SAS DI Studio shows it otherwise it would be difficult to know from the diagram the order of the flow.
Let me know if it helps!


text:
Q: How can I set the mysql's password in the mysqld_safe is running scenario? I use bellow command find the running mysql service.
$ps -ef | grep mysqld
  501  4512     1   0 12:19 pm ??         0:00.06 /bin/sh /Applications/MAMP/Library/bin/mysqld_safe --port=8889 --socket=/Applications/MAMP/tmp/mysql/mysql.sock --pid-file=/Applications/MAMP/tmp/mysql/mysql.pid --log-error=/Applications/MAMP/logs/mysql_error_log
  501  4849  4512   0 12:19 pm ??         0:00.29 /Applications/MAMP/Library/bin/mysqld --basedir=/Applications/MAMP/Library --datadir=/Applications/MAMP/db/mysql56 --plugin-dir=/Applications/MAMP/Library/lib/plugin --log-error=/Applications/MAMP/logs/mysql_error_log.err --pid-file=/Applications/MAMP/tmp/mysql/mysql.pid --socket=/Applications/MAMP/tmp/mysql/mysql.sock --port=8889

But I forget the password, or maybe I did not set it.
now how can I set my mysql's password?
and whether the mysqld_safe service is running means the password did not set?

A: 1-Stop the mysql demon process using this command :
sudo /etc/init.d/mysql stop
2-Start the mysqld demon process using the --skip-grant-tables option with this command
sudo /usr/sbin/mysqld --skip-grant-tables --skip-networking &
3-start the mysql client process using this command
mysql -u root
4-from the mysql prompt execute this command to be able to change any password
FLUSH PRIVILEGES;
5-Then reset/update your password
SET PASSWORD FOR root@'localhost' = PASSWORD('password');
6-If you have a mysql root account that can connect from everywhere, you should also do:
UPDATE mysql.user SET Password=PASSWORD('newpwd') WHERE User='root';
7-Alternate Method:
USE mysql
   UPDATE user SET Password = PASSWORD('newpwd')
   WHERE Host = 'localhost' AND User = 'root';
8-And if you have a root account that can access from everywhere:
USE mysql
   UPDATE user SET Password = PASSWORD('newpwd')
   WHERE Host = '%' AND User = 'root';
For either method, once have received a message indicating a successful query (one or more rows affected), flush privileges:
FLUSH PRIVILEGES;
9-Then stop the mysqld process and relaunch it with the classical way:
sudo /etc/init.d/mysql stop
sudo /etc/init.d/mysql start


text:
Q: Can i use VS Setup Project to build a bootstrapper which can install correct platform version or are there any free 3rd party tools? I'm building 2 different MSI with Visual Studio Setup Project. One for x86 and x64. But i couldn't find a way to combine both into one project so that the bootstrapper is installing the correct platform version.
Is there a way to do so in VS Setup Project or are are there any free 3rd party tools i can use? I found dotnetinstaller, but i'm not sure if that is what i'm looking for.

A: You can use WiX bootstraper: More info can be found here: http://www.wixwiki.com/
An example how to build both 32 and 64 bit MSIs you will find here:
http://blogs.msdn.com/astebner/archive/2007/08/09/4317654.aspx

A: You could write a native app and have it check if the system is x86 or x64 then have it write the correct installer to a temp directory and run it. I wrote a blog post that could probably get you started at http://blog.foldertrack.com/?p=45


text:
Q: How can i get the last inserted value of primary kay field? I am using MySQL.I have to get the last inserted record's primary key value.
How can i get this?

A: This will return the last inserted id.
SELECT LAST_INSERT_ID();

OR
if ((result = mysql_store_result(&mysql)) == 0 &&
    mysql_field_count(&mysql) == 0 &&
    mysql_insert_id(&mysql) != 0)
{
    used_id = mysql_insert_id(&mysql);
}

A: mysqli_insert_id()
PDO::lastInsertId()
mysql_insert_id()

It's well worth checking the documentation if you are likely to meet "race" conditions. http://uk3.php.net/manual/en/function.mysql-insert-id.php etc.

A: There are two function that return this value:
mysql_insert_id()--> PHP function
LAST_INSERT_ID()--> MySQL function that can be used by PHP and other Languages or in MySQL command line interface or MySQL front-end

A: Use follwoing query:
  SELECT LAST_INSERT_ID();


text:
Q: SSD is not being recognized in BIOS I bought my first drive Mushkin Chronos 180GB and got it installed in my computer and loaded up.
I went to Windows 7 and initialized the drive and then I installed "SSDlife Free" and loaded it up and my the SSD drive came up said it was "powered on 3 times"(thought it was odd but then thought maybe some testing???).
I then restarted my computer and loaded into Acronis. Went to my SSD drive and make a partition called Windows (made a basic logical partition). I then loaded up Norton Ghost and wanted to copy my current Windows onto the SSD on the partition I made found out I could not do it through the recovery disk so I made a backup of my Windows drive and wanted to then restore it onto the SSD.
I came back an hour later when the backup was done. I tried to restore the it on my SSD and could not find the partition so I loaded up Acronis again and it did not see it. I then went to the BIOS and saw only my other hard drive.
What I tried

*

*Tried uplugging and replugging in both SATA and power cables.

*Tried using the power and SATA cable from the working drive and giving it the ones that SSD was using.

*Tried SATA AHCI Mode (Intel ICH9 Southbridge)

*Tried SATA PORT0-1 NATIVE MODE (Intel ICH9 Southbridge)

Nothing worked.
Software / hardware
Windows 7 Ultimate
Gigabyte S-Series GA-P35-DS3L Motherboard

A: Did your original WIN7 install have the 100MB hidden partition? Did you copy it and restore it with GHOST?  The hidden partition is required for booting in most cases. Not sure if that would have an impact on being able to "see" the drive in teh BIOS.  As @avirk notes, testing on a known good system would be a big help.  Even connecting as a second drive on a working system would help.


text:
Q: SSH password change automation over a list of IPs I have a bunch of linux servers. What I am trying to do is making sure all the servers have the password I want by prompting all the logins change. I am trying to implement it by writing a short bash script which includes the expect command. I am running it over a file which contains the list of IPs.
My file ips.txt contains:
10.195.166.52
10.195.166.54

My "expect" script is:
#!/usr/bin/expect -f

log_file myfile.log ;# <<< === append output to a file

set timeout 180
set username pippo
set old_password 0ldp455w0rd
set new_password n3wp455w0rd
set filedes [open "ips.txt" r]
gets $filedes ip

while {$ip != -1} {
spawn ssh $username@$ip
expect "$username"
send "$old_password\r"
expect "(current)"
send "$old_password\r"
expect "New"
send "$new_password\r"
expect "Retype"
send "$new_password\r"
expect "$username"
send "exit\r"
#expect eof ;#wait for the connection to close
}
close $filedes

What I obtain is:
You are required to change your password immediately (root enforced)
Last login: Thu Jul 19 16:14:46 2018 from 10.222.233.139
WARNING: Your password has expired.
You must change your password now and login again!
Changing password for user pippo.
Changing password for pippo.
(current) UNIX password:
New password:
Retype new password:
passwd: all authentication tokens updated successfully.
Connection to 10.195.166.52 closed.
send: spawn id exp6 not open
    while executing
"send "exit\r""
    ("while" body line 12)
    invoked from within
"while {$ip != -1} {
spawn ssh $username@$ip
expect "$username"
send "$old_password\r"
expect "(current)"
send "$old_password\r"
expect "New"
send "$ne..."
    (file "./passwd.xp" line 12)

So the script is not proceeding further than the first IP. What is happening ? I am trying variations of the expect commands without success.


text:
Q: Output of SQL query is not coming properly (multiple Lines for status) Below is the query I have written to fetch the patch compliance status.
 select
vUI.Title As 'Title',
vui.ArticleID,
CASE
    WHEN vsn.StateID = 0 or vsn.StateID = 1 or vsn.StateID =  2 THEN --'No Status'
    count(vRSV.Netbios_Name0)
END As 'No Status',
CASE
    WHEN vsn.StateID = 3 or vsn.StateID = 4 or vsn.StateID = 5 or vsn.StateID = 7 or vsn.StateID = 8 or vsn.StateID = 12 or vsn.StateID = 14 THEN --'In Progress'
    count(vRSV.Netbios_Name0)
end as 'In Progress',
Case
    WHEN vsn.StateID = 6 or vsn.StateID = 11 or vsn.StateID = 14 THEN --'Failed'
    count(vRSV.Netbios_Name0)
End as 'Failed',
Case
    WHEN vsn.StateID = 9 or vsn.StateID = 10 THEN --'Success'
    count(vRSV.Netbios_Name0)
    --ELSE 'Not Installed'
END As Success
from v_UpdateComplianceStatus vUCS
join v_UpdateInfo vUI
  on vUCS.CI_ID=vUI.CI_ID
  join v_R_System_Valid vRSV  on vUCS.ResourceId=vRSV.resourceid
inner join v_FullCollectionMembership_Valid vFCMV
  on vUCS.ResourceId=vFCMV.ResourceID
  and vFCMV.CollectionID='CB00123'
join v_GS_OPERATING_SYSTEM vGOS
    on vUCS.ResourceID = vGOS.ResourceID
join v_StateNames vSN
  on vUCS.LastEnforcementMessageID = vSN.StateID and (vSN.TopicType=402 or vSN.TopicType=500 or vSN.TopicType=400)
where vui.DateLastModified between '2019-09-12' and '2019-10-12'
  group by vUI.Title,vui.ArticleID, vsn.StateID

I was expecting output like below.
ArticleID   No Status   In Progress Failed  Success
4516033     NULL          8           102   2149

But output is coming as below.
ArticleID   No Status   In Progress Failed  Success
4516033     NULL          NULL        25    NULL
4516033     NULL          NULL        NULL  253
4516033     NULL          NULL       NULL   1896
4516033     NULL          NULL        69    NULL
4516033     NULL           8           8    NULL

What am I doing wrong here?

A: You want conditional aggregation.  The CASE is the argument to the aggregation function.  So:
select vUI.Title As Title, vui.ArticleID,
       sum(case when vsn.StateID in (0, 1, 2)
                then 1 else 0
           end) as no_status,
       sum(case when vsn.StateID in (3, 4, 5, 7, 8, 12, 14)
                then 1 else 0
           end) as in_progress,
       . . .
from . . .
group by vUI.Title As Title, vui.ArticleID;

Note that you need to change both the SELECT and the GROUP BY.
Also:

*

*Do not use single quotes for column aliases.  That just causes confusion.  Single quotes should only be used for string and date constants.

*Choose column aliases that do not need to be escaped (so avoid spaces).

*IN simplifies your comparisons.

A: you should try summing each value and not suing count() on each row
select
vUI.Title As 'Title',
vui.ArticleID,
sum ( CASE
      WHEN vsn.StateID = 0
        or vsn.StateID = 1 or vsn.StateID =  2 THEN  1 else 0
      END  ) As 'No Status',

sum ( case
      WHEN vsn.StateID = 3 or vsn.StateID = 4 or vsn.StateID = 5
              or vsn.StateID = 7 or vsn.StateID = 8
               or vsn.StateID = 12 or vsn.StateID = 14 THEN 1 else 0

       end ) as 'In Progress',

 sum( CASE
      WHEN vsn.StateID = 6 or vsn.StateID = 11
          or vsn.StateID = 14
     THEN 1 else 0

     End ) as 'Failed',
   sum( CASE WHEN vsn.StateID = 9 or vsn.StateID = 10
      THEN 1 else 0
     END ) As Success
from v_UpdateComplianceStatus vUCS
join v_UpdateInfo vUI
  on vUCS.CI_ID=vUI.CI_ID
  join v_R_System_Valid vRSV  on vUCS.ResourceId=vRSV.resourceid
inner join v_FullCollectionMembership_Valid vFCMV
  on vUCS.ResourceId=vFCMV.ResourceID
  and vFCMV.CollectionID='CB00123'
join v_GS_OPERATING_SYSTEM vGOS
    on vUCS.ResourceID = vGOS.ResourceID
join v_StateNames vSN
  on vUCS.LastEnforcementMessageID = vSN.StateID and (vSN.TopicType=402 or vSN.TopicType=500 or vSN.TopicType=400)
where vui.DateLastModified between '2019-09-12' and '2019-10-12'
  group by vUI.Title,vui.ArticleID


text:
Q: Swift- updating global variable outside closure with completion handler I've searched but I just can't figure out why my global array variable isn't getting updated in the global scope when I call this function. I've commented places in the code where I can print() the results I want but can't make it available outside the functions. I know it's something simple I'm not understanding about closures and completion handlers but I need someone else to have a look. Thanks.
import Foundation
import PlaygroundSupport

func pdate(month: String, day: String, year: String) -> String {
    let pdate = month + "/" + day + "/" + year
    return pdate
}

struct Phenomenon {
    var phenom: String
    var date: String
    var time: String
}

struct Apsides: Codable {
    let data: [Apsdata]?
    struct Apsdata: Codable {
        let phenom: String
        let year: String
        let month: String
        let day: String
        let time: String
    }
}

var arrFromURL: [(Phenomenon)] = []  //define a global I can use later- I know, globals are evil

func doURLsessions(completionHandler: @escaping (Phenomenon?)->()) {
    let sessionApsides = URLSession(configuration: URLSessionConfiguration.default)
    if let timeurl = URL(string: "http://api.usno.navy.mil/seasons?year=2018&tz=-8&dst=true") {
        (sessionApsides.dataTask(with: timeurl, completionHandler: { (data, response, error) in
            if let error = error {
                print("Error: \(error)")
            } else if let data = data {
                let jsonDecoder = JSONDecoder()
                let response = try? jsonDecoder.decode(Apsides.self, from: data)
                if (response?.data != nil) {
                    for item in [response?.data] {
                        for p in item! {
                            switch p.phenom {
                            case "Perihelion":
                                let perihelion = Phenomenon.init(
                                    phenom: p.phenom, date: pdate(month: p.month, day: p.day, year: p.year), time: p.time)
                                completionHandler(perihelion)
                            case "Aphelion":
                                let aphelion = Phenomenon.init(
                                    phenom: p.phenom, date: pdate(month: p.month, day: p.day, year: p.year), time: p.time)
                                completionHandler(aphelion)
                            default: ()
                            }
                        }
                    }
                }
            }
            //print(arrFromURL) //This works fine, but not what I want
        })).resume()
    }
}

func chPhenom(phenom: String, date: String, time: String) {
    let p = Phenomenon.init(phenom: phenom, date: date, time: time)
    arrFromURL.append(p)
    //print(arrFromURL) //Also works fine,  but I want it's contents avilable outside this function
}

doURLsessions(completionHandler: {Phenomenon in
    chPhenom(phenom: Phenomenon!.phenom, date: Phenomenon!.date, time: Phenomenon!.time)
})

print(arrFromURL) //This just prints []- why isn't the global var available here? Is it printed before the asynch func finishes?

PlaygroundPage.current.needsIndefiniteExecution = true

A: Code in function doURLsessions is asynchronous - it isn't blocking other code from executing and since it is a network request it takes some time to finish. In your case print(arrFromURL) is called before doURLsessions is finished so arrFromURL is still empty.


text:
Q: capistrano rails app has parent folder in git using cap '3.7.2' and rails 4.2. Our rails app in in git with a parent folder, so in the git repo there is parentfolder/app instead of app at the root. This causes cap to put my app in a sub folder in the release folder which messes everything up. Is there some easy way to tell cap to ignore the parent folder?

A: Finally found it!
set :repo_tree, 'mysubdir'


text:
Q: Трансляция звука Подскажите программу, чтобы она транслировала звук речь в реальном времени. То есть, нужно установить такую программу на ПК, чтобы я мог подключиться к нему удаленно и слушать что говорят там и т.д. Программа должна запускаться в фоне вместе с системой и работать тоже в фоне. Существуют ли такие программы?

A: Самый простой вариант - "ivideon server" . Работает как служба, пишет и транслирует видео и звук. Бесплатна, если не считать облачное хранение. Есть некоторая нестабильность в работе при определенных условиях.
Vlc запущенный с определенными параметрами и транслировать звук например по rtsp и слушать другим vlc в локальной сети. Просто кинуть ярлык с параметрами в автозагрузку


text:
Q: multi-recipient PHP email form not sending emails I'm trying to get my email form working, but something seems to be hanging up. it's not sending out emails at all!
For reference, this uses Wordpress, and this is the code:
<?php
$action=$_REQUEST['action'];
if ($action=="")    /* display the contact form */
    {
    ?>
    <form  action="#" method="POST" enctype="multipart/form-data">
    <input type="hidden" name="action" value="submit">
    Your name:

    <input name="username" type="text" value="" size="30"/>

    Department:

          <select id="department" class="form-control-footer">
        <option value="Email_0">Sales</option>
        <option value="Email_1">Support</option>
        <option value="Email_2">Website Feedback</option>
        <option value="Email_3">Other</option>
      </select>

    Email Subject

    <input name="emailsubject" type="text" value="" size="30"/>

    Your email:

    <input name="email" type="text" value="" size="30"/>

    Your message:

    <textarea name="message" rows="7" cols="30"></textarea>

    <input type="submit" value="Send email"/>
    </form>

    <?php
    }
else                /* send the submitted data */
    {
    $name=$_POST['username'];

    if (($department=="Email_0"))
    {
        $mailto=$_POST['example@website.com'];
        }
    if (($department=="Email_1"))
    {
        $mailto=$_POST['example@website.com'];
        }
    if (($department=="Email_2"))
    {
        $mailto=$_POST['example@website.com'];
        }
    else
    {
        $mailto=$_POST['example@website.com'];
        }

    $emailsubject=$_POST['emailsubject'];
    $email=$_POST['email'];
    $message=$_POST['message'];
    if (($name=="")||($email=="")||($message==""))
        {
        echo "All fields are required, please fill the form again.";
        }
    else{
        $from="From: $name<$email>\r\nReturn-path: $email";
        $subject="Webform : $emailsubject";
        mail($mailto, $subject, $message, $from);
        echo "Thank you for your email! Your email has been sent, and we will try to respond as soon as we can!";
        }
    }
?>

I've modified the base form to add in departments, which changes the recipient of the contact form. but in doing so, it seems the form no longer sends out those emails at all.
Anyone know what I've done wrong?

A: Here you need to add "name="department"" to the code below
<select id="department" name="department" class="form-control-footer">

Here you need to change your code as showed below:
if (($_POST['department'] == "Email_0"))
{
    $mailto='example@website.com';
}
else if ($_POST['department'] == "Email_1")
{
    $mailto = 'example@website.com';
}
...


text:
Q: Problem with SSL on tomcat with this code i would like to know what this error means:
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target null
this error appers when i try to use this state:
private HttpState setcookies(String msg){
    HttpState state = new HttpState();
    String[] splited;
    String authToken=null;
    String tokenSecret=null;
    splited = msg.split(" ");
    authToken=splited[1];
    tokenSecret=splited[2];
    org.apache.commons.httpclient.Cookie cookie = new org.apache.commons.httpclient.Cookie("winter.servebeer.com", EXTCOOKIE+"accessToken", authToken);
    cookie.setPath("/OfeliaP");
    state.addCookie(cookie);
    cookie=new org.apache.commons.httpclient.Cookie("winter.servebeer.com", EXTCOOKIE+"tokenSecret", tokenSecret);
    cookie.setPath("/OfeliaP");
    state.addCookie(cookie);
    return state;
}

A: I've experienced this kind of thing.  I suspect that the problem is that you've configured the server to present the certificate chain in the wrong order.  Web browsers typically don't care, but the Java implementation of SSL / TLS requires the certificates in the chain to be in the right order.


text:
Q: Django queryset update fields with the lowercase equivalent - Django I would like to update various models in go.
I need to update a varchar field with the lowercase equivalent.

Any idea if this can be done with a single queryset?

A: Since this is a one-off it would be easier to just run ./manage.py dbshell and run the UPDATE queries directly.
UPDATE sometable SET somefield=LOWER(somefield);

A: If you want to do it by using ORM, just try Database Functions.
You can make one fast call:
from django.db.models.functions import Lower
SomeModel.objects.update(somefield=Lower('somefield'))


text:
Q: How can I find out the hostnames of other computers in the same local network? In my local wifi, I can find out the IP and MAC of another computer which also runs Lubuntu, and whose hostname is known to me.
$ sudo arp-scan olive
[sudo] password for t:
Interface: wlx801f02b5c389, datalink type: EN10MB (Ethernet)
Starting arp-scan 1.9 with 1 hosts (http://www.nta-monitor.com/tools/arp-scan/)
192.168.1.198   aa:bb:cc:dd:ee:ff   Liteon Technology Corporation

1 packets received by filter, 0 packets dropped by kernel
Ending arp-scan 1.9: 1 hosts scanned in 1.449 seconds (0.69 hosts/sec). 1 responded

There are other computers in the same local wifi network, which most likely run Windows and whose hostnames I don't know.
Can I find out their hostnames from my computer? arp-scan -l doesn't show that information.
Thanks.

A: Install nmap for whatever flavour of Linux you are on.
Then perform:
nmap -sP xxx.xxx.xxx.xxx/nn

Where xxx.xxx.xxx.xxx/nn is your IP and subnet mask bits. For example, if you were on 192.168.1.0 network with a subnet mask of 255.255.255.0 you would do:
nmap -sP 192.168.1.0/24

Nmap will ping scan all IPs and try to resolve their hostnames for you.
For example, on my local LAN I see:
nmap -sP 192.168.169.0/24

Starting Nmap 7.60 ( https://nmap.org ) at 2019-02-23 20:23 CST
Nmap scan report for _gateway (192.168.169.1)
Host is up (0.00026s latency).
Nmap scan report for grid (192.168.169.6)
Host is up (0.00026s latency).
Nmap scan report for anode (192.168.169.8)
Host is up (0.000048s latency).
Nmap scan report for 192.168.169.100
Host is up (0.0027s latency).
Nmap scan report for 192.168.169.101
Host is up (0.049s latency).
Nmap scan report for 192.168.169.102
Host is up (0.092s latency).
Nmap scan report for 192.168.169.104
Host is up (0.012s latency).
Nmap scan report for 192.168.169.106
Host is up (0.055s latency).
Nmap scan report for 192.168.169.107
Host is up (0.12s latency).
Nmap scan report for 192.168.169.109
Host is up (0.00095s latency).
Nmap scan report for 192.168.169.250
Host is up (0.0024s latency).
Nmap done: 256 IP addresses (11 hosts up) scanned in 3.79 seconds

The hosts with no names are dhcp and do not get hostnames. The others are in DNS, and so they have hostnames.
Similarly, arp-scan should give you the mac address. Again, install arp-scan for your distribution, then do:
arp-scan 192.168.1.0/24

Assuming again you are on the same LAN as the example above. If you have a non-standard interface, you may specify it with the -I switch:
arp-scan -I enp4s2 192.168.1.0/24

Note that on most distros, you will need to be root for this, so (again, example on my local LAN):
sudo arp-scan 192.168.169.0/24

This discovered all of my nodes:
Interface: enp5s0, datalink type: EN10MB (Ethernet)
Starting arp-scan 1.9 with 256 hosts (http://www.nta-monitor.com/tools/arp-scan/)
192.168.169.6   74:d4:35:85:e0:44   GIGA-BYTE TECHNOLOGY CO.,LTD.
192.168.169.1   f4:f2:6d:70:16:c2   (Unknown)
192.168.169.100 6c:70:9f:d0:ff:1a   (Unknown)
192.168.169.101 10:9a:dd:80:f4:93   Apple, Inc.
192.168.169.104 08:02:8e:8e:a0:f6   (Unknown)
192.168.169.111 00:1c:c0:6e:f4:ec   Intel Corporate
192.168.169.106 fc:c2:de:4c:58:48   (Unknown)
192.168.169.102 b4:f6:1c:f2:f9:52   (Unknown)
192.168.169.103 dc:68:eb:5b:aa:c8   (Unknown)
192.168.169.250 00:01:e6:a2:3f:17   Hewlett-Packard Company
192.168.169.107 68:37:e9:d7:39:0b   (Unknown)
192.168.169.105 08:d4:6a:d1:df:5e   (Unknown)

13 packets received by filter, 0 packets dropped by kernel
Ending arp-scan 1.9: 256 hosts scanned in 2.438 seconds (105.00 hosts/sec). 13 responded

A: Reverse-lookup each live host on your router; you will discover their dhcp-hostnames (usually these are set to their hostnames) - first create live_hosts.txt:
sudo arp-scan 192.168.169.0/24 | grep ^192 | awk '{print $1} > live_hosts.txt
then:
for host in $(cat live_hosts.txt) ;
  do echo $host ;
  host $host $router_ip ;
  sleep 0.1 ;
done
Note that your router will query its dhcp-leases file, and even nodes that have disconnected will resolve until their leases are purged. But all currently online nodes will be listed unless your routers name service (usually some tiny dnsmasq) is broken.
You may want all the information for posterity, such as hardware addresses and duration of connections; you can script this easily by scanning your network at intervals, appending output to a file.
You can discover more about linux boxes if they have running services (sshd seems popular nowadays), and all variants will usually have some bonjour/zeroconf hooey active (google mDNS), often something like avahi-daemon. (Call it bugaboo, jimjonesdiary, maga, puss-socket, it's just mDNS. Who are these people that decided on rendezvous, bonjour, avahi. Make it funny at least, please... rarghh.)
While a simple arp MITM with e.g. scapy may be disruptive and rude, you can do what you like on your own network. Using tcpdump to see DNS lookups will tell you both OS and enable you to guess at who is using that machine.


text:
Q: (qt6 + postgre) Driver not loaded, как подключить драйвер (macos) Не могу разобраться, как либо создать драйвер(как указано в документации, да для qt5.6, но для 6й я просто не нашел нужного раздела), либо указать путь до драйвера(он отображается как существующий).
Конекшусь(пытаюсь) к локальной postgresql, установленной из brew в дефолтный путь (/opt/homebrew/var/pos...@15/data), сам qt установлен в users/murzabaev/Qt/..
Вывод из консоли.
QSqlDatabase: QPSQL driver not loaded
QSqlDatabase: available drivers: QSQLITE QODBC QPSQL

В pro файл указал путь до папки с драйверами(самого драйвера я там не нашел).

qt6.4
postgresql 15
Не совсем по теме:
Недавно стал макось юзером, проблему(не решил!) обошел тем, что за виртуалил убунту и поднял бд с qt там, но хотелось бы, понять как все таки запустить данное приложение в дефелтной ос.
Я нашел что-то похожее, но так и не смог разобраться, он каким то образом проваливается в Application/Postgres.app/ (у меня такого апп нет), да и тема так и осталось не завершенной.


text:
Q: Calculation of Akaike Information Criterion My data file is given below.
Expt. (Col 1:2) Fit1 (Col 3:4)  Fit2 (Col 5:6)
x_expt. y_expt  x_fit   y_fit   x_fit   y_fit
2.89394 3.04606 2.95515 3.14485 2.96485 3.16485
2.90727 3.22788 2.96788 3.31939 2.97758 3.34061
2.92788 3.42545 2.98242 3.50303 2.99212 3.52606
2.97576 3.62303 2.99818 3.69758 3.00788 3.72182
2.97394 3.84182 3.01576 3.90182 3.02545 3.92848
3.00061 4.06364 3.03515 4.11818 3.04485 4.14606
3.02788 4.29939 3.05636 4.34545 3.06606 4.37515
3.05758 4.54848 3.08    4.58545 3.0897  4.61697
3.09455 4.80424 3.10606 4.83818 3.11576 4.87212
3.12909 5.07818 3.13515 5.10424 3.14485 5.14061
3.1697  5.37152 3.16667 5.38485 3.17758 5.42364
3.20727 5.65333 3.20182 5.68061 3.21273 5.72182
3.25394 5.98    3.24061 5.99152 3.25212 6.03576
3.30061 6.30909 3.28364 6.32121 3.29576 6.36364
3.35697 6.66061 3.33091 6.66667 3.34364 6.71515
3.41212 7.0303  3.38242 7.02424 3.39636 7.07879
3.47273 7.41818 3.44    7.40606 3.45455 7.46667
3.54606 7.82424 3.50303 7.81212 3.51818 7.87273
3.62242 8.24848 3.57212 8.2303  3.58909 8.29697
3.69939 8.69697 3.64788 8.67879 3.66667 8.74545
3.79212 9.16364 3.73152 9.14545 3.75212 9.21212
3.8903  9.66061 3.82364 9.6303  3.84545 9.70909
4.00242 10.1818 3.92424 10.1455 3.94848 10.2242
4.13212 10.6909 4.03455 10.6849 4.06121 10.7697
4.29697 11.2667 4.15576 11.2546 4.18485 11.3394
4.39273 11.8909 4.28788 11.8485 4.32061 11.9394
4.5503  12.5091 4.43273 12.4727 4.46848 12.5636
4.72061 13.2    4.59152 13.1212 4.63091 13.2242
4.89152 13.8424 4.76424 13.8061 4.80788 13.9091
5.07818 14.5636 4.95333 14.5212 5.00061 14.6303
5.30303 15.3212 5.15879 15.2667 5.21091 15.3818
5.54606 16.0788 5.38303 16.0485 5.44    16.1636
5.79212 16.8909 5.62667 16.8667 5.68848 16.9879
6.07273 17.7273 5.89212 17.7212 5.95939 17.8424
6.35152 18.6303 6.18182 18.6121 6.25455 18.7333
6.67879 19.5394 6.49091 19.5394 6.5697  19.6667
6.99394 20.4727 6.8303  20.503  6.91515 20.6364
7.42424 21.4485 7.19394 21.5091 7.28485 21.6424
7.73939 22.497  7.59394 22.5515 7.69091 22.6909
8.17576 23.5879 8.01818 23.6424 8.12121 23.7758
8.64242 24.7091 8.47879 24.7697 8.58788 24.903
9.12727 25.8242 8.97576 25.9394 9.09091 26.0788
9.59394 27.0727 9.50909 27.1515 9.6303  27.2909
10.1636 28.297  10.0788 28.4061 10.2061 28.5455
10.6909 29.5212 10.6909 29.7091 10.8242 29.8424
11.3939 31.0121 11.3455 31.0485 11.4909 31.1818
12.1152 32.4121 12.0485 32.4364 12.1939 32.5697
12.903  33.8667 12.8    33.8667 12.9455 34
13.6364 35.3515 13.5939 35.3455 13.7515 35.4667
14.4303 36.8546 14.4485 36.8606 14.6    36.9818
15.2849 38.5515 15.3515 38.4242 15.503  38.5394
16.2606 40.1939 16.3091 40.0303 16.4606 40.1455
17.2364 41.8909 17.3212 41.6788 17.4788 41.7879
18.3212 43.7091 18.3939 43.3697 18.5455 43.4727
19.4667 45.5576 19.5273 45.103  19.6788 45.2061
20.5152 46.8849 20.7212 46.8788 20.8667 46.9758
22.0606 49.1758 21.9818 48.6909 22.1152 48.7939
23.3152 51.1879 23.303  50.5515 23.4303 50.6485
24.7212 53.1576 24.6909 52.4485 24.8061 52.5455
26.2121 55.4727 26.1455 54.3879 26.2485 54.4849

a). Col 1:2 represent experimental data.
b). Col 3:4 is fitted data using non-linear least squares fitting using 4 adjustable parameters.
c). Col 5:6 is fitted data using non-linear least squares fitting using 5 adjustable parameters with one parameter fixed to 0.
I wish to calculate AIC for both the fits and conclude which fit is better. Can anybody suggest how to solve this problem in R or Excel?


text:
Q: Linkage error between C++ executable and tensorflow.lib I have been compiling tensorflow 2.4 following this link.
Out of the build process I have:

*

*tensorflow.lib

*tensorflow.dll

*tensorflow headers

To build my application I am using cmake, and the following line handle the linkage:
target_link_libraries(${ADD_EXAMPLE_NAME} PUBLIC ${CMAKE_SOURCE_DIR}/libs/tensorflow/tensorflow.lib)

When building I get the following error:
[ 95%] Linking CXX executable tensorflow_main.exe
CMakeFiles\tensorflow_main.dir/objects.a(tensorflow_main.cpp.obj): In function `main':
C:/Users/tmac3/Desktop/PhD/Homing-Pigeon/examples/tensorflow_main.cpp:8: undefined reference to `tf_git_version()'
...

CMake (more precisely ld) does not find the tensorflow symbols... Therefore, I used DUMPBIN to check whether the symbols are present in tensorflow.lib:
?>DUMPBIN /EXPORTS tensorflow.lib > exports.txt
?>findstr "tf_git_version" exports.txt
        ?tf_git_version@@YAPEBDXZ (char const * __cdecl tf_git_version(void))

Problem: The symbol seems to be present in tensorflow.lib and I ask CMake to link my executable to this file.
Question: What am I missing?
Edit 1:
?>DUMPBIN /SYMBOLS tensorflow.lib
Microsoft (R) COFF/PE Dumper Version 14.28.29337.0
Copyright (C) Microsoft Corporation.  All rights reserved.

Dump of file tensorflow.lib

File Type: LIBRARY

COFF SYMBOL TABLE
000 01017299 ABS    notype       Static       | @comp.id
001 00000000 SECT2  notype       External     | __IMPORT_DESCRIPTOR_tensorflow
002 C0000040 SECT2  notype       Section      | .idata$2
003 00000000 SECT3  notype       Static       | .idata$6
004 C0000040 UNDEF  notype       Section      | .idata$4
005 C0000040 UNDEF  notype       Section      | .idata$5
006 00000000 UNDEF  notype       External     | __NULL_IMPORT_DESCRIPTOR
007 00000000 UNDEF  notype       External     | ⌂tensorflow_NULL_THUNK_DATA

String Table Size = 0x58 bytes

COFF SYMBOL TABLE
000 01017299 ABS    notype       Static       | @comp.id
001 00000000 SECT2  notype       External     | __NULL_IMPORT_DESCRIPTOR

String Table Size = 0x1D bytes

COFF SYMBOL TABLE
000 01017299 ABS    notype       Static       | @comp.id
001 00000000 SECT2  notype       External     | ⌂tensorflow_NULL_THUNK_DATA

String Table Size = 0x20 bytes

  Summary

          CC .debug$S
          14 .idata$2
          14 .idata$3
           8 .idata$4
           8 .idata$5
          10 .idata$6


text:
Q: Change Icon & Window Title colors for Windows 8.1 Thanks to this post I was able to finally change the color of windows active title bar but that is it, unfortunately it still leaves many things to be desired. For example:

*

*How to change the desktop icon text color

*How to change the clock in the taskbar (as well as other taskbar font colors)

*How to change the inactive title bar font color

Is there not a solution that involves copying someone else's preset settings?
I've attempted editing the registry as other posts have mentioned but so far nothing I've edited has changed anything. I've changed the following thus far:

*

*HKEY_CURRENT_USER > Control Panel > Colors

*HKEY_CURRENT_USER > Control Panel > Desktop > Colors

*HKEY_CURRENT_USER > Control Panel > Desktop > WindowMetrics
I was eventually able to get some things to change (after 20+ trial and error restarts), but for things like icons I think I need to change the WindowMetrics but unfortunately those are using binary values that I can't modify without breaking everything (never attempt without a backup).
Would be great if there was a public cheat sheet or some form of documentation on the topic since Microsoft wants to make such a simple task so difficult.


text:
Q: Multiple large file upload to SP in angular I am trying to upload multiple large files to the SP in the angular project and I've done it successfully. But my code uploads all the files at once into the server. This process will lead to some problems within the system. Now I am trying to recreate the program to upload files asynchronously and I'm confused with how to do it properly. Can anyone help me to understand it help me to do it the proper way? Part of my codes are below.

upload.component.html

        <input class="form-control" #selectedFile required type="file" id="formFile" (change)="onFileSelected($event)" [disabled]="uploading" accept="*/*" multiple>

        <button class="btn btn-primary" id="uploadFileBtn" type="button" (click)="onUploadFile()" [disabled]="fileSelected == false || uploading"> Upload</button>

        Status:

         {{progressText}}

upload.component.ts

......
  onFileSelected(event) {
    this.files = event.srcElement.files;
    console.log(event);
    if (this.files) {
      this.fileSelected = true;
    }
    this.progressText = "Click Upload button to start upload";
  }

  onUploadFile() {
    this.uploading = true;
    this.progressText = "Upload pending...";
    if (!this.itemId) {
      this.createSharepointFolder();
    } else {
      // this.uploadFile();
      this.uploadMultipleFiles();
    }
  }

  async uploadMultipleFiles() {
    for (const file of this.files) {
      console.log("Call uploadFile(files:File) to upload file one by one.");
      console.log(file.name);

      await this.uploadFile(file)
    }

  }

  async uploadFile(currentFile: File) {
    this.sessionUploadURL = '';
    var file = currentFile;
    console.log(file.name);

    var fileNameArray = file.name.lastIndexOf('.');
    var fileType = file.name.substring(fileNameArray + 1);
    var fileName = file.name.substring(0, fileNameArray);
    this.progressText = "Creating session...";
    this.ms_graph.currentStatusMessage.subscribe(
      status => {
        this.progressText = status;
        this.changeDetection.detectChanges();
      });
    this.ms_graph.uploadingStatus.subscribe(
      status => {
        this.uploading = status;
        this.changeDetection.detectChanges();
      });
    this.ms_graph.uploadSuccessStatus.subscribe(
      status => {
        this.uploadSuccess = status;
        if (this.uploadSuccess == true) {
          this.toastr.success("File uploaded sucessfully", "Upload complete");
          this.updatedParentRecordEvent.emit(this.parentRecord);
          this.selectedFileField.nativeElement.value = ""; // Clear the value of the file select field
        }
      });
    this.ms_graph.get_upload_session(fileType, fileName, this.itemId).subscribe(
      (response: MSCreateUploadSession) => {
        console.log(JSON.stringify(response));
        this.sessionUploadURL = response.uploadUrl;
        this.ms_graph.upload_chunks.call(this.ms_graph, file, this.sessionUploadURL);

      },
      (error) => {
        console.error("Error get_upload_session() \n" + JSON.stringify(error));
        throw (error);
      }
    );
    this.fileSelected = false;

  }

And upload_chunks method, readFragmentAsync method & upload_chunk method within upload.service.ts file.

upload.service.ts

/*  function upload_chunks
    After getting the uploadUrl, this function does the logic of chunking out
    the fragments and sending the chunks to uploadChunk */
async upload_chunks(file: File, uploadUrl: string) {
    console.log('upload_chunks() called');
    this.changeUploadStatus(true);
    this.changeUploadSuccessStatus(false);
    this.changeStatusMessage("Uploading file...");
    const ms_graph = this;
    var reader = new FileReader();

    // Variables for byte stream position
    var position = 0;
    var chunkLength = 320 * 1024;
    console.log('File size is: ' + file.size);
    var continueRead = true;
    // var token = this.get_token();
    while (continueRead) {
        var chunk;
        try {
            continueRead = true;
            //Try to read in the chunk
            try {
                let stopB = position + chunkLength;
                console.log('Sending Asynchronous request to read in chunk bytes from position ' + position + ' to end ' + stopB)
                chunk = await this.readFragmentAsync(file, position, stopB);
                console.log("UploadChunks: Chunk read in of " + chunk.byteLength + " bytes.");
                if (chunk.byteLength > 0) {
                    continueRead = true;
                } else {
                    break;
                }
                console.log('Chunk bytes received = ' + chunk.byteLength);
            } catch (e) {
                console.log('Bytes Received from readFragmentAsync:: ' + e);
                break;
            }
            // Try to upload the chunk.
            try {
                console.log('Request sent for uploadFragmentAsync');
                // let res = MSCreateUploadSession;
                let res;
                res = await ms_graph.upload_chunk(chunk, uploadUrl, position, file.size);
                let currentBytes = this.util.formatBytes(position);
                let totalBytes = this.util.formatBytes(file.size);
                // Check the response.
                if (res[0] != 202 && res[0] != 201 && res[0] != 200)
                    throw ("Put operation did not return expected response");
                if (res[0] === 201 || res[0] === 200) {
                    console.log("Reached last chunk of file.  Status code is: " + res[0]);
                    continueRead = false;
                }
                else {
                    console.log("Continuing - Status Code is: " + res[0]);
                    position = Number(res[1].nextExpectedRanges[0].split('-')[0])
                }

                console.log('Response received from upload_chunk.');
                this.changeStatusMessage(`Uploading file... (${currentBytes}/${totalBytes})`);
                console.log(`Uploading file... (${currentBytes}/${totalBytes})`);
                // console.log('Position is now ' + position);

            } catch (e) {
                console.log('Error occured when calling upload_chunk:' + e);
            }
            //
        } catch (e) {
            continueRead = false;
        }
    }
    console.log("upload finished and worked!!");
    this.changeStatusMessage("File uploaded sucessfully");
    this.changeUploadStatus(false);
    this.changeUploadSuccessStatus(true);
}
// Reads in the chunck and returns a promise.
    readFragmentAsync(file, startB, stopB) {
        let frag: string | ArrayBuffer | null;
        const reader = new FileReader();
        console.log('startBytes :' + startB + ' stopBytes :' + stopB)
        var blob = file.slice(startB, stopB);
        reader.readAsArrayBuffer(blob);
        return new Promise((resolve, reject) => {
            reader.onloadend = (event) => {
                console.log("onloadend called  " + reader.result?.toString);
                if (reader.readyState == reader.DONE) {
                    frag = reader.result
                    resolve(frag);
                }
            };
        })
    }
    // Upload each chunk using PUT
    upload_chunk(chunk, uploadURL, position, totalLength) {//: Observable<any> {
        let max = position + chunk.byteLength - 1;
        let contentLength = position + chunk.byteLength;

        console.log(chunk.byteLength);

        return new Promise((resolve, reject) => {
            console.log('uploadURL:: ' + uploadURL);

            try {
                console.log('Just before making the PUT call to uploadUrl.');
                let crHeader = `bytes ${position}-${max}/${totalLength}`;
                console.log('Content-Range header being set is : ' + crHeader);
                request
                    .put(uploadURL)
                    .set({ 'Content-Range': crHeader})
                    // .set({ 'Authorization': 'Bearer ' + this.get_token() })
                    .send(chunk)
                    .end((err, res: any) => {
                        if (err) {
                            console.error(err);
                            reject(err);
                            return;
                        }

                        console.log(res.status);
                        console.log(res.body);
                        resolve([res.status, res.body]);

                    });
            } catch (e) {
                console.log('exception inside uploadFragmentAsync::  ' + e)
                reject(e);
            }
        });
    }

A: An perhaps easier approach would be to load the files to an azure blob storage from angular. Then at server side you can access those files when you need them.
The backend api (C#) supports, stream reading, byte[] and whole files.
Cost is not to large either and if money is critical, you can easy delete the files after handling them backend.
Frontend api has an official npm package which you can use and there is an updated guide in azure portal when you have created your first azure blob storage.
Also you have the benefit that the security of the file transfer is handled by the azure system.


text:
Q: How do I add a git submodule in a non empty directory? I am trying to add a submodule in a non empty folder inside a repo with:
git submodule add repo_path.git non_empty_folder

I get the following message:
'non_empty_folder' already exists and is not a valid git repo

Is it possible to force the creation of the submodule? Thanks!

A: *

*Create a new submodule repo outside your main project repository.

*Rsync files from the directory which you want to make a submodule in your main project.

*Commit these files into submodule repo and push it to origin.

*git remove all files in the submodule directory in main project

*Commit changes in main project

*Now you are ready to create a submodule

A word of caution.  I would highly suggest using a visual tool like SourceTree to help you manage submodules.  It is an advanced feature of git and if not managed properly will give you plenty of grief.  On a flip side, if used properly it is very powerful and can help you avoid code duplication.


text:
Q: Eclipse ADT bug - using wrong ResId Today I noticed a very strange bug - the system used the wrong ResId in the method SetBackgroundResource(). Sure I thought it was my mistake. I fixed the ResId by copying and pasting it from the R file. After I've re-installed the app many times for testing I noticed that a wrong image was set again so it messed up my app. I went to the corresponding method and found out that Eclipse inserted a very similar (but wrong! ..015 instead of ..016) ResId as a method parameter without any actions from me.
I don't think that's important but this strange thing always happens here:
LinearLayout nlap = new LinearLayout(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
    LinearLayout.LayoutParams.MATCH_PARENT,
    LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(10, 5, 10, 0);
nlap.setLayoutParams(params);
nlap.setOrientation(LinearLayout.HORIZONTAL);
nlap.setBackgroundResource(0x7f020016);
nlap.getBackground().setAlpha(111);
return nlap;

A: Just clean all your related projects and build again.
Never hard-code a R.id.
I've seen this before: With old versions of ADT and library projects this would sometimes happen. Haven't seen it with ADT 21.
Recently, for me, Eclipse has started underlining R.id's red as if they are wrong or unknown, but they do not show up in the Problems view, and they are not actually wrong. I'm still looking for a bug report for this.


text:
Q: How can I upgrade ansi-html from 0.0.7 to 0.0.8? I have a maven application which uses ReactJS for the front-end and it is using ansi-html:0.0.7 currently. This led to vulnerability alert by GitHub dependabot and it asks me to upgrade to version @^0.0.8.
Usually when I need to upgrade something, I go to yarn.lock file and delete the respective block of configuration and run yarn install/build again which installs the latest version of the dependency.
However, in this case, it is only re-installing 0.0.7 and not 0.0.8 or higher.
I even tried adding the package "ansi-html":"0.0.8" in package.json file and reinstalled everything. Still, no luck.
How can fix this?
Thanks in advance.

A: I know this is an old question, but I am going to add an answer anyway for general knowledge.
From what I understood from the question, ansi-html is a sub-dependency of other dependency in your application. Before forcing a new version of a sub-dependency you need to know what package uses this dependency. You can do that by running
yarn why <package name>

The output will tell you what package in the project that uses that dependency. If that package has a new version then upgrade to it.
If that doesn't work, you can force the affected package to use a newer version of it by adding it to the resolutions section of package.json file
"resolutions": {
    <package name>: <version number>
}

Then try to do a full yarn install or npm install
I don't like this approach and I only use it as a last resort, because if you do any upgrades in the future, it will force sub-dependencies to always download the versions of the resolution section and it could cause issues in the future. So please use it when there is no other solution


text:
Q: how to test if the difference between two percentages is significant on same participants I have 150 students and I made them learn with a book, then with a movie. I graded whether they passed or failed the test.
The results look like this:
60% of students passed when they learned with a book.
70% of students passed when they learned with the movie.
How to tell if the difference is significant?


text:
Q: Erro Netbeans 8.2 "java.sql.SQLException: Unknown system variable 'query_cache_size'" Não consigo conectar em um banco de dados MySql através da IDE Netbeans, é informado o seguinte erro: java.sql.SQLException: Unknown system variable 'query_cache_size'

A: Consegui resolver o erro apenas atualizando a versão do plugin do Maven


text:
Q: Traversing an ExcelRange with EPPlus I'm using EPPlus to read data from an excel file. At one point, I want to get a row of data as an ExcelRange and pass it into another function. But when I try to traverse the ExcelRange in that function, it seems to reassign the ExcelRange.
For instance, if I do this:
Console.WriteLine(excelRange.ToString());
Console.WriteLine(excelRange[1, 1].Text);
Console.WriteLine(excelRange.ToString());

the output I get is
C41:BP41
Training
A1

("Training" is the text in cell A1 of my spreadsheet, not in cell C41)
If I instead try to do:
Console.WriteLine(excelRange.ToString());
Console.WriteLine(excelRange[excelRange.Start.Row, excelRange.Start.Column].Text);
Console.WriteLine(excelRange.ToString());

then I get
C41:BP41

C41

Is there a way to traverse a ExcelRange without it changing?

A: I found a way, but am hoping someone knows of a better way. Here's what I've got that works:
int startRow = excelRange.Start.Row;
int startCol = excelRange.Start.Column;
int endCol = excelRange.End.Column;
for (int i = startCol; i <= endCol; i++)
{
    string cellText = excelRange[startRow, i].Text;
}

A: Alternatively, you can get list of values in cells as
int startRow = excelRange.Start.Row;
int startCol = excelRange.Start.Column;
int endRow = excelRange.End.Row;
int endCol = excelRange.End.Column;

var rowValues=(object[,]) worksheet.Cells[startRow, startCol, endRow, endCol].Value;
List<string> lstValues = rowValues.Cast<object>().ToList().ConvertAll(x => Convert.ToString(x));


text:
Q: How to ensure that we write to a row after a read and ensure that nothing has changed in Rails? Quick question:
Imagine this scenario:
if !order.has_not_refunded?
    order.refund! (has stuff like Stripe.refund, etc.)
end

I want to make sure that after I make the check that the order has refunded, I want to refund and make sure that nothing else has refunded the order yet. It's possible that in between the check and the refund, some other process could have refunded the order. How do I ensure that while reading the row, nothing else can write to the row? Is this what I even want? If so, what's the best way to do this? Does Rails have anything built in to prevent this?


text:
Q: Is there any way of reindent the WHOLE code without using external codeblocks plugins? Is there any way to reindent the WHOLE CODE without installing the Smartindent plugin? A keyboard shortcut maybe?

A: The answer was select all code, then use the source code formatter plugin (AStyle) in the plugins button

A: In vi:
To insert a tab on every line:
:%s/^/\t/
Or if you wanted a certain number of spaces, replace \t with that.
Slightly more complex:
:%s/^([\t ])/\1\t/
Which says replace lines that begin with space or tab with that starting character plus a tab.  (You can substitute \t for number of spaces.)  This way, if your function definitions start in column 1, they'll still be there.  Additionally, blank lines will not unnecessarily have spaces/tabs inserted on them.


text:
Q: How to implement "get or create" query with Realm for Xamarin? Consider the simple model:
public class Session : RealmObject
{
    [ObjectId]
    public string UserId { get; set; }
    public string Token { get; set; }
}

How to get the Session instance by ID or null if it doesn't exist?
var realm = Realm.GetInstance ();
var q = realm.All<Session> ().Where ((x) => x.UserId = "1");
// This won't work if no session is saved:
// var session = q.First ();
// and this won't either
// var session = q.FirstOrDefault ();
// And this is mmm... kind of strange but it's working :)
var session = q.Count() > 0 ? q.First() : null;

So, how it's supposed to be done by design?

A: What you would like to do is:
var localSession = theRealm.All<Session>().FirstOrDefault((Session session) => session.UserId == "1");

But FirstOrDefault/SingleOrDefault is not yet supported (as of 0.77.2)
Any, First and Single are currently supported (Current Linq Support):
If/Else on Any style:
Session session = null;
var sessions = theRealm.All<Session>().Where((Session localSession) => localSession.UserId == "1");
if (!sessions.Any())
    theRealm.Write(() =>
    {
        session = new Session() { UserId = "1", Token = "SO" };
    });
else
    session = sessions.First();
D.WriteLine($"{session?.UserId}:{session?.Token}");

Try/Catch on InvalidOperationException:
Session localSession = null;
try
{
    localSession = theRealm.All<Session>().First((Session session) => session.UserId == "1");
}
catch (InvalidOperationException error) when (error.Message == "Sequence contains no matching element")
{
    theRealm.Write(() =>
    {
        localSession = new Session() { UserId = "1", Token = "SO" };
    });
}
D.WriteLine($"{localSession?.UserId}:{localSession?.Token}");

A: Update
Support for var localSession = theRealm.All<Session>().FirstOrDefault(session => session.UserId == "1"); has shipped in version 0.78.0 onwards.
Original
I am now working on the relevant Realm issue.
Please add comments on there for specific scenarios you would like supported.
Note that we also now have a Nightly feed if you want to try something ahead of an official NuGet release.


text:
Q: Hide and show a comment form with a click I am trying to make the WordPress comment form not show all the time, but to open when clicking on a button. The below code I tried works great.
The problem is that I also want the form to hide by clicking the same button. Any suggestions on how to do this?
Click here to leave a Comment<

  <?php comments_template( '', true ); ?>


text:
Q: apex:commandButton renders incorrectly According to the  Salesforce API, an <apex:commandButton> should render as <input type="submit"> however in my visualforce page, it renders as <input type="button">. Anyone know why this might be happening, and how to fix it?
Here is my code:
<apex:commandButton value="View Applicable Offerings" action="{!getOfferings}" status="status" styleClass="centered btn btn-default" rerender="results, messages" id="getOfferingsButton"/>
<apex:actionFunction name="search" action="{!getOfferings}" status="status" rerender="resultsBlock"/>
<apex:actionStatus id="status" styleClass="centered">
    <apex:facet name="start">
        <img src="/img/loading.gif" class="centered" />
    </apex:facet>
</apex:actionStatus>

A: If the apex:commandButton uses a reRender attribute, it renders as a button, otherwise it renders as a submit.
<apex:page >
    <apex:form id="form">
        <apex:commandButton value="Submit 1" rerender="form"/>
        <apex:commandButton value="Submit 2"/>
    </apex:form>
</apex:page>

Observe the generated HTML for this page and you'll see the difference.
This is semantically correct, because the former doesn't actually submit the form directly (it uses AJAX). The documentation is most likely just incomplete, because it only provides one example.


text:
Q: sync or async for waitforexistence in XCTest? I am new to XCTest and see the following code but get one question about waitforexistence
if aXCUIElement.waitforexistence(timeout: 60) || bXCUIElement.waitforexistence(timeout: 60) {
}

in this case, are we waiting for one minutes to see if aXCUIElement or bXCUIElement exists? or we are waiting for one min for aXCUIElement then waiting for another 1 mins for bXCUIElement?


text:
Q: Yii2 render two models on one view Yii is the best but I'm having a wee bit of trouble replicating some of the code from yii1 to yii2, below I use the code in yii to render two models in one view and would like to replicate this using yii2. Grateful for any help. thanks
VwContractDetailsController

public function actionView($id)//create new dataprovider and pass param from url
    {
        $events=$dataProvider=new CActiveDataProvider('VwContractEvents', array(
            'criteria'=>array(
                'condition'=>'Contractkey_id=:aid',
                'params'=>array(':aid'=>$id)
                ),
                'pagination'=>array(
            'pageSize'=>2
            ),
                'sort' => array(
        'defaultOrder' => 'EventDate DESC',
    ),
            ));

$this->render('view',array(
            'model'=>$this->loadModel($id),
            'events'=>$events,

        ));
    }

vwContractEvents Index //provide full path for itemview

<?php $this->widget('zii.widgets.CListView', array(
    'dataProvider'=>$dataProvider,
    'itemView'=>'/vwcontractevents/_view',
    'enablePagination' => true,

)); ?>

vwContractDetails view //render VwcontractEvents/index on vwContractDetails view

<?php
 $this->renderPartial('/VwContractEvents/index',array('dataProvider'=>$events));
?>

A: The equivalent of renderPartial() in yii2 view is:
yii\base\View::render()

In controller you render with:
yii\base\Controller::render()


text:
Q: SQL: replace NULL with SPACE I want to create a fixed length flat file (separated by ','), but when a field has a null value, the record moves. Please see illustration below (incorrect Jenny and Roland records):
Source Table:

Name    Color  Balance Zip Code
------- ------ ------- --------
Melissa Orange $200.00 40240
Karl    Blue   $150.00 40884
Jenny   -null- -null-  45667
Roland  -null- $110.00 53366
Vincent Green  $285.00 45677

Output I want to get:

Correct_Ouput
----------------------------
Melissa,Orange,$200.00,40240
Karl   ,Blue  ,$150.00,40884
Jenny  ,      ,       ,45667
Roland ,      ,$110.00,53366
Vincent,Green ,$285.00,45677

Output I want to get:

Wrong_Output
----------------------------
Melissa,Orange,$200.00,40240
Karl   ,Blue  ,$150.00,40884
Jenny  ,,,45667
Roland ,,$110.00,53366
Vincent,Green ,$285.00,45677

I tried searching but I get the null to empty string result.
Please help. Thank you.

A: Use the COALESCE(column,' ') function.
For some databases, you can use IFNULL or NVL. See this web page for more details.

A: You could use NVL to replace the NULL value with required number of spaces to retain the format.
For example,
SQL> SELECT 'Karl' NAME,
  2    NVL('Blue', '     ') color,
  3    NVL('$150.00','         ') balance,
  4    40884 zip_code
  5  FROM dual
  6  UNION ALL
  7  SELECT 'Jenny' name,
  8    NVL(NULL, '     ') color,
  9    NVL(NULL,'         ') balance,
 10    45667 zip_code
 11  FROM dual
 12  /

NAME  COLOR BALANCE     ZIP_CODE
----- ----- --------- ----------
Karl  Blue  $150.00        40884
Jenny                      45667

SQL>

You could also use DECODE.
For example,
DECODE(column, NULL, '      ')


text: Q: Google auth to Cloud Firestore with React Native I have created Google authentication to Firebase but I would like to know if I can save the credentials(email, username) of those users to Cloud Firestore DB because I would like to have all the users saved in Firestore. Later, I would like users who have authenticated using Google email, to be able to edit their profiles, for ex. change their name, add a phone number, etc.


text:
Q: What is the best Linux file system to use for MySql? When setting up a dedicated MySql server, what is the best Linux file system to use? Are there any I should avoid?
The data partition will be on a simple Raid 1 mirror (in hardware).

A: From https://stackoverflow.com/questions/1021854/what-is-the-best-linux-filesystem-for-mysql-innodb.  Can we do cross-site dupes?

You should have a look at Lessons Learned in Building a Highly Scalable MySQL Database. They benchmarked mysql with some of these filesystems and jfs looks like a clear the winner.


text:
Q: how to discard sms using webworks in blackberry I am developing an application using webworks api for blackberry OS 5.
my application is listening to received SMSs and detect specific messages from a specicfic numbers then extract some information of it.
my problem is to delete this message from inbox of mobile !
how to discard an sms from blackberry mobile inbox ?

A: In BlackBerry OS 7.1 and lower there is no API for a third party application to delete SMS messages from the user's inbox or block messages from appearing there.
The sender of the SMS message can craft it in a way to prevent it from being shown in the user's inbox.  For more information on that see Use SMS to notify an application.


text:
Q: Finding duplicate values in multidimensional array I'm trying to code a system which will find user accounts that are using the same IPs, and print out the matches with their keys. I have already coded the part where the data is pulled from MySQL and nicely put in a multidimensional associative array, so input looks like this (the key is UserID, values are IP addresses):
$users = array(
               100 => array("1.1.1.1","2.2.2.2","3.3.3.3"),
               200 => array("1.1.1.1","4.4.4.4","5.5.5.5"),
               300 => array("1.1.1.1","4.4.4.4","7.7.7.7")
              );

The expected output would be:
Array
(
    [1.1.1.1] => Array
        (
            [0] => 100
            [1] => 200
            [2] => 300
        )

    [4.4.4.4] => Array
        (
            [0] => 200
            [1] => 300
        )
)

I have searched and used trial and error with multiple nested foreach that would loop through the arrays, tried array_intersect to find the duplicates, but nothing gets me close to the expected output. By now I think I'm overthinking the problem and the solution is really easy, but I cannot seem to get close to the expected output. Any help is appreciated, thank you.

A: $users = array(
                100 => array("1.1.1.1","2.2.2.2","3.3.3.3"),
                200 => array("1.1.1.1","4.4.4.4","5.5.5.5"),
                300 => array("1.1.1.1","4.4.4.4","7.7.7.7")
                );

$allIP = [];
foreach ( $users as $user ) {
    $allIP = array_merge($allIP, $user);
}
$allIP = array_unique($allIP);

$result = [];
foreach ( $allIP as $ip ) {
    foreach ( $users as $key => $val ) {
        if ( in_array($ip, $val, true) ) {
            if ( !isset($result[$ip]) ) {
                $result[$ip] = [];
            }
            array_push($result[$ip], $key);
        }
    }
}

$result = array_filter($result, function ($v, $k) {
    if ( count($v) > 1 ) {
        return true;
    } else {
        return false;
    }
}, ARRAY_FILTER_USE_BOTH);

var_dump($result);

Although I think it's better to do this by SQL as well. It could be extremely slow to achieve this by PHP.

A: $output = array();
// loop through each user
foreach ($users as $id => $ips) {
    // loop through each IP address
    foreach ($ips as $ip) {
        // add IP address, if not present
        if (!isset($output[$ip])) {
            $output[$ip] = array();
        }
        // add user ID to the IP address' array
        $output[$ip][] = $id;
    }
}


text:
Q: Rxjava approach the get last Observable from each thread I'm thinking how to use RXJava for the scenario described bellow.
A List<Object>,each object will be sent to k8s and checked the status till the respone return true,so my polling active is that:
  private Observable<Boolean> startPolling(String content) {
    log.info("start polling "+ content);
    return Observable.interval(2, TimeUnit.SECONDS)
      .take(3)
      .observeOn(Schedulers.newThread())
      .flatMap(aLong -> Observable.just(new CheckSvcStatus().check(content)))
      .takeUntil(checkResult -> checkResult)
      .timeout(3000L, TimeUnit.MILLISECONDS, Observable.just(false))
      ;
  }

Function of sent action:
Observable<Compo> sentYamlAndGet() {
  log.info("sent yaml");
  sentYaml()
  return Observable.just(content);
}

I try to use the foreach to get each object status which like this:
  public void rxInstall() throws JsonProcessingException {
    List<Boolean>observables = Lists.newArrayList();
    Observable.from(list)
      .subscribeOn(Schedulers.newThread())
      .concatMap(s -> sendYamlAndGet())
      .timeout(3000l, TimeUnit.MILLISECONDS)
      .subscribe()
    ;

    Observable.from(list).forEach(s -> {
      observables.add(Observable.just(s)
        .flatMap(this::startPolling)
        .toBlocking()
        .last()
      )
      ;
    System.out.println(new ObjectMapper().writeValueAsString(observables));
  }

Objects of outputs list is :{"o1","o2","o3","o4","o5"}
the last status of objest which I want is : [false,true,false,false,true].
All above style is not much 'ReactX',check object status action do not affect to each other.
How to throw foreach? I trid toIterable(),toList() but failed.
  Observable.from(list)
  .concatMap(s -> sentYamlAndGet())
  .concatMap(this::startPolling)
  ....
  ;

Wanted to know if it's good practice to do that and what would be the best way to do that?
Thanks in advance.

pps: currentlly I'm using rxjava1 <version>1.2.0</version> but can change to 2(´▽`)ノ


text:
Q: Create an InputSelect component that accepts lists with Blazor With Blazor InputSelect you have iterate over list items in the component ChildContent but
I want to create a custom Blazor (WebAssembly version 5) InputSelect that could accept a list of any object to render in the select, the code could be like the followings :
<CustomInputSelect @bind-Value="@myEntity.CountryId" For="@(()=> myEntity.CountryId)" List="countries"
 ValueField="@(a => a.Id)" DisplayField="@(a => a.CountryName)" ></CustomInputSelect>

or even this :
<CustomInputSelect @bind-Value="@myEntity.Country" For="@(()=> myEntity.Country)" List="countries"
 ValueField="Id" DisplayField="CountryName" ></CustomInputSelect>

(Note: I used the For property to help compiler to infer the type of CountryId and also for validation. This is @typeparam of the component.)
I tried so many approaches but none of the worked so I explain them below:

*

*I tried using dynamic type for the list but it seems that Blazor does not supports dynamic types because there was error in razor generated code.

*I tried to use multiple @typeparam for the component, one for the value and one for the list items. And it seems that it does not support it either.
@inherits InputSelect
//or add another typeparam @typeparam TListItem
And
  <select>
                @foreach (var item in List)
                {
                   < option value="???">???</option >
                }
    </select>

    @code{
     [Parameter] public Expression<Func<TValue>>? For { get; set; }
     [Parameter] public List<dynamic> List { get; set; }// or List<TListItem>
     [Parameter] public Expression<Func<TListItem>>? ValueField { get; set; }
     [Parameter] public Expression<Func<string>>? DisplayField { get; set; }

    }

My goal is to send a list of any type to InputSelect while @typeparam is used for binding.

A: I've previous built and used this
@typeparam TItem

    <select class="form-control-label" @onchange="ChangeHandler">
        @if (ShowDefaultOption)
        {
            <option value="0" hidden disabled>- Please Select -</option>
        }
        @foreach (var (id, item) in idDictionary)
        {
            <option value="@id">@Selector(item).ToString()</option>
        }
      </select>

@code {

[Parameter] public IList<TItem> Items { get; set; }
[Parameter] public Func<TItem, object> Selector { get; set; }
[Parameter] public EventCallback<TItem> ValueChanged { get; set; }
[Parameter] public bool ShowDefaultOption { get; set; } = true;

private Dictionary<Guid, TItem> idDictionary;

protected override void OnInitialized()
{
    idDictionary = new Dictionary<Guid, TItem>();
    Items.ToList().ForEach(x => idDictionary.Add(Guid.NewGuid(), x));
}

private async Task ChangeHandler(ChangeEventArgs args)
{
    if (idDictionary.TryGetValue(Guid.Parse(args.Value.ToString()), out var selectedItem))
    {
        await ValueChanged.InvokeAsync(selectedItem);
    }
}
}

Then use can use it like this:
<MySelect ValueChanged="handleStringChange" TItem="string" Items="stringItems" Selector="(x => x)" />b

@_selectedStringItem

@code {

IList<string> stringItems = new List<string>()
{
    "Random",
    "String",
    "Content",
    "ForDemo"
};

string _selectedStringItem;
void handleStringChange(string value) => _selectedStringItem = value;
}

Or with an object:
<MySelect ValueChanged="handleChange" TItem="Person" Items="items" Selector="(x => x.Firstname)" />

@if (_selectedItem is object)
{

Selected person: Name: @_selectedItem.Firstname, Age: @_selectedItem.Age

}

@code {
    class Person
    {
        public string Firstname { get; set; }
        public int Age { get; set; }
    }

    IList<Person> items = new List<Person>
    {
        new Person {Firstname = "John Doe", Age = 26},
        new Person {Firstname = "Jane Doe", Age = 23}
    };

    Person _selectedItem;

    void handleChange(Person value) => _selectedItem = value;
 }