text:
Q: Old JPEG compression to New JPEG compression using libtiff I am currently having a problem with my tiff to bmp implementation as I always encounter this error:
scannerdata.tif: Old-style JPEG compression support is not configured.
How can I convert old-style JPEG compression to new-style JPEG compression to make it supported. Please refer to this post here for my implementation libtiff error: Old-style JPEG compression support is not configured


text:
Q: Adding a caption to a graphic inside a longtable I have the following longtable :
\begin{longtable}{|p{10cm}|}
    \hline
    some text

    \includegraphics[width=10cm,keepaspectratio]{\basedir some.png}

    some text\\
    \hline
\end{longtable}

Is there a way to insert a caption and a label to a graphic inside a longtable?
Or
How can I insert a figure into a longtable cell?
I have been searching for a while but couldn't find any solution.
Thanks in advance.

A: define
\makeatletter
\def\figcaption{%
    \refstepcounter{figure}%
     \@dblarg{\@caption{figure}}}
\makeatother

Then you can use
\figcaption{my caption}

where you have some text

A: David's wise answer guided me to the solution. I am just improving his answer but I lack reputation points to add a comment.
First, it works also for longtabu.
Second, we can also add a table caption with:
\makeatletter
\def\tabcaption{%
\refstepcounter{table}%
\@dblarg{\@caption{table}}}
\makeatother

Then use:
\tabcaption{my caption}

Third, I strongly believe that one has to use p{} columns to get it working. In longtabu, I was using X[] columns and it didn't work.

redpajama_set_name: RedPajamaStackExchange


text:
Q: gnuplot matrix heat map plot flipped when plot
set terminal png
set output 'plot.png'
plot 'matrix.txt' matrix with image

  9  3  3  4
  3  1  1  7
  8  9  1  8
  7  3  9  5

I get

Do you see, its rotated / flipped. How align it with data?
I found Rotating a plot in gnuplot but solution does not apply here.

A: Are you asking how to invert the direction of the y axis?
set yrange [*:*] reverse
plot 'matrix.txt' matrix with image

Or if you want to invert the y coordinates of the matrix but leave the orientation of other plot elements unchanged
plot 'matrix.txt' using ($1):(-$2):($3) matrix with image


text:
Q: Store and object inside an in-memory database I'm trying to store an object Ficheiro inside my in-memory database. This object contains:
private int version;
private Workbook content;

This is my code I'm using to store in the database:
    HSQLServerUtil.getInstance().start("DBMemoria");

    Ficheiro fich = new Ficheiro();
    fich.setVersion(1);
    fich.setContent(workbook);
    byte[] by = serialize(fich);

    try {
        Blob blob = new SerialBlob(by);
        Session ss = HibernateUtils.newSessionFactory("csheets\\ext\\Hibernate\\hibernate.cfg.xml").openSession();
        ss.beginTransaction();
        ss.getTransaction();
        ss.save(workbook);
        ss.getTransaction().commit();
        ss.close();
    } catch (SQLException ex) {
        System.out.println("ERROR");
    }

This is my hibernate.cfg.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.connection.driver_class">org.hsqldb.jdbcDriver</property>
    <property name="hibernate.hbm2ddl.auto">create</property>
    <property name="hibernate.connection.url">jdbc:hsqldb:file:C:\Users\Adam\Documents\NetBeansProjects\lapr4_2dd_g1_s2\lib\Version</property>
    <property name="hibernate.connection.username"/>
    <property name="hibernate.connection.password"/>
    <mapping resource="csheets/ext/Hibernate/File.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

And finally this is my File.hbm.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <class dynamic-insert="false" dynamic-update="false" mutable="true" name="csheets.ext.Hibernate.Ficheiro" optimistic-lock="version" polymorphism="implicit" select-before-update="false" table="File">
    <id column="version" name="version" type="int" unsaved-value="0">
      <generator class="identity">
        </generator>
    </id>
    <property column="content" name="content" type="blob"/>
    <!--<property column="name" name="name" type="string"/>-->
  </class>
</hibernate-mapping>

I'm getting the following error:
Exception in thread "AWT-EventQueue-0" org.hibernate.MappingException: Unknown entity: csheets.core.Workbook

I've already put an @Entity in the Workbook class. Anybody know whats wrong?
And if possible, can you tell me if i'm doing this right?
Thanks

A: Update your hibernate config to the following to make it work (for development machine):
 <property name="hibernate.hbm2ddl.auto">update</property>


text:
Q: WP All Import manual Cron I am having problem to set up Cron to import stock. In Plugin WP-All Import i have two urls. One which starts import, another one is checking process and if it's stuck it kicks it back on.
I'm runing website on cpanel and i tried everything i found on internet. I keep getting 503 error. But when i go to link it works. Do you have any expiriences with WP All import and C-panel cron anyone?
My last settings i tried:

But i got 503 error.
Thanks in advance

A: You can try like this:
wget -q -O /dev/null "https://example.com/wp-load.php?import_key=123xyz&import_id=YOURID&action=trigger"
From the documentation
Each import has two cron URLs – a trigger URL, and a processing URL.
The trigger URL will look something like this:
http://YOUR-WEBSITE.com/wp-load.php?import_key=[YOUR_SECRET_KEY]&import_id=[YOUR_IMPORT_ID]&action=trigger
The processing URL will look something like this:
http://YOUR-WEBSITE.com/wp-load.php?import_key=[YOUR_SECRET_KEY]&import_id=[YOUR_IMPORT_ID]&action=processing
You can find your secret key on the All Import -> Settings screen, and the import ID on the Manage Imports screen.
If you want to run your import every 24 hours, you should run the trigger URL every 24 hours. If you want to run your import once per week, you should run the trigger URL every week.
The processing URL should be run every two minutes because it may not finish your import in one run. The reason is that many hosts have maximum script execution times in place, so its only possible for the processing script to finish only a small percentage of your import before it is timed out.
If this is the case and the processing script is run again after two minutes, it checks to see if your import is finished, or if there's still work to be done. If there's work to be done, it will import posts for as long as it can, or two minutes, whichever is longer.
Then, on the next run of the processing script, it will see if more work needs to be done on the import – and if so, it will do it. If not, it will "untrigger" the import. And now the processing script will have no effect until the import is triggered again by the next run of the trigger script.
Setting Up Cron Jobs
The instructions for setting up cron jobs vary across hosts. Commonly, you can do it in your web hosting control panel.
To create a cron job that hits the cron URLs, commonly the wget command is used. Examples are on the Manage Imports -> Cron Scheduling screen of
WP All Import.
Below are a few cron command examples (not all options work with all hosts, ask your host for help as needed):
wget --spider "http://YOUR-WEBSITE.com/wp-load.php?import_key=[YOUR_SECRET_KEY]&import_id=[YOUR_IMPORT_ID]&action=trigger&rand="$RANDOM
Bash
wget -q -O - "http://YOUR-WEBSITE.com/wp-load.php?import_key=[YOUR_SECRET_KEY]&import_id=[YOUR_IMPORT_ID]&action=trigger&rand="$RANDOM
Bash
curl "http://YOUR-WEBSITE.com/wp-load.php?import_key=[YOUR_SECRET_KEY]&import_id=[YOUR_IMPORT_ID]&action=trigger&rand="$RANDOM
Bash
lynx "http://YOUR-WEBSITE.com/wp-load.php?import_key=[YOUR_SECRET_KEY]&


text:
Q: How to get access token from FB.login method in javascript SDK I need to get the access token from FB.login method in Javascript SDK. My login code is
FB.login(function(response) {
    if (response.session) {
        if (response.perms) {

        } else {
            // user is logged in, but did not grant any permissions
            alert("No Permission..");
        }
    } else {
        // user is not logged in
        alert("Please login to facebook");
    }
}, {perms:'read_stream,publish_stream,offline_access'});

Is there any way to get access token? I am able to get the access token using PHP.

A: If you are already connected, simply type this in the javascript console:
FB.getAuthResponse()['accessToken']

A: https://developers.facebook.com/docs/facebook-login/login-flow-for-web/
{
    status: 'connected',
    authResponse: {
        accessToken: '...',
        expiresIn:'...',
        signedRequest:'...',
        userID:'...'
    }
}

FB.login(function(response) {
    if (response.authResponse) {
        // The person logged into your app
    } else {
        // The person cancelled the login dialog
    }
});

A: response.session doesn't work anymore because response.authResponse is the new way to access the response content after the oauth migration.Check this for details:
SDKs & Tools › JavaScript SDK › FB.login

A: You can get access token using FB.getAuthResponse()['accessToken']:
FB.login(function(response) {
   if (response.authResponse) {
     var access_token =   FB.getAuthResponse()['accessToken'];
     console.log('Access Token = '+ access_token);
     FB.api('/me', function(response) {
     console.log('Good to see you, ' + response.name + '.');
     });
   } else {
     console.log('User cancelled login or did not fully authorize.');
   }
 }, {scope: ''});

Edit:
Updated to use Oauth 2.0, required since December 2011. Now uses FB.getAuthResponse();
If you are using a browser that does not have a console, (I'm talking to you, Internet Explorer) be sure to comment out the console.log lines or use a log-failsafe script such as:
if (typeof(console) == "undefined") { console = {}; }
if (typeof(console.log) == "undefined") { console.log = function() { return 0; } }

A: response.session.access_token doesn't work in my code. But this works:
response.authResponse.accessToken
     FB.login(function(response) { alert(response.authResponse.accessToken);
     }, {perms:'read_stream,publish_stream,offline_access'});

A:

window.fbAsyncInit = function () {
    FB.init({
        appId: 'Your-appId',
        cookie: false,  // enable cookies to allow the server to access
        // the session
        xfbml: true,  // parse social plugins on this page
        version: 'v2.0' // use version 2.0
    });
};

// Load the SDK asynchronously
(function (d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

function fb_login() {
    FB.login(function (response) {

        if (response.authResponse) {
            console.log('Welcome!  Fetching your information.... ');
            //console.log(response); // dump complete info
            access_token = response.authResponse.accessToken; //get access token
            user_id = response.authResponse.userID; //get FB UID

            FB.api('/me', function (response) {
                var email = response.email;
                var name = response.name;
                window.location = 'http://localhost:12962/Account/FacebookLogin/' + email + '/' + name;
                // used in my mvc3 controller for //AuthenticationFormsAuthentication.SetAuthCookie(email, true);
            });

        } else {
            //user hit cancel button
            console.log('User cancelled login or did not fully authorize.');

        }
    }, {
        scope: 'email'
    });
}

<fb:login-button scope="public_profile,email" onlogin="fb_login();">
                </fb:login-button>

A:

window.fbAsyncInit = function () {
    FB.init({
        appId: 'Your-appId',
        cookie: false,  // enable cookies to allow the server to access
        // the session
        xfbml: true,  // parse social plugins on this page
        version: 'v2.0' // use version 2.0
    });
};

// Load the SDK asynchronously
(function (d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

function fb_login() {
    FB.login(function (response) {

        if (response.authResponse) {
            console.log('Welcome!  Fetching your information.... ');
            //console.log(response); // dump complete info
            access_token = response.authResponse.accessToken; //get access token
            user_id = response.authResponse.userID; //get FB UID

            FB.api('/me', function (response) {
                var email = response.email;
                var name = response.name;
                window.location = 'http://localhost:12962/Account/FacebookLogin/' + email + '/' + name;
                // used in my mvc3 controller for //AuthenticationFormsAuthentication.SetAuthCookie(email, true);
            });

        } else {
            //user hit cancel button
            console.log('User cancelled login or did not fully authorize.');

        }
    }, {
        scope: 'email'
    });
}

<fb:login-button scope="public_profile,email" onlogin="fb_login();">
                </fb:login-button>


text:
Q: Setting TextField Value State in "sap.ui.model.SimpleType.extend" I am trying to add validation for time using regular expression for a column inside my table. First I have added a column,please find the code below:
oTableFileContents.addColumn(
    new sap.ui.table.Column("Time")
    .setTemplate(
        new sap.ui.commons.TextField({
            editable:true,
            valueState : sap.ui.core.ValueState.Error,
            tooltip:""
        })
        .bindProperty("value","Time",new sap.myproject.Time())
    )
    .setLabel(
        new sap.ui.commons.Label({
            text : "Time"
        })
    )
);

Here, by default I am setting ValueState of each TextField to "Error" so that each blank entry is in error state. And while assigning model I have to set each valid entry to "Success". For that I am defined my extended class as :
sap.ui.model.SimpleType.extend("sap.myproject.Time", {
    formatValue: function(oValue) {
        var re = /^([0-1]\d):([0-5]\d)\s?(?:AM|PM)?$/i;
        if(oValue!=null){
            if(re.test(oValue)) {
                // this.setEditable(false);    //ERROR
                //this.setValueState(sap.ui.core.ValueState.Success);   //ERROR
                alert("Success");
            }
        }

        return oValue;
    },

    parseValue: function(oValue) {
        return oValue;
    },

    validateValue: function(oValue) {}
});

However in above code I am unable to set TextField's state to "Success". May be I am unable to get reference to my TextField. Can anyone help me out to set this Valuestate? Any help/suggestion would be appreciated.  Thanks, Kunal.

A: Please no, do never try to attempt to reference a UI control from within your formatter, ever! :-)
Simply throw a sap.ui.model.FormatException and the framework will do the rest for you:
// ...snip...
formatValue: function(oValue) {
    var re = /^([0-1]\d):([0-5]\d)\s?(?:AM|PM)?$/i;
    if(oValue!=null){
        if(!re.test(oValue)) {
            throw new sap.ui.model.FormatException("Value " + oValue + " is not in a valid Date format");
        }
    }
    //optional, if you don't want empty/null dates
    else {
        throw new sap.ui.model.FormatException("Date cannot be null or empty");
    }

    return oValue;
},
// ...snip...

EDIT: In order to have a visual clue of a format or validation error, you should attach to the format and validation eventhandlers in your controller's onInit event handler:
sap.ui.getCore().attachFormatError(function (oEvent) {
  oEvent.getParameter("element").setValueState(sap.ui.core.ValueState.Error);
});
sap.ui.getCore().attachValidationError(function (oEvent) {
  oEvent.getParameter("element").setValueState(sap.ui.core.ValueState.Error);
});
sap.ui.getCore().attachValidationSuccess(function (oEvent) {
  oEvent.getParameter("element").setValueState(sap.ui.core.ValueState.None);
});


text:
Q: Stata - How to Generate Random Integers I am learning Stata and want to know how to generate random integers (without replacement).  If I had 10 total rows, I would want each row to have a unique integer from 1 to 10 assigned to it.  In R, one could simply do:
sample(1:10, 10)

But it seems more difficult to do in Stata.  From this Stata page, I saw:
generate ui = floor((b-a+1)*runiform() + a)

If I substitute a=1 and b=10, I get something close to what I want, but it samples with replacement.
After getting that part figured out, how would I handle the following wrinkle: my data come in pairs.  For example, in the 10 observations, there are 5 groups of 2.  Each group of 2 has a unique identifier.  How would I arrange the groups (and not the observations) in random order?  The data would look something like this:
obs   group  mem     value
1     A      x       9345
2     A      y       129
3     B      x       251
4     B      y       373
5     C      x       788
6     C      y       631
7     D      x       239
8     D      y       481
9     E      x       224
10    E      y       585

obs is the observation number.  group is the group the observation (row) belongs to.  mem is the member identifier in the group.  Each group has one x and one y in it.

A: First question:
You could just shuffle observation identifiers.
set obs 10
gen y = _n
gen rnd = runiform()
sort rnd

Or in Mata
jumble(1::10)

Second question: Several ways. Here's one.
gen rnd = runiform()
bysort group (rnd): replace rnd = rnd[1]
sort rnd

General comment: For reproducibility, set the random number seed beforehand.
set seed 2803

or whatever.


text:
Q: How to reinstall nginx if I deleted /etc/nginx folder (Ubuntu 14.04)? I'm trying to reinstall nginx, but I have this
nginx -t

nginx: [alert] could not open error log file: open()
"/var/log/nginx/error.log" failed (2: No such file or directory)
2015/01/25 16:18:01 [emerg] 1400#0: open() "/etc/nginx/nginx.conf"
failed (2: No such file or directory)
nginx: configuration file /etc/nginx/nginx.conf test failed

How to install and start nginx if I removed all the nginx folders?

A: Login as root or:
sudo su -

Then uninstall nginx:
apt-get purge nginx nginx-common nginx-full

And then install it:
apt-get install nginx

The other way is to run sudo command with -H:
sudo -H apt-get purge nginx nginx-common nginx-full
sudo -H apt-get install nginx

A: Try:
sudo aptitude purge nginx && sudo aptitude install nginx

This code will remove and reinstall Nginx

A: apt-get --purge remove nginx-*
apt-get install nginx


text:
Q: EF Dynamic contains does not work as expected I'm using the EntityFramework and the library 'System.Linq.Dynamic.Core' for dynamically selecting records based upon an array of values.
It works fine for int[] but it returns funky SQL with string[].
var whereQuery = _context.Registrations.AsQueryable();

int[] intArray = new[] {1, 2, 3};
string[] array = new[] {"A001", "D444"};

whereQuery = whereQuery.Where($"@0.Contains(RegistrationId)", intArray);
whereQuery = whereQuery.Where($"@0.Contains(Code)", array);

When debugging I see it generated the following SQL statment
...
FROM [dbo].[Registrations] AS [Extent1]
WHERE ([Extent1].[RegistrationId] IN (1, 2, 3))
AND (( CAST(CHARINDEX([Extent1].[Code], N'A001') AS int)) > 0)

For the int[] it generates the correct / expected "IN-statement".
For the string[] it only checks for the first value from the array. I would expect:
AND ([Extent1].[Code] IN (N'A001', N'D444'))

Versions :
System.Linq.Dynamic.Core v1.0.14.0  (runtime v4.0.30319)
EntiftyFramework  v6.0.0.0
What I am I missing?

A: using List<string> instead of an string[] solves the problem.
For more information also see :
https://github.com/StefH/System.Linq.Dynamic.Core/issues/61

This is not a bug.
The reason is that you test fails because you provide an array in the
  Where clause as the params.. This actually means that if you provide
  an array like { "A001", "D444" }, the code tries to replace @0 by "A001",
  and tries to replace @1 by "D444" and so on. But you only have defined
  @0.

Reply to "Not a bug" above.
Yes, my sample displays two times @0. This is just sample code that I copied. The error remains even when using only 1 parameter.


text:
Q: Query issue in bulk file I am trying to query the data from the .log file. All schema is perfectly same as the file, but still my query gives a response that no row is effected. The following is my .log file structure:
date-time,client-ip,client-hostname,server-ip,server-hostname,source-context,connector-id,source,event-id,internal-message-id,message-id,recipient-address,recipient-status,total-bytes,recipient-count,related-recipient-address,reference,message-subject,sender-address,return-path,message-info,directionality,tenant-id,original-client-ip,original-server-ip,custom-data
2017-08-23T00:00:08.631Z,10.10.30.112,xyz.domain.COM,172.16.0.25,ISIL1,08D4E23F10F7AE79;2017-08-23T00:00:05.760Z;0,ISB\Default ISBEX,SMTP,RECEIVE,702862,<secureMailer.d-347bf50db40440f6bbed36d4c4602181@horizonblue.com>,sasasda@xyz.COM;asadad@xyz.COM;mubashar@yxz.COM,134,3,Secure Message Delivery,secureMailer@horizonblue.com,secureMailer@horizonblue.com,0cI: ,Originating,15.0.30.5,15.1.0.20,S:PurportedSender=Horizon_ACH@horizonblue.com;S:FirstForestHop=as.xyz.COM
Following is my Sql schema:
CREATE TABLE [dbo].[LogTest]
(
  [date-time] VARCHAR(max) NULL,
  [client-ip] VARCHAR(max) NULL,
  [client-hostname] VARCHAR(max) NULL,
  [server-ip] VARCHAR(max) NULL,
  [server-hostname] VARCHAR(max) NULL,
  [source-context] VARCHAR(max) NULL,
  [connector-id] VARCHAR(max) NULL,
  [source] VARCHAR(max) NULL,
  [event-id] VARCHAR(max) NULL,
  [internal-message-id] VARCHAR(max) NULL,
  [message-id] VARCHAR(max) NULL,
  [recipient-address] VARCHAR(max) NULL,
  [recipient-status] VARCHAR(max) NULL,
  [total-bytes] VARCHAR(max) NULL,
  [recipient-count] VARCHAR(max) NULL,
  [related-recipient-address] VARCHAR(max) NULL,
  [reference] VARCHAR(max) NULL,
  [message-subject] VARCHAR(max) NULL,
  [sender-address] VARCHAR(max) NULL,
  [return-path] VARCHAR(max) NULL,
  [message-info] VARCHAR(max) NULL,
  [directionality] VARCHAR(max) NULL,
  [tenant-id] VARCHAR(max) NULL,
  [original-client-ip] VARCHAR(max) NULL,
  [original-server-ip] VARCHAR(max) NULL,
  [custom-data] VARCHAR(max) NULL
)

  Bulk
      Insert LogTest
      From 'C:\Users\zz\Desktop\asy.log'
      with
      (
      Fieldterminator = ',',

      Rowterminator = '/t'
      )

A: The sample data contains different number of columns per row. row one, the headers, contains 26 columns while the second row, the data contains 22 columns only. Hence, if you add four more columns to the second row and accept the default RowTerminator, your code is OK.
date-time,client-ip,client-hostname,server-ip,server-hostname,source-context,connector-id,source,event-id,internal-message-id,message-id,recipient-address,recipient-status,total-bytes,recipient-count,related-recipient-address,reference,message-subject,sender-address,return-path,message-info,directionality,tenant-id,original-client-ip,original-server-ip,custom-data
2017-08-23T00:00:08.631Z,10.10.30.112,xyz.domain.COM,172.16.0.25,ISIL1,08D4E23F10F7AE79;2017-08-23T00:00:05.760Z;0,ISB\Default ISBEX,SMTP,RECEIVE,702862,<secureMailer.d-347bf50db40440f6bbed36d4c4602181@horizonblue.com>,sasasda@xyz.COM;asadad@xyz.COM;mubashar@yxz.COM,134,3,Secure Message Delivery,secureMailer@horizonblue.com,secureMailer@horizonblue.com,0cI: ,Originating,15.0.30.5,15.1.0.20,S:PurportedSender=Horizon_ACH@horizonblue.com;S:FirstForestHop=as.xyz.COM,23,24,25,26

create TABLE #LogTest
(
[date-time] VARCHAR(max) NULL,
[client-ip] VARCHAR(max) NULL,
[client-hostname] VARCHAR(max) NULL,
[server-ip] VARCHAR(max) NULL,
[server-hostname] VARCHAR(max) NULL,
[source-context] VARCHAR(max) NULL,
[connector-id] VARCHAR(max) NULL,
[source] VARCHAR(max) NULL,
[event-id] VARCHAR(max) NULL,
[internal-message-id] VARCHAR(max) NULL,
[message-id] VARCHAR(max) NULL,
[recipient-address] VARCHAR(max) NULL,
[recipient-status] VARCHAR(max) NULL,
[total-bytes] VARCHAR(max) NULL,
[recipient-count] VARCHAR(max) NULL,
[related-recipient-address] VARCHAR(max) NULL,
[reference] VARCHAR(max) NULL,
[message-subject] VARCHAR(max) NULL,
[sender-address] VARCHAR(max) NULL,
[return-path] VARCHAR(max) NULL,
[message-info] VARCHAR(max) NULL,
[directionality] VARCHAR(max) NULL,
[tenant-id] VARCHAR(max) NULL,
[original-client-ip] VARCHAR(max) NULL,
[original-server-ip] VARCHAR(max) NULL,
[custom-data] VARCHAR(max) NULL
)

  Bulk
      Insert #LogTest
      From 'C:\test.log'
      with
      (
      Fieldterminator = ','
--      ,Rowterminator = '/r/n'
      )

select * from #LogTest

UPDATE
If some rows are nulls, then you may Bulk Insert into a temporary one-column table before the actual table. from the temp table ready only the non-null rows, parse through the columns and output them to the actual table.
Create table #Temp (LongColumn Varchar(max))
BULK INSERT #Temp FROM 'C:\Test.Log';

with tmp as(
    select ROW_NUMBER()over(order by (select null)) as RowNo,
            LongColumn
    from #Temp as a
    WHERE a.LongColumn is NOT NULL
    ), cols as(
    select  a.RowNo
            , ROW_NUMBER() over(partition by RowNo order by (select null)) as ColNo
            , b.value
    from tmp as a
    cross apply STRING_SPLIT(a.LongColumn, ',') as b
)insert into #LogTest
select
        [1], [2], [3], [4], [5], [6], [7], [8], [9], [10]
        ,[11], [12], [13], [14], [15], [16], [17], [18], [19], [20]
        ,[21], [22], [23], [24], [25], [26]
from
(
  select RowNo, value, ColNo
  from cols
) src
pivot
(
  max(value)
  for ColNo in ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10]
        ,[11], [12], [13], [14], [15], [16], [17], [18], [19], [20]
        ,[21], [22], [23], [24], [25], [26])
) p
order by p.RowNo
;


text:
Q: My external javascript JQUERY doesn't work on chrome or other browser The html file is
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>My Website /title>
<link rel='stylesheet' type='text/css' href='stylesheet4.css'>
<link rel='stylesheet' type='text/css' href='http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css'>
</head>
<body>
<!--other code -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="script3.js"></script>
</body>
</html>

and my script3.js file is
$(function(){

  "use strict";
    $('#checkOut').click(function(){
        var time=2;
         alert("The time is "+time+"!");
    // more code
});

how am I linking it wrong?
when i used jfiddle to test my code, the alert works when i click the button. however, i'm using notepad++ and i'm not sure what I'm doing wrong.

A: I see two issues, and something else you should fix.
In the script3.js, you have a missing });. So it should be:
$(function(){
  "use strict";
    $('#checkOut').click(function(){
        var time=2;
        alert("The time is "+time+"!");
        // more code
    });
});

The title tag is not formatted correctly:
<title>My Website /title>

Needs to be:
<title>My Website </title>

EDIT: Example:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>My Website </title>
        <link rel='stylesheet' type='text/css' href='stylesheet4.css'>
        <link rel='stylesheet' type='text/css' href='http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css'>
    </head>
    <body>
        <!--other code -->
        <input type="button" id="checkOut" value="check out" />

        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
        <script type="text/javascript" src="script3.js"></script>
    </body>
</html>


text:
Q: Reading full Names in an Archive or ISO image? I recently installed Ubuntu 18.04 on my Laptop wanting to learn Linux. I have some Video Courses in ISO Images; whenever I want to extract files from them, I don't get full names for some reason. I tried to mount it with Furuis ISO Mount Tool but got the same result.
I have to switch to Windows to extract files from the ISO image with full names.

A: What you're seeing is the automatic mounts that get generated by GUI applications and they seem to take the most conservative mount options: msdos.
So for the moment, continue what you're doing until you come to the mount command in your course and then mount the ISO files manually with an iso9660 file system and UNICODE character set like UTF-8.
From man mount:

iocharset=value
     Character set to use for converting between 8 bit characters and 16 bit Unicode characters. The default is iso8859-1. Long filenames are stored on disk in Unicode format.

If man mount doesn't make any sense now neither, ignore it until you reach it in your course material and then come back to this.
Note: Hard to remember as it was probably a long time ago, but you're a N00b again: Don't try to run before you can walk... ;-)


text:
Q: Set Multiple Default Values for People/Group Picker I have a scenario where I would like to set the default values of a people picker to a handful of users based on information in the form. However, if I set the AccountID of the field to a concatenated string of the usernames DOMAIN\account1; DOMAIN\account2; DOMAIN\account3 InfoPath tries to validate the string as being one username.
Is there any way around this? Is it possible to somehow dynamically set multiple default values for a people/group picker?
Thanks in advance for any help.

A: Choices are seperated in SharePoint using ;# instead of ;. Setting your default value to DOMAIN\account1;#DOMAIN\account2;#DOMAIN\account3 should allow you to set multiple default values.
Alternatively there appears to be a solution posted on Technet (link) that may work.
In case the link doesn't work in future here's the contents of that:

Hi Thank you for responding. Sorry for not being as clear as I hoped
  to be.
List A is a customized form library with the people picker as a
  promoted field from the form. Not build from the library. List B is a
  document library, and I am actually creating a new item in this
  library where my default content type is a customized document set.
So my workflow creates an item in the doc library, which is by default
  a document set. I then set the properties of the document set from the
  work flow like you show above. But instead of UPDATE, I am using
  CREATE. This works perfectly fine and how I want it to, except for the
  people picker with multiple selections.
I found a work around where I have a text field with a default value
  (done in InfoPath)
xdMath:Eval(xdMath:Eval(/my:myFields/my:PeoplePicker/pc:Person,
  'concat(pc:AccountId, "; ")'), "..") This sets the text field with the
  multiple users with the display name. I then use this field to set the
  people picker, and it works perfectly.


text:
Q: Which drivers come out the box with Selenium Standalone Server? Here you can see how to make Selenium Standalone Server use the chromedriver. My question is, which drivers are include out the box in the Selenium Standalone Server jar?
Should I use the browsers drivers instead of the drivers included in the Selenium Standalone Server jar?
I know that with Firefox the Selenium Team recommend use the Firefox driver, but what about the others browsers?

A: The post you have pointed out as how to make Selenium Standalone Server use the chromedriver is a demonstration of using Selenium Standalone Server in Grid configuration i.e. through setting up Selenium Grid Hub and Selenium Grid Node.
Selenium 3.x releases doesn't supports any of the drivers out the box in the Selenium Standalone Server jar.
The main reason behind Selenium Team recommending to use the geckodriver (Firefox) and Mozilla Firefox Browser because both geckodriver and Mozilla Firefox Browser follows the W3C Specifications.


text:
Q: How to implement SSL Pinning - Public Key Pinning (Not Certificate Pinning) with Moya in Swift? I went through may blogs on internet but finding issue when implementing it. Blogs like https://betterprogramming.pub/ssl-pinning-with-moya-in-swift-d5a5edae22c2 (using certificate pinning)
Is there anyone who did Public Key Pinning with Moya and can share me the way how I can achieve this.
Thanks in anticipation!

A: After a lot of digging, I found the solution. Implemented using TrustKit. Please refer this link --> https://github.com/datatheorem/TrustKit. For iOS 12+.


text:
Q: Не могу отцентрировать блок, подскажите как правильно центрировать Пытаюсь центрировать и через flex, и через grid, он начинает ездить. А если использую position: absolute, то он просто пропадает. Не обращайте внимания на блок, я его не заполнял контентом потому что не могу его отцентрировать.

.review {
    height: 950px;
    background-color: #F2EBDC;
    font-family: 'Roboto';
}

h1 {
    font-size: 48px;
    color: #594740;
    font-weight: 600;
    text-align: center;
    position: absolute;
    left: 0;
    right: 0;
    white-space: nowrap;
    margin-top: -90px;
}

.first-review__line {
    background-color: #8F9471;
    width: 100%;
    height: 35px;
    top: 120px;
    position: relative;
}

.second-review__line {
    background-color: #8F9471;
    width: 100%;
    height: 95px;
    top: 780px;
    position: relative;
}

.review__container {
}

.review__slider {
    position: relative;
    top: 80px;
}

.review__block {
    margin-left: 250px;
    width: 815px;
    height: 530px;
    background: #8F9471;
    box-shadow: -9px 11px 4px rgba(0, 0, 0, 0.25);
}

            Отзывы клиентов

A: Вы же в стилях для review__block указали отступ слева как margin-left: 250px;
Замените на margin: 0 auto;
В этом случае отступы сверху и снизу будут нулевые, а слева и справа - auto, то есть одинаковые автоматические. Блок встанет посередине.


text:
Q: notifyItemChanged(position) is not updating the view What I am doing:
RecyclerView -> calling new fragment onRecyclerView Item Click(through interface) -> updaing somthing in new fragment -> closed the current fragment-> trying to update the selected item data. (calling notifiyItemChanged(position))
But data is not updated on UI side, I checked ArrayList is updating (through debugger).
Reason: notifiyItemChanged(position) is not calling the onBindViewHolder()
Code:
RecyclerView Intilization:
mLayoutGridManager = new GridLayoutManager(getActivity(), 4);
     mTableAdapter = new TableAdapter(getActivity(),    RoomFragment.this);
    mTableRecyclerView.setAdapter(mTableAdapter);
    mTableRecyclerView.setHasFixedSize(false);
    mTableRecyclerView.setLayoutManager(mLayoutGridManager);

Calling Fragment:
tableOrderDetails = TableOrderDetailsFragment.newInstance(table,position);
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();

        transaction.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left, R.anim.enter_from_right, R.anim.exit_to_left);
        transaction.add(R.id.fragment_container, tableOrderDetails);
        transaction.addToBackStack(CustomerListFragment.TAG);
        transaction.commitAllowingStateLoss();

//updating the views
public void updateTable(int tableID, String tableStatus, int position){

             if (data.get(position).getTableID()==tableID && tableStatus!=null){
                data.get(position).setCurrentTableStatus(tableStatus);

                 notifyItemChanged(position);
             }
      }

#Possible Reason:
Views are not attached.
Solution Tried:

*

*notifyDataSetChanged()

*runOnUiThred

*call update function using Looper.


text:
Q: React Native Project BUILDS Succesfull(with deprecated warning) and opens in my emulator, but keeps loading forever I used yarn to install the packages, Im using typescript, my index is JS.
I'm getting a white screen with the load symbol on the emulator..
Thanks for the ones helping
Here's what Im getting:
info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag.
(node:41396) Warning: Accessing non-existent property 'padLevels' of module exports inside circular dependency
(Use `node --trace-warnings ...` to show where the warning was created)
Jetifier found 1123 file(s) to forward-jetify. Using 4 workers...
info JS server already running.
info Installing the app...

> Task :app:installDebug
09:49:22 V/ddms: execute: running am get-config
09:49:22 V/ddms: execute 'am get-config' on 'emulator-5554' : EOF hit. Read: -1
09:49:22 V/ddms: execute: returning
Installing APK 'app-debug.apk' on 'Pixel_2_API_28(AVD) - 9' for app:debug
09:49:22 D/app-debug.apk: Uploading app-debug.apk onto device 'emulator-5554'
09:49:22 D/Device: Uploading file onto device 'emulator-5554'
09:49:22 D/ddms: Reading file permision of C:\Users\Daniel\CalcSol\android\app\build\outputs\apk\debug\app-debug.apk as: rwx------
09:49:22 V/ddms: execute: running pm install -r -t "/data/local/tmp/app-debug.apk"
09:49:24 V/ddms: execute 'pm install -r -t "/data/local/tmp/app-debug.apk"' on 'emulator-5554' : EOF hit. Read: -1
09:49:24 V/ddms: execute: returning
09:49:24 V/ddms: execute: running rm "/data/local/tmp/app-debug.apk"
09:49:24 V/ddms: execute 'rm "/data/local/tmp/app-debug.apk"' on 'emulator-5554' : EOF hit. Read: -1
09:49:24 V/ddms: execute: returning
Installed on 1 device.

Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.2/userguide/command_line_interface.html#sec:command_line_warnings

BUILD SUCCESSFUL in 29s
141 actionable tasks: 2 executed, 139 up-to-date
info Connecting to the development server...
info Starting the app on "emulator-5554"...
Starting: Intent { cmp=com.calcsol/.MainActivity }'''

A: You can try:

*

*Delete node_modules and re-install

*Go to your android folder and delete the file .idea

*In Android Studio: file > Invalidate Caches / Restart and select 'Invalidate and Restart'


text:
Q: Jquery animation quandry I am having a problem where a div slides into view, but has a piece missing from it that only shows up after the sliding action stops.
The div is materializing from 'display:none', and here is the relevant jquery:
$('#maincontent').show('slide', { direction: 'left' }, 500);
})

You can view the live page and the source here:
http://joepolitic.com/sites/AlmostFamous.html
Any suggestions?
Thanks

A: I think the problem has to do with how the browser renders margin and padding. H1 and P tags have default values for margin and padding.
The background will show up if you remove the h1 and p tags, or if you style out the margin and padding like this:
h1,p{margin:0;padding:0;}

A: It looks like the section 8.3.1 of the CSS1 specification is relevant: the margin of the  #maincontent div and the margin of the h1 are collapsing while the #maincontent div is positioned relatively in the jQuery-generated ui-effect-wrapper.
http://www.w3.org/TR/CSS2/box.html#collapsing-margins
Adding 1-pixel padding on the #maincontent div prevents the margins collapsing, and fixes the problem while allowing you to keep margins around the h1.
#maincontent {
    padding: 1px;
}


text:
Q: Linq to SQL writing translatable functions I'm pretty sure the answer to this is "you can't do that" or "No, no, you misunderstand...", but:
I have a linq class, thing,  which will happily execute this:
 var thingsWithAandB = from t in db.things
                       where t.propA.HasValue && t.propB.HasValue
                       select t;

But I do this a lot, and so I want:
partial class thing
{
    public bool hasAandB
    {
        get
        {
            return propA.HasValue && propB.HasValue;
        }
    }
}

and then:
var thingsWithAandB = from t in db.things where t.hasAandB select t;

But of course, when I do this, I get "Can't translate that into SQL" errors. And I understand that this is because calling methods in the middle of SQL queries isn't possible, since my code and the database are separate.
What's the way to do this? Is it impossible?

A: It is perfectly possible. Damien Guard (damieng.com) has a sample on his blog showing how to do that.
http://damieng.com/blog/2009/06/24/client-side-properties-and-any-remote-linq-provider

A: You can use extension methods:
public static class MyExtensions{
    public static bool HasAandB(this thing t){
        return t.propA.HasValue && t.propB.HasValue;
    }
}

and then use it:
var thingsWithAandB = from t in db.things
                   where t.HasAandB()
                   select t;

EDIT
Sorry, this will probably give you the same exception...


text:
Q: How to scale aws ec2 cluster based on java application memory I have a java application which is deployed on aws ec2 cluster. I have auto scaling configured based on cpu usage but the problem is application is not CPU intensive but is IO intensive, CPU usage is 20% on an average, so when traffic increases it is not able to send all the messages in real time causing buffering. This is causing delay in arrival of messages in downstream systems.
How can i auto scale my cluster based on incoming traffic and heap usage of deployed application?

A: you should use custom metrics for this purposes
CloudWatch does not collect memory consumption by default. To enable this you should use custom metrics script and then you be able to change autoscaling group behavior corresponding to memory consumption chages or any other event which you need to monitor and react

A: You can create a bash script, running with cron, that collect the Java heap memory usage and incoming connections, and then sends the to cloudwatch custom metrics.
How to collect to memory and disk stats from AWS ec2 instances
Examples in Perl
And then Alert and Auto scale based on those custom metrics


text:
Q: Is it an 'original sin' to do init work in __new__? If so, how best to handle run once init for singletons? I have a class that has the standard python singleton form I use.  It also inits a single value, but rather than init it in each instance, I init it in __new__() when I do the singleton handling.  Is this the pythonic way to do it?  If not, how else can I?
class Foo(object):
    _inst = None
    def __new__(cls, val):
        if Foo._inst is None:
            Foo._inst = super(Foo, self).__new__(cls)
            Foo._inst.val = val
        return Foo._inst

This is obviously the simplified form.  I have used the construction of waiting till __init__() to check and set Foo._inst to handle run once init for a singleton, but that seems ripe for synchronization errors in a multithreaded situation.  For situations where there're no values that can get corrupted in the existing instance if __init__() is run again, there's no harm in putting the init in __init__(), except that you are running code that effectively does nothing when you don't need to, but there are often corruptible state values I don't want to overwrite.  I know singletons are evil too, but some times, they are the best solution (like defining special use types I want to be able to check with is).
This seems like the best solution I can come up with, but I feel dirty initializing instance values in __new__().  Does anyone have ideas on how to handle this better?

A: You can always use global variables instead of singletons.  Example for a class with three different instances:
class _Ternary(object):
    """Internal class.  Don't instantiate!"""
    def __init__(self, value):
        self.value = value

ternary_0 = _Ternary(0)
ternary_1 = _Ternary(1)
ternary_2 = _Ternary(2)

def ternary(value):
    """Factory function to request a "ternary" instance."""
    return {0: ternary_0, 1: ternary_1: 2: ternary_2}[value]

This is straight-forward and will avoid the pain of singletons.

A: To answer the first question:
Singletons are not used too often in Python as they are not really required.
To answer the second:
If you think you really need them, there is slightly cleaner, similiar pattern called "Borg" which is sometimes used, see: the Borg design pattern
If you need to just share some attributes between instances and don't need full-blown singleton (which can be instantiated once) you may simply use class attributes like so:
class Foo( object ):
    val = ...

    def __init__( self ):
        ...

Then all instances will share the same value of the "val" attribute.

A: There's no better way to create singletons. If you're going for it (and three-valued logic is about the only example I can think of where this makes sense), then you can do it the way you are.


text:
Q: Command for enabling networking? What is the command for enabling networking and wireless using command line?
I have made a script that delays the startup apps for quicker boot times.
I have learned that disabling networking also helps in a quicker boot time.
I would like to add a command that shall enable networking and wireless in the shell script.

A: Are you looking for sudo service networking start ?
I believe network-manager handles the networking and interface on Ubuntu 12.04 so it should be like:
sudo service network-manager start

[EDIT]
Just an update in support of my comment below, for automating SUDO when piping the password to it from external source use:
echo "password" | sudo -S service network-manager start

Which will not ask for the password interactively.
-S Switch here make sudo to read the password from standard input and not from terminal.

A: When using NetworkManager (its service running) there is no need for sudo to enable/disable networking.
Use nmcli:
nmcli networking {on | off | connectivity}

connectivity get network connectivity state (full/none...).
Just for WiFi:
nmcli radio wifi {on | off}

A: to start network
sudo /etc/init.d/networking start

to stop
sudo /etc/init.d/networking stop

to restart
sudo /etc/init.d/networking restart

Source


text:
Q: Multiple levels I was reading a tutorial about creating multiple levels, and the below really interested me on how i should go about this.

It may seem natural to make one class per level, with each class
  extending AvoiderGame, and use events to switch between them. So, we
  might have classes named AvoiderGameLevelOne, AvoiderGameLevelTwo,
  etc., and let each one fire off a "NavigationEvent.NEXT_LEVEL" when
  appropriate. Presumably then the document class would listen for this
  event, and when it heard it, it would run "playScreen = new
  AvoiderGameLevelTwo()" (or whichever level was appropriate), and pass
  through all the information such as score and time to this new
  playScreen instance.

I'm not entirely sure on how to go about this. I put my stage, which is an array of tiles in a class called level1, level2, etc and had it extend my main class. Just to check if everything works, I added a public static var called levelArray in my main, which is a blank array. Then in level1, I pushed my array into levelArray.
So for my level1 class
package  {

    public class Level1 extends Main {

        public var floor1:Array = new Array();
        floor1[0] = [2,1,1,1,1,1,2];
        floor1[1] = [1,1,1,1,1,1,1];
        floor1[2] = [1,1,1,2,1,1,1];
        floor1[3] = [1,1,1,1,1,1,1];
        floor1[4] = [1,1,1,2,1,1,1];
        floor1[5] = [1,1,1,1,1,1,1];
        floor1[6] = [2,1,1,1,1,1,2];

        public function Level1() {

            Main.levelArray.push(floor1);
        }

    }

}

Doesn't seem to be working. levelArray comes up as blank. Might be because the two classes aren't communicating with each other correctly? Any ideas if I am approaching this the correct way?

A: I dont know if the rest of your concept is sound, but I think the syntax is off for the part you have shown.  try:
package  {

    public class Level1 extends Main {

        public var floor1:Array = new Array( [2,1,1,1,1,1,2],
                                             [1,1,1,1,1,1,1],
                                             [1,1,1,2,1,1,1],
                                             [1,1,1,1,1,1,1],
                                             [1,1,1,2,1,1,1],
                                             [1,1,1,1,1,1,1],
                                             [2,1,1,1,1,1,2]
                                           );

        public function Level1() {
            Main.levelArray = floor1;
        }
    }

}

EDIT: if the only thing distinct about each level is the array that forms the floor, you may consider the fact that you do not need a new class for each level, just a new array.  you can define the arrays for each level in the class that is super to this one and then just replace them with each progression.


text:
Q: R: transforming character to date with only year and month to apply a dateRange input on a boxplot output in a Shiny app I have dataframe (in the following called df) with the first column df$date being dates with type character, formatted as %Y-%m.
My first question would be: how can I transform the types of all the entries in this column from character to date, keeping the same format with only year and month? I've tried as.Date("2011-08", format(%Y-%m)), as.yearmon("2011-08") (returns a num, but I want a Date), format(as.Date("2011-08"),"%Y-%m"). All didn't work.
The reason I want to change the type of this column is that I want to implement a dateRange input in a Shiny app, ranging from the minimum to the maximum date in the column mentioned above. Maybe there is another solution to this without needing to change the type?
This is my input in the Shiny-App:
box(width = 4, height = "50px",
                 dateRangeInput(inputId = 'dateRange',
                                label = "Period of analysis : ",
                                format = "yyyy-mm",language="en",
                                start = min(df$date),
                                end = max(df$date),
                                startview = "year", separator = " - ")
                 )

I want to have min(df$date) resp. max(df$date) for start and end, but it is not working. Again, the problem seems to be, that df$date has the type chr, e.g. "2011-08".
My Output-Code in the server function of the Shiny-App looks like this:
output$PartPlot <- renderPlot({
       PartPlot_new <- subset(df, date >= input$dateRange[1] & date <= input$dateRange[2])
       boxplot(PartPlot_new[, input$Table2], xlab = "Part", ylab = "Percentage")
     })

As you can see, the goal is to have boxplots from the other columns of df (containing percentages).
Appreciate any help! Thanks in advance.

A: You can transform date string into a date value, with make use of this handy library:
library(anytime)

times <- c("2004-03-21 12:45:33.123456",
           "2004/03/21 12:45:33.123456",
           "20040321 124533.123456",
           "03/21/2004 12:45:33.123456",
           "03-21-2004 12:45:33.123456",
           "2004-03-21",
           "20040321",
           "03/21/2004",
           "03-21-2004",
           "20010101")

anydate(times)
 [1] "2004-03-21" "2004-03-21" "2004-03-21" "2004-03-21" "2004-03-21" "2004-03-21"
 [7] "2004-03-21" "2004-03-21" "2004-03-21" "2001-01-01"

In your case, if you want to convert with %Y-%M format, you can also try:
times <- c("2018-11")
anydate(times)
[1] "2018-11-01"

A: What novica commented is absolutely correct.  Leave your date as a full proper date with year, month, and day, where day can be 1.  Column type will obviously be date.  If you need to show the year and month in a label client-side, take the date value, format as a string and drop off the day.  In your shiny client page where you select the inputs, you can show the year and month "label" but the "value" you pass will be a full date (or you can add the day server-side before using dateRangeInput.


text: Q: In WinRT, loading images in listbox by enabling VirtualizingStackPanel.VirtualizationMode as Recyling, image get blurred I have added items in listbox as 50 images by enabling VirtualizingStackPanel.VirtualizationMode as Recyling. By scrolling the listbox, images in the listbox get blurred. Any one have idea on this to resolve the issue ?


text:
Q: Cannot POST error using Express, Mongoose, EJS (For the solution check the last answer)
I'm creating object with rating system with default value of 0. What I'm trying to do is to update the rating value by choosing one of the options in the <select> dropdown menu. The problem is when I'm submiting the selected value it sends the 'Cannot POST / ...' error.
Here's the app.js code with post and get requests:
// Updating Single Object
app.post('project/:projectId', (req, res) => {
  const project = {};
  project.rating = req.body.rating;

  Project.update({_id: request.params.projectId}, project, (err) =>{
    if(err){
      console.log(err);
      return;
    } else {
      res.redirect('/project/:projectId');
    }
  });
});

// Route To Single Project
app.get('/project/:projectId', (req, res) => {
  const requestedProjectId = req.params.projectId;
  Project.findOne({_id: requestedProjectId}).populate('image_file').exec((err, project) => {
    res.render('project', {
      project: project
    });
  });
});

And the form:
<form action="/project/<%= project.id %>" method="post">
 <select class="" name="rating">
  <option value="0">Rate us</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
  <option value="6">6</option>
  <option value="7">7</option>
  <option value="8">8</option>
  <option value="9">9</option>
  <option value="10">10</option>
 </select>
 <input type="submit" value="Vote">
</form>

I think I'm missing something but can't figure it out.
Thank you in advance.

A: Solved it after 3 hours, realizing I was missing the / before project in the url route.
app.post('project/:projectId', (req, res) => {

A: Just change your url in routes, use  /project/:projectId instead of project/:projectId in app.post() method

A: Maybe instead of:
<form action="/project/<%= project.id %>" method="post">

you should use:
<form action="/project/<%= project._id %>" method="post">


text:
Q: Github actions get trigger in branch when it shouldnt So I have the main branch and I want to be able to deploy to production when ever I have a push or a pull_request and I want to deploy develop environment tag any branch with 'develop', except main.
The following is on my main.yml
name: Create and Upload Prod Container and Deploy to Prod Amazon ECS

on:
  push:
    branches:
      - main
  pull_request:
    branches:
      - main

I am currently in the develop branch as you can see

But when ever I push a commit to the develop branch I am seeing the main.yml is being called. I can tell the main.yml is being called because it is the title "Create and Upload Prod Container and Deploy to Prod Amazon ECS"

A: You are seeing a Pull Request triggering your workflow and it's correct based on what you have in the YML file.
There must be a PR existing that has a base being main and when you push to develop it got synchronized - as you can see in your own attached screenshot.
This is the second part of your YML pull_request: every Pull Request with a base to main will also trigger your workflow.
If you want to just have push to main remove the second part.
Merges of PRs will be working then as those are treated as a push, so your first condition will be met.

A: You provided not valid yml content. Try to correct the indentation. You can check the validity for example here https://onlineyamltools.com/convert-yaml-to-json
name: Create and Upload Prod Container and Deploy to Prod Amazon ECS

on:
  push:
    branches:
      - main
  pull_request:
    branches:
      - main


text:
Q: Please help. I need to add a log file to this multi-threaded rsync script Define source, target, maxdepth and cd to source
 source="/media"
    target="/tmp"
    depth=20
    cd "${source}"

Set the maximum number of concurrent rsync threads
 maxthreads=5

How long to wait before checking the number of rsync threads again
 sleeptime=5

Find all folders in the source directory within the maxdepth level
 find . -maxdepth ${depth} -type d | while read dir
    do

Make sure to ignore the parent folder
 if [ `echo "${dir}" | awk -F'/' '{print NF}'` -gt ${depth} ]
    then

Strip leading dot slash
 subfolder=$(echo "${dir}" | sed 's@^\./@@g')
    if [ ! -d "${target}/${subfolder}" ]
    then

Create destination folder and set ownership and permissions to match source
mkdir -p "${target}/${subfolder}"
chown --reference="${source}/${subfolder}" "${target}/${subfolder}"
chmod --reference="${source}/${subfolder}" "${target}/${subfolder}"
    fi

Make sure the number of rsync threads running is below the threshold
while [ `ps -ef | grep -c [r]sync` -gt ${maxthreads} ]
do
echo "Sleeping ${sleeptime} seconds"
sleep ${sleeptime}
done

Run rsync in background for the current subfolder and move one to the next one
nohup rsync -au "${source}/${subfolder}/" "${target}/${subfolder}/"
    </dev/null >/dev/null 2>&1 &
    fi
    done

Find all files above the maxdepth level and rsync them as well
find . -maxdepth ${depth} -type f -print0 | rsync -au --files-from=- --from0 ./ "${target}/"

A: Thank you for all your help. By adding the -v switch to rsync, I solved the problem.

A: Not sure if this is what you are after (I don't know what rsync is), but can you not just run the script as,
./myscript > logfile.log

or
./myscript | tee logfile.log

(ie: pipe to tee if you want to see the output as it goes along)?
Alternatively...  not sure this is what real coders do, but you could append the output of each command in the script to a logfile, eg:
#at the beginning define the logfile name:
logname="logfile"
#remove the file if it exists
if [ -a ${logfile}.log ]; then rm -i ${logfile}.log; fi
#for each command that you want to capture the output of, use >> $logfile
#eg:
mkdir -p "${target}/${subfolder}" >> ${logfile}.log

If rsync has several threads with names, I imagine you could store to separate logfiles as >> ${logfile}${thread}.log and concatenate the files at the end into 1 logfile.
Hope that is helpful? (am new to answering things - so I apologise if what I post is basic/bad, or if you already considered these ideas!)


text:
Q: How to stub "global" module variables in node.js with Coffeescript without --bare? I have some environment variables from Heroku and for readability, I tend to assign them to global variables for readability:
ACCESS_TOKEN = process.env.ACCESS_TOKEN

Now I'd like change value for that in tests. I have tried rewire and sandboxed-module. However, they are both setting global variables directly, whereas coffeescript variables are wrapped in anonymous function.
Is there any way around this, or do I really have to use --bare if I want to test my code?

A: I'm not familiar with node, but the approach I'd use, and that I've used in other technologies is wrap up globals or external dependencies in an object which can be swapped out for a stub or mock object when needed in test.
Say rather than storing the value in ACCESS_TOKEN you made a herokuEnvironment object and gave it the method accessToken(). Wherever you need to use the properties you inject the object. Then in production that method calls process.env.ACCESS_TOKEN. If you need a safe version to inject into a test situation, you just supply { accessToken: function () {return 'foo';}}


text:
Q: Custom error message for a cell-processor in SuperCSV? I'm using SuperCSV-2.3.1.
Is it possible to have a custom error msg to attach to a cell-processor, so when it fails validation, we get the custom msg in the exception?
Thanks.

A: Yes, but only if you write your own cell processors (see this related question)


text:
Q: recurcive CTE how to use it I want to create a recursive cte by passing a date through it until it reaches final date. Can anyone show me an example of how to do it
I need to pass a starting date and a final date and make a count of how many students there were in every year!
where :date and :finaldate is an input
 with seventeen as
(
    select  count(studentid)
    from students s
    join periodrange p on p.idx = s.periodrangeidx
    where p.validdate between :date and :finaldate
)

I want to have the sum of the students for each year
Would something like this even work or did i dream to far for recrusive CTE

A: You dont need CTE, you can just use a group by and count:
select  count(studentid), extrac(year from p.validatdate) as Year
from students s
join periodrange p on p.idx = s.periodrangeidx
where p.validdate between :date and :finaldate
Group by extrac(year from p.validatdate), studentid


text:
Q: A word for a big, difficult, weird question Is there a word that describes an important question that is difficult to answer? I'm attempting to get permission for something big.

A: Perhaps you can use conundrum. According to Collins:
conundrum
noun

1) a riddle, esp one whose answer makes a play on words
    2) a puzzling question or problem

A: My favorite is:
A thorny problem

[usually before noun] Causing distress, difficulty, or trouble:

*

*a thorny problem for our team to solve

Note the synonym knotty
(Oxford)


text:
Q: Get a Google App Make application open to not only a specific page but also a specific record? How do get a Google App Make application open to not only a specific page/form in Google App Maker but also a specific record within that page?

A: There are different techniques to achieve this behavior and for sure the implementation will depend on your requirements.

*

*if you want your app's URL to display current state and make this URL shareable, then you need to read this: Integration between different Google Appmaker Apps

*if you don't care about shareable URL and you have common datasource for your list and details pages, then you can just update selected record in your list and navigate user to the details page:
// row's or row descendant's onClick event
app.datasources.ItemsList.selectKey(widget.datasource.item._key);
app.showPage(app.pages.ItemDetails);

*

*if you have dedicated datasource for you details page, then your code can look like this:

// row's or row descendant's onClick event
var detailsDs = app.datasources.ItemDetails;
detailsDs.unload();
detailsDs.query.filters._key._equals = widget.datasource.item._key;
app.showPage(app.pages.ItemDetails);

You need to unload details datasource to prevent blinking (showing previous item, if you are viewing item by item). By the way, you can also unload datasource in onDetach event of the details page.


text:
Q: javascript to convert text tree to table I have a textual tree like this
A
:...A1
:   A2
B
:...B1
:   :...B11
:       B12
:       :...B121
:           B122
C
:...C1
    :...C11
        :...C111
            C112

I want to convert it to array like this using regex and javascript
ID,ParentID
A,null
A1,A
A2,A
B,null
B1,B
B11,B1
B12,B1
B121,B12
B122,B12
C,null
C1,C
C11,C1
C111,C11
C112,C11

What should be the most efficient way?


text:
Q: CGI Perl Use of uninitialized value $user in string I have a problem checking if the variables I retrieve with CGI are right.
HTML:
Nombre de Usuario:
<input type="text" id="name" name="user_name" />

Contraseña:
<input type="password" id="password" name="user_password" />

CGI/Perl code:
my $c = CGI->new;
.
.
.
my $user = $c->param('user_name');
my $password = $c->param('user_password');

if($user eq "" || $password eq "") {
        printf "Error";
        exit;
}

The main problem is that if I just do:
print $user;

The output is correct and it prints the value, but in apache error.log, it still says that the variable is uninitialized and then goes into the "if" and exits.
I also tried with "$user" and comparing the strings to undef but nothing.

A: To test whether a variable has a defined value, you should use the 'defined' function:
if (!defined($user) || !defined($password)) { ... }

A: If those parameters have not been passed in by the form then they will be undefined, and you will receive a warning if enabled by "use warnings;".  You can ensure they are defined by providing fallback values for the assignments:
my $user = $c->param('user_name') // "";
my $password = $c->param('user_password') // "";


text:
Q: If $H$ is a Hilbert space, does the coordinate projection $\pi :H\oplus H\rightarrow H$ take closed subspaces to closed subspaces? Here $H\oplus H$ has the product topology, which is induced from the "$\ell^2$-norm" $\|(x,y)\|:=\sqrt{\|x\|^2+\|y\|^2}$. This is indeed a Hilbert space via the inner product $\langle (x,y), (x',y')\rangle := \langle x,x'\rangle + \langle y,y'\rangle$.
Now we have a projection $\pi : H\oplus H \rightarrow H$, given by $(x,y)\mapsto x$. My question is: if $M$ is a closed subspace of $H\oplus H$, then is $\pi(M)$ a closed subspace of $H$?

A: If this were the case, then any closed, densely defined operator on $H$ would automatically be bounded. Indeed, let $A$ be a closed, densely defined operator on $H$ with domain $D(A)$. By definition of a closed operator, the graph
$$\Gamma(A):=\{(x,Ax)\in H\oplus H\,:\,x\in D(A)\}$$
is a closed subspace of $H\oplus H$. If your question had a positive answer, this would imply $\pi(\Gamma(A))=D(A)$ is a closed subspace, so since $A$ is densely defined this means $D(A)=H$ and hence by the closed graph theorem $A$ is bounded.
In particular, we can find explicit counterexamples to your question by taking the graph of any closed, densely defined operator on a Hilbert space. For example,
$$H=L^2(0,1),\quad M=\{(u,v)\in H\oplus H\,:\,u\text{ is weakly differentiable and }u'=v\}.$$

A: No, this need not be the case. If you take $H := {\mathscr l}^2({\mathbb N})$, you can identify the projection $H\oplus H\to H$ with the map $\text{even}: {\mathscr l}^2({\mathbb N})\to {\mathscr l}^2({\mathbb N})$ mapping a sequence $(x_n)_n$ to the sequence $(x_{2n})_n$ of its even parts. Now, consider the subspace $U  := \{(x_n)\in {\mathscr l}^2({\mathbb N})\ |\ x_{2n+1} = n x_{2n}\text{ for all }n\in{\mathbb N}\}$. Then any eventually vanishing sequence belongs to $\text{even}(U)$ but $(1/n)_n\notin \text{even}(U)$.


text:
Q: Is there a way to bind an onFocus Event to a TextField in NativeScript? Apparently I can't find a focus event handler in NativeScript's documentation or API reference of TextFields elements. Am I wrong?
Or, is there a way to introduce the onFocus event extending the existing Nativescript's element?
(I am using typescript without Angular 2)

A: You can use the on method that is mentioned here. I don't know if this is what you are looking for but here is an example:
In XML:
<TextView id="textfield" textWrap="true" tap="textfieldTap"/>

In js file:
var myTextfield = page.getViewById("textfield");

myTextfield.on("tap", function() {
    console.log("Hello from the other side");
});

Also, there is another way to listen to focus event on TextField. As we have the tap="textfieldTap"inside the XML TextField tag, then we can declare a function in the js to listen to that event:
function textfieldTap(args) {
    console.log("Textfield tap " + args.text);
}
exports.textfieldTap = textfieldTap;

A: A PR for adding focus is pending review. Won't be long before you can use it on TextField and TextView elements!


text:
Q: Finite connected groups over a perfect field of characteristic p In 14.4 of "Introduction to Affine Group Schemes" it is proved (!) that if $A$ represents a finite connected group scheme over a perfect field $k$ of characteristic $p$ then $A$ has the form $k[X_{1}, X_{2}, ..., X_{n}] / (X_{1}^{p^{e_{1}}}, ...., X_{n}^{p^{e_{n}}})$. But what about $\mu_{p} = k[X]/(X^{p}-1)$? It is connected but not isomorphic to $k[X]/(X^{p})$ as $k$-groups. They are isomorphic as $k$-schemes.
Does this theorem mean " ...... $A$ has the form $k[X_{1}, X_{2}, ..., X_{n}] / (X_{1}^{p^{e_{1}}}, ...., X_{n}^{p^{e_{n}}})$ up to isomorphism of $k$-schemes"?

A: Others can do this much better than I, but here's what's happening: to describe a group scheme of any kind, you need to talk about not only the underlying space, but also the law of composition on the group. In this case, the kernel of $[p]$ in the muliplicative group, you describe the law of composition by writing down the the comultiplication on the affine ring $k[X]/(X^p)$. This is simply $X\mapsto 1 \otimes X + X \otimes 1 + X \otimes X$.


text:
Q: How to calculate Johnson Noise Voltage? I used a Johnson Noise calculator to find the voltage of in a steel conductor, but it disagreed with the following calculation where $R = \frac{\rho \ L}{A} = \frac{7 \cdot 10^{-7} \ \Omega \ m \ \ 0.001 \ m}{0.001 \ m^2} = 0.0007 \ \Omega$.
$$\begin{align}
V &=k \ TR \\
&= 1.38064852 \cdot 10^{-23} \frac{m^2 kg}{ s^2 K} \times 275 \ K \times 0.0007 \ \Omega\\
&= 2.6577484 \cdot 10^{-24} \ V
\end{align}$$
The calculator in the first line says the scale is of $10^{-9}$ or so which is very different from $10^{-24}$. Which is correct?

A: The equation for Johnson-Nyquist noise is
$$V = \sqrt{4 \ k T \Delta f R }$$
Taking the square root of the value you calculated gives a value much closer to the calculator, $1.6 \cdot 10^{-12} \ V$. (Recalculating with the factor of $4$ added gives $3.3 \cdot 10^{-12} \ V$.)


text:
Q: replaceAll and beginning of line (java) I would like to use String's replaceAll function to delete any char that is not in a given set. I tried
x = x.replaceAll("^[A-Za-z]", "");

However this is not working because when placed at the beginning of the expression, the ^ character has another meaning (match the beginning of a line).
How can I get the behavior I want? I could not find any help on the correct syntax.
Thanks

A: x = x.replaceAll("[^A-Za-z]", "");

It should be inside the brackets.

A: Are you looking for the negation of the range? Then it has to be inside the brackets.
x = x.replaceAll("[^A-Za-z]", "");

More in the Java Doc.


text:
Q: I can't understand the meaning of this sentence "It seemed like weeks went by before you finally asked for my number"
Is that mean he asked numbers quickly or few weeks later?
Excerpt From
Thirteen Reasons Why
Jay Asher
This material may be protected by copyright.

A: I think the person from whom the number was to be asked was eagerly waiting for the other person to ask for his number.
So even if, the person may have asked the number not too later, it seemed to the other person as if he had waited for a long time.
So the word 'seemed like' has been used.

A: The author is referring to the time you asked for his number, and the fact that the author thinks you (seemingly) waited a long time before asking.  The delay is the key sentiment here so maybe he/she was hoping you had asked sooner.


text:
Q: How to get a form value in a controller I am using Spring MVC. How can I get text box value of the following snippet in my controller method?
<form name="forgotpassord" action="forgotpassword" method="POST" >

User: <input type='text' name='j_username' />

  <input type="submit" value="OK" class="btn">

</form>

A: You can use @RequestParam like this:
@RequestMapping(value="/forgotpassword", method=RequestMethod.POST)
public String recoverPass(@RequestParam("j_username") String username) {
    //do smthin
}

A: You can get single value by @RequestParam  and total form values by @ModelAttribute.
Here is code for single field-
 @RequestMapping(value="/forgotpassword", method=RequestMethod.POST)
 public String getPassword(@RequestParam("j_username") String username) {
        //your code...
    }

And if you have more values in form and want to get all as a single object-
Use @ModelAttribute with spring form tag.

A: 1. Use Form tag library
Just add

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>

<form:form name="forgotpassord" action="forgotpassword" method="POST">

User: <input type='text' name='j_username' />

  <input type="submit" value="OK" class="btn">

</form:form>

2. Now in controller

    @RequestMapping(value="/forgotpassword", method = RequestMethod.POST)
    public ModelAndView forgotpassword(@ModelAttribute("FormJSP_Name") User user,BindingResult result) {

        String user = user.getjUsername(); //use it further
        ModelAndView model1 = new ModelAndView("NextJSP_Name");
        return model1;
    }


text:
Q: MVC2 HTML Linking - Is this proper, or is there a better way? I haven't done MVC2 (or any MVC really) in over a year and while this works, I want to make sure it's the best way.
I have a "splash" page that allows the user to choose what they want to work on; Interfaces, Events, Parameters or Tasks.  The HTML is:

Interfaces

Create, Edit or Delete Interfaces

Tasks

Create, Edit or Delete Tasks

Parameters

Create, Edit or Delete Parameters

Events

Create, Edit or Delete Events

The links work and go to the appropriate pages, but for whatever reason, I'm not sure if this is the proper way to go about it.  I have controllers for each, the proper folders with the Index views for each.  I don't think I should be using Html.ActionLink, but maybe there's something else I should be using.  Any thoughts?  Thanks.

A: Yes, you should be using a helper for these. This will ensure that your generated links use the appropriate routes, which will make your life much easier in the future if you do anything fancy with your URLs or deploy to a non-root path (i.e. /)
In your case, the easiest solution is to replace the URL with @Url.Action. I'd use that over Html.ActionLink because Html.ActionLink doesn't let you easily linkify content more complicated than simple text (e.g. your html).

Interfaces

Create, Edit or Delete Interfaces

If you're not using Razor, go switch to that first. It's worth it. Or drop the @ sign and add some <%= ... %>.
As @MichalFran notes, though, if it's working now, you can always just start following this advice in the future and revisit what you've already done when/if you need to down the road.

A: This answer is not standalone. I am posting it as a supplement to Michael Haren's answer, which I like.
The other thing I would like to add as a "thought" is T4MVC. I am a big fan of it, because it can help you get rid of more "magic strings" in both @Url.Action and @Html.Action. For example, take Michael's example code:

    ...

Using T4MVC, you can get rid of the magic strings, and render the route URL like so:

Then, if you ever rename the InterfacesController or rename / change the signature of your Index() action method, the view will fail to compile instead of getting a 404 at runtime.
Another cool thing is that you can pass parameters to the routing engine as if you were invoking the action method:
public ActionResult ById(int entityId) { ... }

    ...

I don't know why more people don't post about this!


text:
Q: Convert (or re-compress) bitmap/raster images embedded in an SVG? It is possible to embed bitmap/raster images into an SVG (via the image tag).
Is there a tool (preferable command line) to change the format or the compression of the embedded bitmaps? For example, I have an SVG with an embedded PNG bitmap image. I'm looking for a tool that could be called like
svgconvertertool -convert_embedded_pngs_to_jpg -compression high  -f original.svg -out result.svg

creating a new svg with is similar to the original svg, except that all embedded pngs are converted to jpg.
Background: I want to reduce the file size of a couple of SVGs. The file size is basically determined by the embedded PNGs, which I want to convert to (low-quality) JPGs.
Does imagemagick knows that trick?

A: Since I haven't found a tool I wrote a Java based solution. This can be run via
java -cp "«pathto»/png_to_jpg_in_svg/bin" PNG_to_JPG_in_SVG «file|folder»

It can either process a single SVG «file» or all SVGs transitively contained in «folder». If an embedded PNG is found, it is replaced with an JPG version. Since JPG does not support transparency, the background is set to white. The compression quality is set to 50%.
When I was done I found that Florian Eßer has published a python script doing the same trick. His tool requires Python and uses the Python Imaging Library (PIL).
Maybe there is a way of using command line tools such as sed and imagemagick to do the trick, but I haven't found a working script which extracts/replaces the embedded files so that imagemagick can work with that. Alas I didn't find a suitable command in Inkscape.

PS: I'm pretty surprised that someone "downrated" my question. In our case, I was able to reduce the file size of SVGs exported by Sketch (which has a lousy SVG export) by a factor of 4! If someone knows about another tool, I would be happy to hear about it.


text:
Q: Whats the default sort order for Search results in Sharepoint 2013 How does Sharepoint search results sort if you don't customize them? I seem to only find ways to customize the sort order but that might not be necessary.
Underlying question is about doing a bit of SEO for some documents (I have made a custom search scope for a large document library with 20 or so columns)

A: The default sort order is Relevance. You can change this to any sortable Managed Property if you like, for example Last Name for People (if you make the Last Name property Sortable).

A: The "sort order" of search results in SharePoint 2013 is affected by multiple options. The main influences for the ranking are: Managed Metadata, File Type, User Preferences
You are able to modify this ranking by modifying the ranking algorithm, i have seen this in a demo. But I think this affects SP2013 globally, so this should be your last option.
To get you started, you may want to read this: https://blogs.realdolmen.com/experts/2014/06/05/understanding-item-ranking-in-sharepoint-2013-search/


text:
Q: foreach from=$results item="entry" name=status I am trying to add up the value of a specific ({$entry.zip}) field within an array but I can't seem to figure it out, don't particularly want to go through a loop if at all possible.
{foreach from=$results item="entry" name=status}
    {$entry.id} {$entry.id} {$entry.id} {$entry.zip}
{/foreach}

{$entry.zip} produces various numbers, and I would like to add them up to provide me with a running total. Is it possible?
Cheers, Jason.

A: Adapting your example this should be rather straight forward.
{assign var='mysum' value=0}
{foreach from=$results item="entry" name=status}
    {assign var='mysum' value=$mysum+$entry.zip}
    {$entry.id} {$entry.id} {$entry.id} {$entry.zip} {$mysum}
{/foreach}

However, for the sake of separating the application logic from the view layer, which Smarty is usually for, I'd put that somewhere in your php code, maybe even in the array itself which results into $results.


text:
Q: How can I include a report (not a dashboard) on a page? I need to include a report in a lightning page.
I can add the report in a Report Chart, but I want only show the report, no charts. I would like do it by standard, but I can developer a lightning component or a visualForce
Thanks

A: Create dashboard --> display as --> lightning table


text:
Q: Composing ID from connected entities' IDs? My dynamoDB database has 2 tables which I added a many-to-many connection to. In order to prevent duplicate entries in the connection table, I want to make the its keys be in the format <Table1_Entity_ID>_<Table2_Entity_ID>.
The only way I can prevent multiple copies of identical connections being created is by having a unique ID that is deterministic, so I'm not sure how else to do this. Does anyone know if this sort of approach is common?


text:
Q: Need help tracking lsass.exe memory leak I'm trying to track down a memory leak in lsass.exe, following guidelines from article1 and article2, among others.  I've gotten through setting up gflags for lsass.exe, rebooted, and found it has process ID 804.  Now I run the command line:

umdh -p:804 -f:mylog.txt

This immediately spits back the error:

Error: Failed to enumerate process modules.

And the log file has nothing useful:
//
// UMDH: version 6.2.9200.16384: Logtime 2013-05-16 14:49 - Machine=SHAUL-WORK-LT - > PID=804
//
// Debug privilege has been enabled.
// OS version 6.1 Service Pack 1
// Umdh OS version 6.2
//
// Preparing to dump heap allocations.
// Only allocations for which the heap manager collected a stack are dumped. Allocations whithout stack are ignored.
// The stack trace for an allocation is dumped as a list of addresses. They will be resolved to function names at compare time.
//
// Connecting to process 804 ...
// Process 804 opened handle=48.

Where do I go from here?

A: Low-level tools like UDMH tend to be closely coupled with the OS. Seems that your UDMH is from a different OS:
// OS version 6.1 Service Pack 1     <<<< 6.1 = Windows 7
// Umdh OS version 6.2               <<<< 6.2 = Windows 8

Try getting UDMH that match your Windows 7 (6.1.7600).

A: As far as I can see, lsass.exe in Windows 7 is not leaking memory.
The article you quotes relates to Windows Server 2003 / Vista, where lsass.exe and csrss.exe
leaked memory like crazy and accessed the disk non-stop, so were some of the main reasons that Vista was such a failure (or a smaller success than Windows 7).
These bugs were fixed in Windows 7 (but never in Vista - don't ask me why).
If your version of lsass.exe does leak memory on a large scale,
I would verify your computer with several well-known antivirus products,
as well as run sfc /scannow.
As regarding umdh (even if debugging lsass.exe and is not really necessary),
ensure that you have installed the latest Windows SDK and Debugging Tools for Windows.
If umdh still doesn't work with this latest version
(or as was remarked by @Jonathan with the Windows 7 version),
and if you run it in a Command Prompt (cmd) that is "Run as Administrator"
(required even if you are the administrator),
then Microsoft may have blocked its capability of tracing system-essential processes
such as lsass.
One last try may be to use another privileged user account with the help of DevxExec
(download) :
devxexec.exe /user:TrustedInstaller "umdh -p:804 -f:mylog.txt"

A: If I were you, I would do the following:
Download process explorer from here http://technet.microsoft.com/en-gb/sysinternals/bb896653.aspx
Open it up and right click on lsass.exe and go to properties. Jump to the threads tab and see if there are any threads with consistent cpu usage and go to the services tab and see if there are any services you don't recognise or any third party non windows related services using lsass, and stop them. Hopefully that will lead you in the direction of the cause of the problem.


text:
Q: table can be searched instead of tab----the search function in sphinx I built my docs locally using Sphinx and it contains one or two articles to test.

When I search for "tab", there are no search results, but I expected it to match "table".  When I search for "table", there are two search results.  Why are there no search results when I search for "tab"?

A: The default Sphinx search returns only exact matches, as one can see in the following lines of the source code:
// perform the search on the required terms
for (i = 0; i < searchterms.length; i++) {
  var word = searchterms[i];
  var files = [];
  var _o = [
    {files: terms[word], score: Scorer.term},
    {files: titleterms[word], score: Scorer.title}
  ];
  ...
}

The search takes a search term and checks if it is a key in the search index (JSON object, generated during build time). If this is the case, it retrieves further information about the files (and lines) that contain the term.
To change this, you need to extend the default Sphinx search to first check if your search term is a fuzzy (approximate) match to any of the terms the search index lists and then feed all matches as "terms" into the search function.
To my knowledge there is no open source solution/Sphinx theme available that already does this for you.


text:
Q: Refetch firestore data on page reload I want to refetch firebase firestore data each time I enter a page. Currently it only works when I reload the page with Ctrl+R or somethting, but not when I route to this page with a routerLink. I hope it's understandable what I mean :)
I tried destroying the data with ngOnDestroy and things to make it async as possible. I also looked for solutions on the web, but nothing worked for me.
In Component where I want to show the data:
data: Data[];

ngOnInit() {
    this.loadService.getData().subscribe(result => {
      this.data = result;
    });
  }

In Service where I load the data:
  dataCollection: AngularFirestoreCollection<Data>;
  dataDoc: AngularFirestoreDocument<Data>;
  data: Observable<Data[]>;

  constructor(private afStore: AngularFirestore, private afStorage:
  AngularFireStorage, private notification: NotificationService) {
    this.dataCollection = afStore.collection('data');
    this.data = this.dataCollection.snapshotChanges().pipe(
      map(actions => actions.map(a => {
        const data = a.payload.doc.data() as Data;
        const id = a.payload.doc.id;
        return { id, ...data };
      }))
    );
  }

  getData() {
    return this.data;
  }

So this works for the way when I reload the page manually, but not with internal navigations of the Angular Router.

A: The internal update on navigation has to do with the angular change detection. In this case you have to trigger the change detection by your self, like in this example form my git:
import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { CalcComponent } from '../calc-component';

@Component({
  selector: 'app-circular-area',
  templateUrl: './circular-area.component.html',
  styleUrls: ['./circular-area.component.scss']
})
export class CircularAreaComponent implements OnInit {
  public render: Boolean;
  public radius: number;
  public r: number;
  constructor(private cdRef: ChangeDetectorRef) { }

  onChange(event: any, r: number) {
    console.log(r);
    this.r = Number(r);
    this.render = true;
    this.cdRef.detectChanges();
    this.render = false;
  }

  ngOnInit() {
    this.render = false;
  }
}

Use the call
    this.cdRef.detectChanges();

to update your components.
and a flag that you trigger it once !


text:
Q: How to get a date after adding days :TypeError: unsupported type for timedelta days component: Series I am trying to get a new date after adding some days in the actual date. But I am getting the following error:
TypeError: unsupported type for timedelta days component: Series

My sample data and code is provided below:
data={'Date':['8/24/2020','8/26/2020','9/20/2020','10/26/2020','5/26/2020','4/26/2020'],
     'Days':[23,34,56,78,65,54]}
df=pd.DataFrame(data,columns=['Date','Days'])
df.Date=pd.to_datetime(df.Date)
df.newdate=df.Date+timedelta(df.Days)

A: Use pd.to_timedelta
import pandas as pd

df['new_date'] = df.Date + pd.to_timedelta(df.Days, unit='d')

0   2020-09-16
1   2020-09-29
2   2020-11-15
3   2021-01-12
4   2020-07-30
5   2020-06-19
Name: new_date, dtype: datetime64[ns]

A: Try the following code:
def get_newdate(row):
 return row['Date'] + pd.Timedelta(days = row['Days'])

call the above function in the following manner
df.Date = pd.to_datetime(df.Date)
df['newDate'] = df.apply(get_newdate, axis = 1)


text:
Q: How can i add a base URL for all my BackboneJS Models/Collections REST calls? Lets have the following code :
( function($) {
    TeacherModel = Backbone.Model.extend({
        defaults : {
            uid : -1,
            name : ""
        }
    });

    TeachersCollection = Backbone.Collection.extend({
        model : TeacherModel,
        url : function() {
            return "/path/to/api" + "/teacher";
        }
    });
}());

I want to have "/path/to/api" as a global setting to Backbone (I know i can export it globally in window, but i want to set it somewhere in Backbone)
Is there a way and what is the best practice for this ?

A: The way I usually tackle this is to create a base collection and inherit from it, like so:
BaseCollection = BackBone.Collection.extend({
    path: '/path/to/api'
});

TeachersCollection = BaseCollection.extend({
    // path is now accessible from this and all other derived collections.
});


text:
Q: How do I make a network request in Qt binding to a specific interface/IP? So as of Qt 5, QHttp is deprecated and we're all supposed to use QNetworkAccessManager now. Fine. But how do I make a request (HTTP or otherwise) from my multihomed machine without feeling like I'm playing roulette?
If there is no way, then what is a workaround? For my specific case right now, I just need to download a file via HTTP. But is there really no way to do this in a generic way with QtNetwork?

A: The quick workaround would be to use this in your project file
QT += http

It is still available in a separate module for compatibility.

A: If you are lucky enough that the desired interface is a separate physical (hardware) interface, you can do e.g. (web_view is a QWebView*):
QNetworkConfigurationManager config_manager;
QList<QNetworkConfiguration> configs = config_manager.allConfigurations();
bool found_interface = false;
QString desired_interface_name("eth1");
foreach (const QNetworkConfiguration &config, configs) {
    if (config.name() == desired_interface_name) {
        found_interface = true;
        QNetworkAccessManager *network_access_manager = new QNetworkAccessManager;
        network_access_manager->setConfiguration(config);
        web_view->page()->setNetworkAccessManager(network_access_manager);
        break;
    }
}
if (!found_interface) {
    //we failed to find the interface!
}

Again, this will not work if the IP is bound to a virtual interface part of one physical interface (e.g. eth1:1, eth1:2, etc). I am still looking for a solution for that case.


text:
Q: react-native-maps : How to follow user location on button press I am using react-native-maps and it works great. But I have two problems.

*

*I am able to follow user location automatically using the followsUserLocation but when I move the map it keeps dragging me back to the user location. How could I fix this?

*I want to have refresh button, and when the user press the button, I want my map view to follow user location.
constructor() {
    super();
    this.state = {
        followsUserLocation: true,
    };
}

mapView() {
    return(
        <MapView style={styles.map}
        showsUserLocation
        followsUserLocation={this.state.followsUserLocation}
        initialRegion={{
        latitude: 37.523814,
        longitude:  126.927494,
        latitudeDelta: 0.0922,
        longitudeDelta: 0.0421}}/>
   )
}

Any comments or advise would be really appreciated! Thanks in advance!

A: Try onUserLocationChange callback and set your region accordingly using setState
   state = {
    showsUserLocation: true,
    followsUserLocation : true,
    mapRegion: {
      latitude: 37.78825,
      longitude: -122.4324,
      latitudeDelta: 0.0922,
      longitudeDelta: 0.0421,
    },
  };

    <MapView
            style={{ flex: 1 }}
            region={this.state.mapRegion}
            //use this callback to update the regions
            onUserLocationChange={event => console.log(event.nativeEvent)}
            showsUserLocation={this.state.showsUserLocation}
            followsUserLocation={this.state.followsUserLocation}
          />

A: if you are working with Reack Hook
you can create a var instead of useState.
In my case to prevent the app from crashing handled with the ternary condition.
  var liveMap = {
mapRegion: {
  latitude: lattitude ? lattitude : 19.88134866090193,
  longitude: longitude ? longitude : 73.97658792586263,
  latitudeDelta: 0.0022,
  longitudeDelta: 0.0021,
},

     <MapView
        mapType="satellite"
        style={{ height: 400, width: "100%" }}
        showsUserLocation={false}
        zoomEnabled={true}
        zoomControlEnabled={true}
        followsUserLocation={true}
        // onUserLocationChange={(event) => console.log("this is event",event.nativeEvent)}
        showsUserLocation={true}
        followsUserLocation={true}
        region={liveMap.mapRegion}
        // initialRegion={{
        //   latitude: lattitude ? lattitude : 19.88134866090193,
        //   longitude: longitude ? longitude : 73.97658792586263,
        //   latitudeDelta: 0.0022,
        //   longitudeDelta: 0.0021,
        // }}
      >
        <Marker
          coordinate={{
            latitude: lattitude ? lattitude : 19.88134866090193,
            longitude: longitude ? longitude : 73.97658792586263,
          }}
          title={"JavaTpoint"}
          description={"Java Training Institute"}
        />
      </MapView>


text:
Q: How to add anchor tag conditionally in ItemTemplate of Repeater I have Showing the Image Slider on page. To Display I have used the Repeater. Now I have not used anchor tag to image for every image. So Anchor tag is conditionally.
My code is
 <ItemTemplate>

 </ItemTemplate>

Now I always shows the image but every image not cover with a tag. How I achieved this.

A: You can use some kind of databinding to the alt tag.
Assuming you have the alt-text somewhere in the datasource
Eg:
   <ItemTemplate>

         <img id="SliderImage" runat="server" alt='<%#Eval("youralttextfield")%>' />

(Pay attention to single and double quotes here)


text:
Q: Aren't both of these conditions the same? I'm solving this beginner problem on Codeforces, Young Physicist.
https://codeforces.com/problemset/problem/69/A
The answer is to find if 3 forces are in equilibrium.
I've submitted two versions of my answers. One passed but one didn't. But I can't figure why it won't pass, aren't both of the condition same?
if (sumx == 0 && sumy == 0 && sumz == 0)
    cout << "YES" << "\n";
else
    cout << "NO" << "\n";

above is the one that passed.
if (sumx + sumy + sumz == 0)
    cout << "YES" << "\n";
else
    cout << "NO" << "\n";

this is the one that didn't pass.

A: Consider sumx = -1, sumy = 1, sumz = 0. There's a 2-dimensional infinity of solutions to x + y + z = 0, and x = y = z = 0 is just a 0-dimensional singularity.
If you graph x + y + z = 0, you get this:

Every point on this plane is a set of three values that gives you 0 from their sum. The point where all three are zero is just a single point out of the sea. A quick check that tells you you've oversimplified the constraint is that you have 3 variables, but only 1 equation. That means you should still have 3 - 1 = 2 dimensions of freedom, but a single point has 0 dimensions of freedom.

A: The answer is no. When you have sumx + sumy + sumz == 0, it doesn't necessarily mean that all these variables are equal to 0. Let's assume that sumx = -1, sumy = 0, symz = 1. This:
if (sumx == 0 && sumy == 0 && sumz == 0)
    cout << "YES" << "\n";
else
    cout << "NO" << "\n";

outputs NO, but this:
if (sumx + sumy + sumz == 0)
    cout << "YES" << "\n";
else
    cout << "NO" << "\n";

outputs YES.


text:
Q: Ubuntu "git pull --rebase" gets errors of "can't stat objects" - can you suggest what is the problem I've been installing packages on my VM, (python / dev 3.6 oriented especially), and it seems I corrupted some setup, so now I get the following errors:
git pull --rebase
Auto packing the repository in background for optimum performance.
See "git help gc" for manual housekeeping.
error: The last gc run reported the following. Please correct the root cause
and remove .git/gc.log.
Automatic cleanup will not be performed until the file is removed.
error: Could not stat '.git/objects/4f/6716241438e21094af08213c05290a34cffdd7'
error: Could not stat '.git/objects/4f/abf345fc90d14f6f0026cf91bcc4c2fd5c58b8'
and lot more of them
could you suggest how to fix it?

A: "git gc" solved the problem (see git docs)


text:
Q: How to take a first character from the string Using VB.Net & SQL Server 2005
Dim S as string
s = "Rajan"
s = "Sajan"

I want to take a first character from the string (s)
Expected Output
R
S

Need VB.Net Code Help

A: Use chars:
Dim firstChar As char;
firstChar = s.Chars(0);

http://vb.net-informations.com/string/vb.net_String_Chars.htm

A: Try this..
Dim S As String
S = "RAJAN"
Dim answer As Char
answer = S.Substring(0, 1)

A: Try this:
Dim s = "RAJAN"
Dim firstChar = s(0)

You can even do this:
Dim firstChar = "RAJAN"(0)

A: "ABCDEFG".First returns "A"
Dim s as string

s = "Rajan"
s.First
'R

s = "Sajan"
s.First
'S


text:
Q: Интерактивный ввод для запускаемого процесса Сделал простой shell скрипт для переборки всех установленных пакетов и удаления ненужных:
#!/bin/sh

pkgs=`dpkg --get-selections | awk '{ print $1 }' | cut -f1 -d :`

echo "$pkgs" | while IFS='' read -r line || [ -n "$line" ]; do
    apt purge "$line"
done

Но когда shell интерпретатор вызывает apt purge "$line" apt останавливается с сообщением "Abort." по причине отсутствия интерактивного ввода:
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following extra packages will be installed:
  sysvinit-core
The following packages will be REMOVED:
  acl* systemd* systemd-sysv*
The following NEW packages will be installed:
  sysvinit-core
0 upgraded, 1 newly installed, 3 to remove and 0 not upgraded.
Need to get 132 kB of archives.
After this operation, 12.2 MB disk space will be freed.
Do you want to continue? [Y/n] Abort.

Как мне при запуске apt purge "$line" передать ввод в порожденный процес на момент его исполнения?

A: наиболее простой вариант — избавиться от переназначения stdin (происходящего, в частности, при запуске под-оболчки ввиду использования конвейера — |).
т.е., примерно так:
for line in $(dpkg --get-selections | cut -f 1); do
  apt purge $line
done