text:
Q: How to append a series value using if...else in Python I have a data frame with around 10k Observation and few features.
Manually in excel file I can create a new column based on given data i.e.
 = IF(A = 0, 1, B)

where A, B are basically Column name.
Output of above formula would be appended on new column i.e. C.
I have used below Python code :
C = []

for x in df['A']:
    if x == 0:
        C.append(1)
    else:
        C.append(df['B'])

But the above output is giving me "unhashable type: 'Series'" Error.
Anyway to correct the above code

A: Don't use a loop, use np.where:
import numpy as np
# as new column
df['C'] = np.where(df['A'].eq(0), 1, df['B'])
# as list
C = np.where(df['A'].eq(0), 1, df['B']).tolist()

or mask:
# as new column
df['C'] = df['B'].mask(df['A'].eq(0), 1)

# as list
C = df['B'].mask(df['A'].eq(0), 1).to_list()

A: You are trying to append the whole column - you need to append the value.
Try:
c = []
for a, b in zip(df['A'], df['B']):
    c.append(1 if a == 0 else b)


text:
Q: Duplicate Ids in kmeans clustering I have a dataset of an ecommerce store that contains orders made within a month. One customer could have multiple records in the dataset, as expected. When I performed kmeans using python, the resulting clusters were overlapping by the customers that made multiple orders, but to different products. The problem is I want to provide recommendations for each customer, but I cannot determine which cluster to pick for such customers.
Thanks in Advance
# K-Means Clustering

# Importing the libraries
import numpy as np
np.set_printoptions(threshold=np.inf)
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.preprocessing import LabelEncoder,OneHotEncoder

# Importing the dataset
dataset = pd.read_csv('FYP.csv')
X = dataset.iloc[:, [10]].values
Y=dataset.iloc[:, [9]].values
Z=dataset.iloc[:,[5]].values

#The First Way Using LabelEncoder to change categorical values to numerical ones
labelencoder_X = LabelEncoder()
X=labelencoder_X.fit_transform(X[:,0])
labelencoder_Y = LabelEncoder()
Y=labelencoder_Y.fit_transform(Y[:,0])

done = np.vstack((Y,X)).T
done = np.column_stack((Z,Y,X))

#The Second Way
onehotencoder_done = OneHotEncoder(categorical_features="all")
done = onehotencoder_done.fit_transform(done).toarray()

#Then Applying PCA
from sklearn.decomposition import PCA
pca = PCA(n_components=2)
done = pca.fit_transform(done)
explained_variance = pca.explained_variance_ratio_

# Using the elbow method to find the optimal number of clusters
from sklearn.cluster import KMeans
wcss = []
for i in range(1, 11):
    kmeans = KMeans(n_clusters = i, init = 'k-means++', max_iter = 1000, n_init = 10)
    kmeans.fit(done)
    wcss.append(kmeans.inertia_)
plt.plot(range(1, 11), wcss)
plt.title('The Elbow Method')
plt.xlabel('Number of clusters')
plt.ylabel('WCSS')
plt.show()

# Fitting K-Means to the dataset
kmeans = KMeans(n_clusters = 3, init = 'k-means++', max_iter = 1000, n_init = 10)
y_kmeans = kmeans.fit_predict(done)

# Visualising the clusters
plt.scatter(done[y_kmeans == 0, 0], done[y_kmeans == 0, 1], s = 100, c = 'red', label = 'Cluster 1')
plt.scatter(done[y_kmeans == 1, 0], done[y_kmeans == 1, 1], s = 100, c = 'blue', label = 'Cluster 2')
plt.scatter(done[y_kmeans == 2, 0], done[y_kmeans == 2, 1], s = 100, c = 'green', label = 'Cluster 3')
plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], s = 300, c = 'yellow', label = 'Centroids')
plt.title('Clusters of customers')
plt.xlabel("Category")
plt.ylabel("Subcategory")
plt.show()

Dataset Sample

redpajama_set_name: RedPajamaStackExchange


text:
Q: setText in another layout So I'm having a little bit of trouble trying to change the text of a TextView in another layout. My MainActivity.java sets the content view as activity_main.xml, which <include>s app_bar_main.xml, which <include>s content_main.xml, where my main app layout is displayed (it's a Navigation Drawer Activity in Android Studio).
Part of my code in MainActivity.java is shown below:
String user, organisation;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Default code to include navigation drawer here

    if (savedInstanceState == null) {
        Bundle bundle = getIntent().getExtras();

        if (bundle != null) {
            user = bundle.getString("user");
            organisation = bundle.getString("organisation");

            LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View hamburgerMenu = inflater.inflate(R.layout.nav_header_main, null);

            TextView navUsername = (TextView) hamburgerMenu.findViewById(R.id.nav_username),
                    navOrgGroup = (TextView) hamburgerMenu.findViewById(R.id.orgGroup);

            navUsername.setText(user);
            navOrgGroup.setText(organisation);
        }
    }
}

And my nav_header_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="@dimen/nav_header_height"
    android:background="@drawable/side_nav_bar"
    android:gravity="bottom"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:theme="@style/ThemeOverlay.AppCompat.Dark">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/nav_header_vertical_spacing"
        android:contentDescription="@string/user"
        android:src="@android:drawable/sym_def_app_icon" />

    <TextView
        android:id="@+id/nav_username"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/nav_header_vertical_spacing"
        android:text="@string/user"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1" />

    <TextView
        android:id="@+id/orgGroup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/email" />
</LinearLayout>

But for some reason the TextViews in nav_header_main.xml never changes. It remains as the default values set in the XML file. Why is this so? Thanks in advance!

A: Since my comment helped solve:

In my code I'm using somewhat of a different strategy to change the TextView in the navigation drawer. View v = navigationView.getHeaderView(0); TextView emailTextView = (TextView) v.findViewById(R.id.emailTextView);

As for the explanation, you might take a look at this question. It'd be redundant that I copy the text here.

A: your hamburgerMenu has inflated but not add to any viewGroup to show it


text:
Q: Release a snapshot to nexus using maven 3.0.5 I am unable to release a snapshot version of an artifact which I build using maven to nexus. The version of my artifact states 1.0.0-SNAPSHOT.
I can execute mvn clean install without an issue. But when I try to deploy using mvn deploy , I get the following error :
Return code is: 400, ReasonPhrase: Repository version policy: RELEASE does not allow version: 1.0.0-20161019.214318-1. -> [Help 1]

According to what I was able to find out was that maven3 adds the timestamp instead of the SNAPSHOT suffix on the artifact that I want to deploy. The <uniqueVersion> tag of maven is not supported in maven3. What is the approach that I need to take to deploy these artifacts using mvn deploy command.
Updated :
pom.xml
   <distributionManagement>
    <repository>
      <id>my-nexus-snapshots</id>
      <name>Internal Snapshot Releases</name>
      <url>http://localhost:9999/repository/maven-snapshots/</url>
    </repository>
    <snapshotRepository>
      <id>my-nexus-releases</id>
      <name>Internal Releases</name>
      <url>http://localhost:9999/repository/maven-releases/</url>
    </snapshotRepository>
  </distributionManagement>

settings.xml
    <server>
        <id>my-nexus-snapshots</id>
        <username>user</username>
        <password>user123</password>
    </server>
    <server>
        <id>my-nexus-releases</id>
        <username>user</username>
        <password>user123</password>
    </server>

A: Usually, your nexus has separate repositories "snapshots" and "releases". SNAPSHOT versions are deployed to the former, non-SNAPSHOT versions to the latter. For deployment, these repositories have to be specified by you. You can do this by adding the distributionManagement section to your pom. There you can define specific targets for both targets.
<distributionManagement>
  <repository>
    <id>releases</id>
    <name>releases</name>
    <url>http://somerepo:8081/nexus/content/repositories/releases/</url>
  </repository>
  <snapshotRepository>
    <id>snapshots</id>
    <name>snapshots</name>
    <url>http://somerepo:8081/nexus/content/repositories/snapshots/</url>
  </snapshotRepository>
</distributionManagement>

A: If you are using Gradle it can be done in your repositories settings.
Just add the maven-snapshots url
For example:
 repositories {
        maven {
            url = 'http://nexus.something.com/repository/maven-central/'
        }
        maven {
            url = 'http://nexus.something.com/repository/maven-releases/'
        }
        maven {
            url = 'http://nexus.something.com/repository/maven-snapshots/'
        }
    }


text:
Q: How to append div dynamically lower part of div tag? I want to add div dynamically lower part of a div like chat box in Facebook or whats-app. Whenever I want to add dives it add from upper part of the body.

A: This might help!.. for your dynamically add divs and for chat like css, you'll need to modify your css.

var app = angular.module('myapp', []);

function MyCtrl(){}
MyCtrl.prototype = {
  addElement:function(){
    var newEle = angular.element("
new div!
");
    var target = document.getElementById('target');
    angular.element(target).append(newEle);
  }
};

app.controller('myCtrl', MyCtrl);

  <button type="button" ng-click="$ctrl.addElement()">Add Element</button>


text:
Q: dnf update not working in CentOS Unable to run dnf update command as root in CentOS8. Below error occurred while,
Failed to open log file: /var/log/hawkey.log

A: Check /Var/log partition size, it might be full therefor dnf can't write new logs


text:
Q: How to Dynamic generate Open Graph protocol meta tags <meta property="og:url" content="<?php echo "http://". $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];?>"/>
<meta property="og:description" content=""/>
<meta property="og:title" content=""/>
<meta property="og:image" content=""/>

I've tested with the head.phtml file,but I don't know how to get product attributes such like sku, color and images.
I tested with $this->helper('catalog/image')->init($_product, 'image') found in
media.phtml on meta tag and get a blank page,but images on product view are working fine.
That confuses me a lot.

A: You need to can add this to one of your layout files:
<catalog_product_view>
    <reference name="head">
        <block type="core/template" name="open-graph" as="open-graph" template="opengraph/product.phtml" />
    </reference>
</catalog_product_view>

Now you need to create the file opengraph/product.phtml inside you theme (app/design/frontend/{package}/{theme}/template/) with the following content:
<?php $_product = Mage::registry('current_product'); ?>
<?php if ($_product) : ?>
    <meta property="og:url" content="<?php echo "http://". $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];?>"/>
    <meta property="og:description" content="<?php echo htmlspecialchars($_product->getDescription())?>"/>
    <meta property="og:title" content="<?php echo htmlspecialchars($_product->getName())?>"/>
    <meta property="og:image" content="<?php echo $this->helper('catalog/image')->init($_product, 'image')?>"/>
<?php endif;?>

If you need to include the sku or color in there you can get them like this:
$sku = $_product->getSku();
$color = $_product->getAttributeText('color');

Clear the cache when you are done.


text:
Q: How do I retrieve a particular value when the table name, column are given in a SQL Procedure declare @id int
execute getLastRaw 'subjectID','tblSubject', @id output
print @id

alter procedure getLastRaw @column char(20), @tbl Char(20),
@return int output
as
declare @dynSQL varchar(100)
select @dynSQL ='SELECT TOP 1 '+@return+'='+ @column + ' FROM ' + @tbl + ' ORDER BY ' + @column + ' DESC'
exec(@dynsQL)

I want to get the value which gets selected from the select statement. But it says:
Msg 245, Level 16, State 1, Procedure getLastRaw, Line 5
Conversion failed when converting the varchar value 'SELECT TOP 1 ' to data type int.

A: *

*When you concatenate @return SQL Server tries to convert the whole expression to int because of datatype precedence

*You can't assign @return outside or inside of the dynamic SQL because of scope: the stored proc and the dynamic SQL are different. Local variables are local to the scope only
You'll have to use a temp table: this is per connection and available for inner scopes (dynamic SQL)
...
declare @dynSQL varchar(100)

select @dynSQL ='SELECT TOP 1 '+ @column + ' FROM ' + @tbl + ' ORDER BY ' + @column + ' DESC'

CREATE TABLE #result (rtn int)

INSERT #result (rtn)
exec(@dynsQL)

SELECT @return = rtn FROM #result
GO

Although, it is just as easy and more correct to use a proper SELECT...
declare @id int
SELECT @id = subjectID FROM tblSubject ORDER BY subjectID DESC
print @id


text:
Q: Log4j entries going to WebLogic managed server out file Some of my log4j entries are going to the managed server out file. This isn't happening all the time.  My log4j is set up with INFO for everything, but when it does go to the out file, I all the DEBUG is getting logged.  What could be causing this?
Here's the log4j.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<!-- ===================================================================== -->
<!-- -->
<!-- Log4j Configuration -->
<!-- -->
<!-- ===================================================================== -->
<!-- $Id: log4j.xml,v 1.13.2.3 2003/05/02 00:53:12 slaboure Exp $ -->
<!--
        | For more configuration infromation and examples see the Jakarta Log4j
        | owebsite: http://jakarta.apache.org/log4j
-->
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"
        debug="false">
        <!-- =================Appenders for CSF=================-->
        <appender name="CSF_FILE"
                class="gov.va.integration.core.logging.ExceptionCRRollingFileAppender">
<!--            <param name="Threshold" value="INFO" /> -->
<!--            <param name="File" value="${logFile.location}" /> -->
                <param name="File" value="./servers/${weblogic.Name}/logs/myapp/myapp.log" />
                <param name="Append" value="true" />
                <param name="MaxFileSize" value="50000KB" />
                <param name="MaxBackupIndex" value="10"/>
                <layout class="org.apache.log4j.PatternLayout">
                        <param name="ConversionPattern" value="[%d{yyyy-MM-dd'T'HH:mm:ss,SSSZ} %-5p][%t](%F:%L): %c - %m\r%n" />
                </layout>
        </appender>
        <!-- =================Appenders for Events=================-->
        <appender name="EVENT_FILE"
                class="org.apache.log4j.RollingFileAppender">
                <param name="Threshold" value="INFO" />
                <param name="File" value="" />
                <param name="Append" value="true" />
                <param name="MaxFileSize" value="500KB" />
                <param name="MaxBackupIndex" value="1" />
                <layout class="org.apache.log4j.PatternLayout">
                        <param name="ConversionPattern" value="%d %-5p [%c] %m%n" />
                </layout>
        </appender>

        <!--=================End Appenders for Event================= -->
        <!-- ============================== -->
        <!-- Append messages to the console -->
        <!-- ==============================-->
        <appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
                <param name="Target" value="System.out" />
<!--            <param name="Threshold" value="INFO" /> -->
                <layout class="org.apache.log4j.PatternLayout">
                        <!--  The default pattern: Date Priority [Category] Message\n -->
                        <param name="ConversionPattern"
                                value="[%d{yyyy-MM-dd'T'HH:mm:ss,SSSZ} %-5p]: myapp %c - %m\r%n" />

                        <param name="ConversionPattern"
                                value="[%d{yyyy-MM-dd'T'HH:mm:ss,SSSZ} %-5p]: myapp %c - %m\r%n" />
                </layout>
        </appender>

        <appender name="JSR77" class="org.apache.log4j.FileAppender">
                <param name="Append" value="false" />
                <param name="File" value="/log/jsr77.log" />
                <layout class="org.apache.log4j.PatternLayout">
                        <param name="ConversionPattern"
                                value="%d{ABSOLUTE} %-5p [%c{1}] %m%n" />
                </layout>
        </appender>
        <!-- ====================== -->
        <!-- More Appender -->
        <!-- ====================== -->
        <!-- Buffer events and log them asynchronously -->
        <appender name="ASYNC" class="org.apache.log4j.AsyncAppender">
                <appender-ref ref="CSF_FILE" />
                <appender-ref ref="EVENT_FILE" />
        </appender>
        <!-- ================ -->
        <!-- Limit categories -->
        <!-- ================ -->
        <!-- Limit categories to INFO
                <category name="">
                <priority value="INFO"/>
                </category>
        -->
        <!--
                RULES for logging DEBUG < INFO < WARN < ERROR < FATAL.
        -->
        <!-- tested and run
        <category name="*" additivity="false">
                <priority value="ERROR" />
        </category>
  -->
        <!--
                Decrease the priority threshold
                <category name="">
                <priority value="DEBUG"/>
                </category>
        -->

        <!-- Setup the Root category -->
        <root>
                <priority value="INFO"/>
                <appender-ref ref="CSF_FILE" />
        </root>
</log4j:configuration>


text:
Q: Why can't String.Empty be used when creating a const string variable? I often use String.Empty for a placeholder, which equates to "".  So my question, why does a const not like String.Empty?  They compile identically.
// Good
private const string example = "";

// Bad
private const string example = String.Empty;

What in String.Empty makes it not able to be used with a const.

A: String.Empty is not a constant it's only readonly field. And since it's readonly field (which is not known on compile time) it can't be assigned to a constant.
http://referencesource.microsoft.com/#mscorlib/system/string.cs,c9f70a27facb27cf
...
//We need to call the String constructor so that the compiler doesn't mark this as a literal.
//Marking this as a literal would mean that it doesn't show up as a field which we can access
//from native.
public static readonly String Empty;


text:
Q: NSLog import and library I can't believe how much trouble I am having finding this:
I want to use NSLog()
what do I have to #import and what library do I link to?
thanks in advance,
Jay

A: NSLog is apart of the Foundation framework.

A: Just like the rest of the NS classes and functions, you do not need to #import anything if you have the standard build setup such that the foundation classes are implicitly imported.

A: Go to http://developer.apple.com and in the search box type NSLog(). This takes you to the Foundation functions which documents this.
So the #import you are looking for is:
#import <Foundation/Foundation.h>

or, if you are on Xcode 5 and have module support turned on:
@import Foundation;


text:
Q: Transforming a row-based JSON in a column-based JSON in PYTHON would like to transform a row-based JSON in a column-based JSON. I receive the JSON in a row-based form and will do some visualization with it, which would be easier in a column-based form.
row-based would look something like this:
{
  "0": {
    "fname": "John",
    "lname": "Miller",
    "age": 50
  },
  "1": {
    "fname": "Eve",
    "lname": "Johnson",
    "age": 40
  }...

Example column-based:
{
  "fname": {
    "0" : "John",
    "1" : "Eve"
  },
  "lname": {
    "0" : "Miller",
    "1" : "Johnson"
  },
  "age": {
    "0": 50,
    "1" : 40
  }...

Is there a more efficient way than just looping through all elements and rewriting the JSON completely with python?
Thanks!

A: You should use pandas module, well fitting.
import pandas as pd
data = '''
{ "0": { "fname": "John", "lname": "Miller", "age": 50 }, "1": { "fname": "Eve", "lname": "Johnson", "age": 40 }}
'''
dataNew = pd.read_json(data,orient='index').to_json()
print(dataNew)

{"fname":{"0":"John","1":"Eve"},"lname":{"0":"Miller","1":"Johnson"},"age":{"0":50,"1":40}}


text:
Q: Thread-safe initialization of static variables using local static std::once_flag and local static pointer I'm using Visual Studio 2013, which doesn't have "magic statics" feature implemented yet, so local static variables initialization isn't yet thread-safe. So, instead of
Foo& GetInstance()
{
    static Foo foo;
    return foo;
}

I do something like this:
std::unique_ptr<Foo> gp_foo;
std::once_flag g_flag;

Foo& GetInstance()
{
    std::call_once(g_flag, [](){ gp_foo = std::make_unique<Foo>(); });
    return *gp_foo;
}

But I don't like the idea of having gp_foo and g_flag global variables (first, problem with the order of initialization of static variables in different translation units; second, I would like to initialize variables only when we need them, i.e. after first call to GetInstance()), so I implemented the following:
Foo& GetInstance()
{
    // I replaced a smart pointer
    // with a raw one just to be more "safe"
    // not sure such replacing is really needed
    static Foo *p_foo = nullptr;

    static std::once_flag flag;
    std::call_once(flag, [](){ p_foo = new Foo; });
    return *p_foo;
}

And it seems to work (at least it passes the tests), but I'm not sure it's thread-safe, because here we have the same potential problem with the initialization of static local variables p_foo and flag in multiple threads. Initialization of raw pointer with nullptr and initialization of std::once_flag seems more innocent than calling Foo's constructor, but I would like to know whether it is really safe.
So, are there any problems with the last code snippet?

A: By far the most stable approach to singleton object initialisation is the schwartz_counter. It's how std::cin, cout etc are implemented and how they always work, regardless of initialisation order of global objects.
It works in all versions of c++.
https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Nifty_Counter

A: If Foo& GetInstance() is only part of the same compilation unit then the initialization order is defined hence it is thread safe.
However, if above is not the case and multiple compilation units are referencing that then the initialization order would depend on the order of the calls to Foo& GetInstance() and if multiple threads are involved then the order is undefined hence not thread safe.
Worth checking:

*

*Static variables initialisation
order

*zero initialization and static initialization of local scope static variable

A: Your last code snippet is fine from a thread-safe initialization point of view.
However, it is not clear how are you going to use the Foo object in threads calling GetInstance.
Since you are returning a reference to a non-const object, I suppose threads  may modify the Foo object.
Keep in mind that you need additional synchronization for this (eg. a mutex)
If the Foo object is fully initialized by its constructor and threads calling GetInstance will only read from the object, there is no problem but I would suggest to return const Foo &


text:
Q: Implement Gantt Highcharts in react Hi I'm new to both the techs anyone can help with the implementation of gantt chart higharts in react .
Hi have tried the basic of react and made a file with the following compenents.
import './App.css';
import GanttMainDiv from './Components/GanttMainDiv';
function App() {
return (

  <GanttMainDiv />

);
}
export default App;
Can someone help me with implementation ,events and manipulation .

A: Are you sure that you want to use the Highcharts library? From the part of the code that you shared looks like you are trying to use amcharts.
Anyway, here is a basic demo of the Highcharts Gantt implemented in the React environment: https://codesandbox.io/s/highcharts-react-demo-vcs5b?file=/demo.jsx


text:
Q: LEFT JOIN with right table criteria I would like to join table A and B with the following criteria to get the result table.
TABLE A is the Starting TIME
TABLE B consist of both TIME IN and TIME OUT
USER need to clock in (TIME IN), start machine (TIME START), clock out (TIME OUT)

*

*TIME IN >= TIME START

*TIME START >= TIME OUT

*MAX TIME IN/OUT

*DISTINCT Results based on ID

I tried left join but couldn't get the result that I want. I tried using CASE but the are lots of redundant result. Please advise.

A: SELECT a.ID     as id,
       GROUP_CONCAT(CASE
                        WHEN b.Code = 'In'
                            THEN b.Time
           end) as `Time In`,
       `TIME START`,
       GROUP_CONCAT(CASE
                        WHEN b.Code = 'Out'
                            THEN b.Time
           end) as `Time Out`
FROM `Table A` a
JOIN `Table B` b on a.ID = b.ID
WHERE 1
  AND ((b.Code = 'In' && b.`TIME` <= a.`TIME START`) OR
       (b.Code = 'Out' && b.`TIME` >= a.`TIME START`))
GROUP BY a.ID, a.`Time Start`

query doesn`t handle Code='In/Out' you need to split this explict

A: You can do this with a couple of LEFT JOINs:
SELECT
  ts.ID,
  MAX(ti.Time) AS Time,
  MAX(ts.TimeStart) AS TimeStart,
  MAX(tto.Time) AS TimeOut
FROM tableA ts
LEFT JOIN tableB ti ON ts.ID = ti.ID AND ti.Code IN ('IN','IN/OUT') -- "Time IN"
LEFT JOIN tableB tto ON ts.ID = tto.ID AND tto.Code IN ('Out','IN/OUT') -- "Time OUT"
GROUP BY ts.ID
ORDER BY ts.ID

Like Impaler mentioned, your description of IN/OUT and the desired result you provided don't seem to be in sync.  The example above assumes IN/OUT is both IN and OUT.  This will also give you the max TimeIn/TimeOut values if there are duplicate entries.
DB Fiddle (Postgres)

A: Try aggregating table B before the join:
WITH cte AS
 ( -- pivot into in/out time
   SELECT
      ID
     ,Max(CASE WHEN Code IN ('IN', 'IN/OUT') THEN Time END) AS TimeIn
     ,Max(CASE WHEN Code IN ('Out','IN/OUT') THEN Time END) AS TimeOut
   FROM tableB
   GROUP BY ID
 )
SELECT
   a.ID
  ,CASE WHEN TimeStart >= TimeIn THEN TimeIn END AS TimeIn
  ,TimeStart
  ,CASE WHEN TimeStart <= TimeOut THEN TimeIn END AS TimeIn
FROM tableA AS a
LEFT JOIN cte AS b
  ON a.ID = b.ID


text:
Q: Mentioning people with multi-word display names or user ids in a Slack Message using a WebHook and Ansible Slack I'm using the Ansible slack module to send notifications, which include @mentions for notifiable people. I'm having trouble with multi-word display names, though single-word display names work fine.
For example:
ok: [localhost] => {
    "msg": "message: `SANDPIT` started ELMS and LACM MapGuide\nFYI <@alice> <@bob>"
}

But then <@Genghis Khan> comes to work alongside Alice and Bob. And he, because he's Ghengis Khan, of course chooses a multi-word display name. Given the following message:
ok: [localhost] => {
    "msg": "message: `SANDPIT` started ELMS and LACM MapGuide\nFYI <@Ghenkis Khan> <@bob>"
}

@bob is recognised, <@Ghenkis Khan> isn't.
I've also tried user ids as recommended at https://api.slack.com/changelog/2017-09-the-one-about-usernames but they don't work any better, so I've reverted to display names. But for completeness here is an example of the message content, with valid user ids but an invalid result:
TASK [slack : debug]
***********************************************************
ok: [localhost] => {
    "msg": "message: `SANDPIT` started ELMS and LACM MapGuide\nFYI <@U12345DK> <@U12345TT>"
}

As mentioned, Slack is not buying these user ids either.
Here's the Ansible task that sends the message to Slack. All tokens etc are working as expected, and this is all happening in the same workspace.
- name: Send message via Slack
  slack:
    token: 'valid token'
    color: 'valid color'
    msg: '{{ message }}'
    link_names: 1
  # problems with notifications should not fail the pipeline
  ignore_errors: yes

A: According to the official documentation of the msg property of the slack plugin all angle brackets and ampersands need to be escaped using HTML notation:

Message to send. Note that the module does not handle escaping
  characters. Plain-text angle brackets and ampersands should be
  converted to HTML entities (e.g. & to &) before sending. See
  Slack's documentation (https://api.slack.com/docs/message-formatting)
  for more.

So you want to try something like this:
TASK [slack : debug]
***********************************************************
ok: [localhost] => {
    "msg": "message: `SANDPIT` started ELMS and LACM MapGuide\nFYI <@U12345DK> <@U12345TT>"
}


text:
Q: SSIS Script Task: Select from datatable1 into datatable2 I'm using SQL 2014, Visual Studio 2013.  I have the following code that's part of a larger script task:
//Load DataTable1 with Source Excel Sheet Data
OleDbCommand oconn = new OleDbCommand("select * from [" + sheetname + "]", cnn);
OleDbDataAdapter adp = new OleDbDataAdapter(oconn);
DataTable dt = new DataTable();
adp.Fill(dt);

What I would like to do next is select a targeted number of columns from datatable1, and fill another datatable.  Something like this:
//Load another DataTable with Data from datatable1
OleDbCommand oconn2 = new OleDbCommand("select [column1], [column2] from datatable1", cnn);
OleDbDataAdapter adp2 = new OleDbDataAdapter(oconn2);
DataTable dt2 = new DataTable();
adp2.Fill(dt2);

Is this possible?  The reason behind this is complicated, but I don't know another way around it.  My source files are Excel.  So the data needs to be brought into a datatable.  Then the column names need to modified.  Then a table can be made with the modified column names.  But first, the data needs to be brought into a datatable as is, as I'm not sure I want to modify the source files.
Thank you.

A: Define the second DataTable using the data types and new names for the columns that will be added to it.  Then you can populate this object by using the ordinal position of the columns in the initial DataTable with the Add method as below.
            DataTable dt2 = new DataTable();
            dt2.Columns.Add("NewColumnName1", typeof(int));
            dt2.Columns.Add("NewColumnName2", typeof(string));

            //in this example dt is the original DataTable
            foreach (DataRow dr in dt.Rows)
            {
                          //add only necessary columns by their
                          //ordinal position in source DataTable
                         dt2.Rows.Add(dr[1], dr[0]);
            }


text:
Q: MvvM Collection model I have Person model with some fields.
ID  FirstName   LastName    DOB
1   Samantha    Smith   Jul.9 1987,
2   John    Jonson  Aug.23 1978,
3   Mark    Kramer  Jan.5 1971,
4   Linda   Miller  Apr.9 1982
public class Person
{
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string DOB { get; set; }

    Public override string ToString()
    {
       return String.Format("{0}, {1}, {2}, {3}, {4}", ID, FirstName, LastName, DOB);
    }
}

How can I add data from database to Person model
public class PersonRepository : Collection<Person>
{

 public PersonRepository()
    {

        foreach (PropertyInfo property in typeof(Person).GetProperties())
            Add(new Person() { FirstName = property.Name });

    }
}

so I can use it in new class as private;
ObservableCollection<Person> _items = new ObservableCollection<Person>();
public IEnumerable<Person> Items { get { return _items; } }


text:
Q: insertRow() in QT5.4 Is there a limit in the number of rows that can be inserted using insertRow() of QTableWidget Class?
In my program, I increment a variable, say count, and use the statement insertRow(count). It works perfectly if count <= 500. If count > 500, the code stops running. I am working in MSVS2013.
EDIT : Code added
    QXmlStreamReader xs(ba);
    int i=-2;
    QTableWidgetItem* titem=NULL;

    QStringList qslHeaders;
    map < QString, pair<QString, QString >> HeaderMap;
    int map_index = 0;
    int col_count_set = 0;
    map<QString, pair<QString, QString>>::iterator iter;
    while (!xs.atEnd())
    {
        bool flag = true;
        ++i;
        if (xs.readNextStartElement() && xs.name().toString() == "ROW")
        {
            insertRow(i);
            while (flag)
            {
                switch (xs.readNext())
                {
                case QXmlStreamReader::StartElement:
                {
                    QString name = xs.name().toString();

                    //Insert data to map here
                }
                break;

                case QXmlStreamReader::EndElement:
                    if (xs.name().toString() == "ROW")
                    {
                        map_index = 0;
                        if (HeaderMap.size()>0 && col_count_set == 0)
                        {
                            setColumnCount(HeaderMap.size());
                            col_count_set++;
                        }
                        iter = HeaderMap.begin();
                        while (iter != HeaderMap.end())
                        {
                            titem = new QTableWidgetItem(iter->second.first);
                            setItem(i, map_index, titem);
                            iter++;
                            map_index++;
                        }
                        flag = false;
                    }
                    break;
                default:
                    break;
                }
            }
        }
        // WRITTEN FOR DEBUGGING
        if (i > 501)
            break;
       // DEBUG
    }
    iter = HeaderMap.begin();
    while (iter != HeaderMap.end())
    {
        if (!qslHeaders.contains(iter->second.second))
        {
            qslHeaders.append(iter->second.second);
        }
        iter++;
    }
    setHorizontalHeaderLabels(qslHeaders);


text:
Q: adding missing dates into a data table based on some conditions in R I have a data table like this :
timestamp    Status
05-01-2020    0
06-01-2020    0
07-01-2020    1
08-01-2020    1
09-01-2020    1
11-01-2020    0
13-01-2020    1

If The status is 1 and status 0 are appearing on two different days, then I need to fill the missing dates. Here on 9th last value of status is 1 and it is becoming 0 on 11th only. So in between I have 10th. I need to add these dates to the existing data table  or create a new data table and put status as 1
I am aware of this :
library(tidyverse)

complete(dt, status, timestamp)

Expected output:
 timestamp    Status
    05-01-2020    0
    06-01-2020    0
    07-01-2020    1
    08-01-2020    1
    09-01-2020    1
    10-01-2020    1
    11-01-2020    0
    13-01-2020    1

This should repeat for any number of days in between. But only for conditions between 1 and 0 and not between 0 and 1

A: This is an interesting question. If I understand correctly, the OP asks to insert additional rows between each group of contiguous values of Status if the previuos group had Status == 1 and the current group has Status == 0. In addtion, I understand that filling up missing dates within a streak of Status == 1 is not requested.
So here are two different data.table approaches:
1. Grouping and prepending additional rows to each Status == 0 group
This solution borrows from Matt Dowle's answer to Get the last row of a previous group in data.table (see here for another use case).
It creates groups of contiguous streaks of 0/1 values in Status (using rleid()). For each group, it is checked whether it is required to insert rows. If so, the additional rows are prepended to the rows of the current group (using rbind()).
library(data.table)
options(datatable.print.class = TRUE)
dt[, timestamp := as.IDate(timestamp, "%d-%m-%Y")]   # coerce character date to numeric
dt[, grp := rleid(Status)]   # create groups of consecutive values of Status
dt[, new := ""]   # just for test & demonstration
pg <- first(dt)  # initialise storage of last row of previous group
dt[, {
  if (first(timestamp) - pg$timestamp > 1L & pg$Status == 1L) {
    # if there is a gap and Status switches from 1 to 0 the fill the gap
    add <- .(timestamp = seq(pg$timestamp + 1L, first(timestamp) - 1L, by = 1L), Status = 1L, new = "*")
  } else {
    # no gap to fill
    add <- .SD[0L]
  }
  pg <- last(.SD)   # remember last row
  rbind(add, .SD)   # prepend additional rows
}, by = grp][, grp := NULL][]   # remove grouping variable

     timestamp Status    new
        <IDat>  <int> <char>
 1: 2020-01-05      0
 2: 2020-01-06      0
 3: 2020-01-07      1
 4: 2020-01-08      1
 5: 2020-01-09      1
 6: 2020-01-10      1      *
 7: 2020-01-11      0
 8: 2020-01-13      1
 9: 2020-01-14      0
10: 2020-01-16      1
11: 2020-01-17      1
12: 2020-01-18      1      *
13: 2020-01-19      1      *
14: 2020-01-20      0

Note that an enhanced dataset has been used (see below) to allow for a more thoroughly testing. Also, the column new has been added just to demonstrate where the rows have been inserted.
2. Identify gaps, create missing rows, append and re-order
This approach is different. It identifies the gaps which are to be filled, creates the missing rows, appends them to the original dataset, and re-orders the rows by timestamp:
library(data.table)
options(datatable.print.class = TRUE)
library(magrittr)   # piping used to improve readability
dt[, timestamp := as.IDate(timestamp, "%d-%m-%Y")] # coerce character date to numeric
lapply(
  dt[, .I[timestamp - shift(timestamp, fill = first(timestamp)) > 1L & shift(Status) == 1 & Status == 0]],
  function(i) dt[, .(timestamp = seq(timestamp[i - 1L] + 1L, timestamp[i] - 1L, by = 1L), Status = 1L)]
) %>%
  c(list(dt)) %>%
  rbindlist() %>%
  .[order(timestamp)]

     timestamp Status
        <IDat>  <int>
 1: 2020-01-05      0
 2: 2020-01-06      0
 3: 2020-01-07      1
 4: 2020-01-08      1
 5: 2020-01-09      1
 6: 2020-01-10      1
 7: 2020-01-11      0
 8: 2020-01-13      1
 9: 2020-01-14      0
10: 2020-01-16      1
11: 2020-01-17      1
12: 2020-01-18      1
13: 2020-01-19      1
14: 2020-01-20      0

The expression
dt[, .I[timestamp - shift(timestamp, fill = first(timestamp)) > 1L & shift(Status) == 1 & Status == 0]]

identifies the gaps to be filled by returning the indices in the original dataset dt where the additional rows need to be inserted before.

[1]  6 11

So, the additional rows need to be inserted between rows 5 to 6, and 10 to 11, resp.
3. Data
The dataset has been expanded to allow for a more thoroughly testing.
dt <- fread(
  "timestamp    Status
05-01-2020    0
06-01-2020    0
07-01-2020    1
08-01-2020    1
09-01-2020    1
11-01-2020    0
13-01-2020    1
14-01-2020    0
16-01-2020    1
17-01-2020    1
20-01-2020    0")

Note that all solutions posted so far assume that dt is ordered by increasing timestamp. If not, it can be achieved by
setorder(dt, timestamp)

A: An option using rolling join to find the date before the closing zero and then fill up the missing dates for each continuous set of ones:
DT[Status==1L, nextzero :=
    DT[Status==0L][.SD, on=.(timestamp), roll=-Inf, x.timestamp - 1L]
]

ans <- rbindlist(list(
        DT[Status==1L & !is.na(nextzero),
            .(timestamp=seq(min(timestamp), nextzero, by="1 day"), Status=1L),
            nextzero],
        DT[Status==0L | is.na(nextzero)]
    ), use.names=TRUE)[, nextzero := NULL]

setorder(ans, timestamp)[]

data:
library(data.table)
DT <- fread("timestamp    Status
05-01-2020    0
06-01-20200
07-01-2020    1
08-01-2020    1
09-01-2020    1
11-01-2020    0
13-01-2020    1")
DT[, timestamp := as.IDate(timestamp, "%d-%m-%Y")]

A: Added some more rows to your data to include the case of more than one missing day.

library(tidyr)
library(dplyr)
library(lubridate)

  df %>%
    mutate(timestamp = as.Date(timestamp, format = "%d-%m-%Y"),
         to_fill = case_when(Status == 1L & lead(Status) == 0L & difftime(lead(timestamp), timestamp, "days") > 1 ~ 1,
                            TRUE ~ 0)) %>%
    complete(timestamp = seq.Date(min(timestamp), max(timestamp), by = "day")) %>%
    fill(to_fill) %>%
    mutate(Status = case_when(is.na(Status) & to_fill == 1 ~ 1L,
                            TRUE ~ Status)) %>%
    na.omit() %>%
    select(-to_fill)

#> # A tibble: 14 x 2
#>    timestamp  Status
#>    <date>      <int>
#>  1 2020-01-05      0
#>  2 2020-01-06      0
#>  3 2020-01-07      1
#>  4 2020-01-08      1
#>  5 2020-01-09      1
#>  6 2020-01-10      1
#>  7 2020-01-11      0
#>  8 2020-01-13      1
#>  9 2020-01-15      1
#> 10 2020-01-16      1
#> 11 2020-01-17      1
#> 12 2020-01-18      0
#> 13 2020-01-19      0
#> 14 2020-01-22      1

data
df <- data.frame(timestamp = c("05-01-2020", "06-01-2020", "07-01-2020", "08-01-2020", "09-01-2020", "11-01-2020", "13-01-2020", "15-01-2020", "18-01-2020", "19-01-2020", "22-01-2020"),
                 Status = c(0L, 0L, 1L, 1L, 1L, 0L, 1L, 1L, 0L, 0L, 1L ))

Created on 2020-05-20 by the reprex package (v0.3.0)

A: We can filter the rows which we want to expand. The condition to select rows is if current row Status is 1 and next row Status is 0 OR current row Status is 1 and previous row's Status is 0.
library(dplyr)
df$timestamp <- as.Date(df$timestamp, '%d-%m-%Y')

temp <- df %>%
        filter(Status == 1 & lead(Status) == 0 | lag(Status) == 1 & Status == 0)

Then create groups of two rows in that dataframe and expand them filling the dates between them and updating Status as 1. Once we have expanded dataset we can bind it with the original dataset to get complete dataset.
temp %>%
   group_by(grp = rep(1:n(), each = 2, length.out = n())) %>%
   tidyr::complete(timestamp = seq(min(timestamp), max(timestamp), by = 'day'),
                   fill = list(Status = 1)) %>%
   ungroup %>%
   select(-grp) %>%
   bind_rows(anti_join(df, temp)) %>%
   arrange(timestamp)

# A tibble: 8 x 2
#  timestamp  Status
#  <date>      <dbl>
#1 2020-01-05      0
#2 2020-01-06      0
#3 2020-01-07      1
#4 2020-01-08      1
#5 2020-01-09      1
#6 2020-01-10      1
#7 2020-01-11      0
#8 2020-01-13      1

A: You could create a temporary data frame which is complete in sense of dates and which Status column is 1.
dat$timestamp <- as.Date(dat$timestamp, format="%d-%m-%Y")  ## date format is needed
tmp <- data.frame(timestamp=seq(dat$timestamp[1], by="day", length.out=nrow(dat)),
           Status=1)

Then use match to rbind that row where the lagged diff is -1.
dat <-
  rbind(dat,
        tmp[match(dat$timestamp[match(-1, c(diff(dat$Status), NA))] + 1, tmp$timestamp), ])
dat[order(dat$timestamp), ]
#     timestamp Status
# 1  2020-01-05      0
# 2  2020-01-06      0
# 3  2020-01-07      1
# 4  2020-01-08      1
# 5  2020-01-09      1
# 61 2020-01-10      1
# 6  2020-01-11      0
# 7  2020-01-13      1

Data
dat <- read.table(text="timestamp    Status
05-01-2020    0
06-01-2020    0
07-01-2020    1
08-01-2020    1
09-01-2020    1
11-01-2020    0
13-01-2020    1", header=T)


text:
Q: Please help in Zend Db Select I want to write this query via zend db select
SELECT * FROM bookmarks
 INNER JOIN urls
 ON urls.url_id = bookmarks.url_id WHERE (bookmarks.bmk_id = '2') AND (bookmarks.user_id = 1)
Please tell me how to write? I am asking this because the method I am using to write this query is not working.

A: I think this is what you need to do. It's absolutely textbook as described on in the documentation
$select = $db->select()
             ->from('bookmarks')
             ->join('urls', 'urls.url_id = bookmarks.url_id')
             ->where('bookmarks.bmk_id=?', 2)
             ->where('bookmarks.user_id=?', 1);


text:
Q: Problem passing parameters into main function in C++ test bench I'm trying to test a function I have created in C++ by using a testbench. The main function parameters are two 8x8 arrays:
 void multiplyArray2(int A[8][8], int B[8][8]){

In my test bench file, I have created an input array of values and an output array and am trying to input them into the function:
int dataIn[8][8];
int dataOut[8][8];

int main(){

    dataIn = {{68, 68, 67, 67, 66, 67, 67, 67},
                {69, 69, 68, 68, 67, 69, 67, 67},
                {70, 70, 71, 71, 70, 70, 70, 70},
                {72, 72, 72, 71, 72, 72, 72, 71},
                {74, 74, 73, 73, 74, 74, 74, 74},
                {75, 76, 75, 75, 76, 76, 75, 75},
                {76, 77, 77, 76, 76, 76, 76, 76},
                {79, 78, 79, 79, 78, 76, 77, 77}};

    multiplyArray2(dataIn, dataOut);

When I try to input parameters into the function in the test bench it is providing me with this error message:

And I have no idea why...

A: void multiplyArray2(int A[][8], int B[][8])

This should solve your problem.
Multi-dimensional arrays are not very well supported by default in C and C++. You can pass an N-dimension array only when you know N-1 dimensions at compile time.


text:
Q: React-Redux-Form - Integrating date picker I'm new to redux form, so sorry if i use the wrong terminology.
I've been using react-redux-form to handle my redux and backend communication.
https://github.com/davidkpiano/react-redux-form
Recently I was asked to implement a datepicker. Our initial choice is to use Airbnb datepicker, however we can't send the captured value into the backend.
Maybe it's easier to show my code:
on return of render()-
<Form model="trip" onSubmit={(val) => this.handleSubmit(val)}>
    <Control.select model=".city">
        {getCities}
    </Control.select>

    <Control
        model=".travelDate"
        component={SingleDatePicker}
        mapProps={{
            onDateChange: props => props.onChange,
            onFocusChange: props => props.onChange,
            date: props => props.modelValue
        }}
    />

        <Button name="Lets Begin!" buttonType="primary" />

</Form>

Well I've been doing a bit of searching, and it react-datepicker by airbnb has a bit of an issue with react-redux form. If anyone know any better plug in worth using. Please let me know
Thanks for your help,

A: *

*react-datetime https://github.com/YouCanBookMe/react-datetime implementaion is given below:-

form.js

Valid until

          <Control
              model='.valid_until'
              component={DateField}
              mapProps={{
                  value: (props) =>{return props.viewValue}
                }}
                />

Datefield.js

import React, {PureComponent, PropTypes} from "react";
import Datetime from 'react-datetime/DateTime';
require('react-datetime');

const DateComponent = (props)=> {

    return (
        <Datetime defaultValue={new Date()}
        value={props.value}
        {...props}
        style={{width:'150%'}}/>
    );

};

export default DateComponent

*

*Second you can use react-md DatePicker
 https://react-md.mlaursen.com/components/pickers/date


text:
Q: Expression for FFT of parametric function If a function is defined parametrically $F_{(t)}=(x_{(t)}, y_{(t)})$, is there an expression for the Fourier transform of function $x_{(y)}$ in terms of the FFT of $x_{(t)}$ and $y_{(t)}$ ?
I checked many tables and found nothing, but, I guess, it should be a known simple and common expression.


text:
Q: How to change the xml properties from default properties?
The above screen capture shows the expected output and actual output, red color indicates that it differs from the actual output that is shown in green color.
To create xml document I have used the marshall concept.Java code used to create xml document are given below.
 import com.ehf.bean.Invoice;
 import com.sap._0050089212_one_off.ypt74nkey_.StandardFaultMessage;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import javax.xml.bind.JAXBContext;
 import javax.xml.bind.JAXBException;
 import javax.xml.bind.Marshaller;
 import javax.xml.parsers.ParserConfigurationException;
 import javax.xml.transform.TransformerException;
 import org.xml.sax.SAXException;

 public class Ehf {

 public static void main(String[] args) throws ParserConfigurationException,
 TransformerException, SAXException, IOException, StandardFaultMessage,
 com.sap.xi.a1s.global.StandardFaultMessage, JAXBException {

    JAXBContext contextObj = JAXBContext.newInstance(Invoice.class);

    Marshaller marshallerObj = contextObj.createMarshaller();
    marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    Invoice invoice = new Invoice();
    invoice.setCustomizationID("dsf");
    invoice.setInvoiceTypeCode(0);
    marshallerObj.marshal(invoice, new FileOutputStream("question.xml"));

}

}

Note: Invoice  class is generated using xsd, through xjc command.
How can resolve this problem?

A: @javax.xml.bind.annotation.XmlSchema(
namespace = "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2",
elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED,
xmlns ={@XmlNs(prefix="cac", namespaceURI="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2"),
        @XmlNs(prefix="cbc", namespaceURI="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2"),
        @XmlNs(prefix="", namespaceURI="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2")
       })

The above code is working for me as expected, this code should be write in package-info.java


text:
Q: Converting pandas dataframe to an array I have a csv file named "transactions4.csv" that contains values that look like:
column 1|column 2

--------|---------
12345   | 10
23456   | -15
12376   | 10
56842   | 25
45678   | -5
78324   | 20

Here's what I have so far:
import pandas as pd
transactionsFileName = "transactions4.csv"
df = pd.read_csv(transactionsFileName)
print(df.to_string())

This prints the values from the file, but I'm not sure how to put each column into an array.

A: T + as_matrix
df.T.as_matrix()
Out[70]:
array([[12345, 23456, 12376, 56842, 45678, 78324],
       [   10,   -15,    10,    25,    -5,    20]], dtype=int64)

A: You could also query the .values attribute.
x = df.values.T

print(x)
array([[12345, 23456, 12376, 56842, 45678, 78324],
       [   10,   -15,    10,    25,    -5,    20]])

If you want each column in a separate array, just unpack them:
i, j = x

print(i)
array([12345, 23456, 12376, 56842, 45678, 78324])

print(j)
array([ 10, -15,  10,  25,  -5,  20])


text:
Q: Gradle ShadowJar with Other SourceSet Resources I am using the ShadowJar Gradle plugin to build a Jar containing all of the source files in the  src/main/java directory and other Jar files in a lib directory and it is working fine. What I need is another ShadowJar task, a devShadowJar task, that will instead of pulling in a JSON file in the src/main/resources folder, it will pull in a JSON file in the src/dev/resources folder.
I added this to the build.gradle file to define the dev source set:
sourceSets {
    dev
}

But now I am not sure how to create a devShadowJar task to use the dev JSON resource instead of the JSON resource file located in src/main/resources.

A: try playing around this:
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar

task devShadowJar(type: ShadowJar) {
    zip64 true
    from './build/classes/java/main'
    from project.configurations.compile
    from './src/dev/resources' // or wherever the resources and up under ./build
}


text:
Q: How to cut certain field in a file and insert in middle of another file in unix I have a file like below with "|" delimited.
1234|This is Line 1|Yes
5678|This is Line 2|Yes
9999|This is Line 3|Yes

I already have a XML file and I want to insert 1st,2nd,3rd column in different positions and create 1 XML file for each line like below
<tag1>1234</tag1>
<tag2> This is line 1 </tag2>
<tag3> Yes </tag3>

Basically I want to read every line from the first file and create a XML file for each line by inserting the fields in different positions. Any help of how to do it in shell scripting would be of great help
I tried this, but for loop is not reading 2nd column properly("This is Line 1").it is taking  each space as a field and create multiple files
  for i in `cat file | awk -F"|" '{print $1}'`
    do
    echo $i
    j=`cat addxml | grep "tag2" | awk -F ">" -v var="$i" '{print $1">"var$2">"}'`
    sed 's|<tag2></tag2>|'"${j}"'|g' addxml > input1.xml
    done

A: Just say...
awk -F"|" '{file="file_"NR
            for (i=1;i<=3;i++)
                printf "<tag%d>%s</tag%d>\n", i, $i, i >> file
           }' file

so you have files like:
$ tail file*
==> file_1 <==
<tag1>1234</tag1>
<tag2>This is Line 1</tag2>
<tag3>Yes</tag3>

==> file_2 <==
<tag1>5678</tag1>
<tag2>This is Line 2</tag2>
<tag3>Yes</tag3>

==> file_3 <==
<tag1>9999</tag1>
<tag2>This is Line 3</tag2>
<tag3>Yes</tag3>


text:
Q: Android Dragging ListView and ContextMenu I'm still working with dragging listview (example from google https://www.youtube.com/watch?v=_BZIvjMgH-Q) - long click by listview item - goes dragging and I want to implement context menu on short click, but my changes do not seem towork. After short click on listview item goes dragging effect..
here is my code for activity:
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Utils.changeTheme(this,getApplicationContext());
        Utils.setLang(this,getApplicationContext());
        setContentView(R.layout.activity_list);

        listView = (DynamicListView) findViewById(R.id.listview);
        adapter = new StableArrayAdapter(this, R.layout.text_view, productsArray);
        listView.setList(productsArray);
        listView.setAdapter(adapter);
        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

        registerForContextMenu(listView);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                view.showContextMenu();
            }
        });

    }

With simple listview, short click working without any problems...
Could anybody explain what I'm doing wrong?
Thx in advance!

A: The best solution in this case is use popup menu instead of context menu.


text:
Q: I tried installing brew core utilities and I got this error "Installing... Warning: No available formula with the name "coreutils"" ==> Searching for similarly named formulae...
Error: No similarly named formulae found.
==> Searching for a previously deleted formula (in the last month)...
Error: No previously deleted formula found.
==> Searching taps on GitHub...
I tried installing core utilities for SHELLS by 4ndr34z


text:
Q: java.lang.ArrayIndexOutOfBoundsException: 2 error message is displayed Code is like this:
String txtDatePr = driver.findElement(By.id("--ID--")).getText();
      int txtPrLength = txtDatePr.length();
      System.out.println(txtPrLength);
      if (txtPrLength == '0'){
          System.out.println("Sellable From date value is empty");
      }
      else{
          String[] arrsplitDatePr = txtDatePr.split("/");
          int addYearPr = Integer.parseInt(arrsplitDatePr[2]);
          addYearPr = addYearPr + 3;
          String newYearPr = String.valueOf(addYearPr);
          String changedDatePr = arrsplitDatePr[0]+'/'+arrsplitDatePr[1]+'/'+newYearPr;
          driver.findElement(By.xpath("//span[@class='--Class---'][1]/input")).sendKeys(changedDatePr);
      }

For
System.out.println(txtPrLength);

Its showing me the sysout value as 0 , but after that its giving an error message:
java.lang.ArrayIndexOutOfBoundsException: 2

A: txtPrLength is an integer replace '0' with  0
if (txtPrLength == 0){
          System.out.println("Sellable From date value is empty");
      }

A: First Thing : It seems you are not getting the text from your expected element that's why it is showing result 0
For debugging you can try below code :
String txtDatePr = driver.findElement(By.id("--ID--")).getText();
int txtPrLength = txtDatePr.length();

System.out.println("String value ="+txtDatePr +"And Length ="+txtPrLength);

Here you will get the clear idea which text you are getting.
Second Thing : replace '0' with 0 in your if condition as you need to compare text length with integer
if (txtPrLength == 0)
{
      System.out.println("Sellable From date value is empty");
}

Third : You are getting java.lang.ArrayIndexOutOfBoundsException: 2 because every time you are moving in else condition where you are using index = 2 right here :
int addYearPr = Integer.parseInt(arrsplitDatePr[2]);

So Just do one thing, make correction in your if condition as mentioned above and try so it won't move in else condition if there is no text.

A: Why you are applying "" in an Integer value , remove it
 if (txtPrLength == 0)
 {
  //Code
 }


text:
Q: Allow users to upload files to my google drive script I have forms that can be filed by users and uploaded to my google drive. The following code accomplishes that task. However, it also asks permission from the user to access their drive, and uploads to the user's drive and not to my drive. I want this to upload directly to my Google drive.
How can I allow my script access to my drive? Can I use a kind of hard-coded tokens or access tokens?
$client = new Google_Client();
$client->setApplicationName("Drive API Quickstart");
$client->setDeveloperKey("xxxxxxxxxxxx");
$client->setRedirectUri("xxxxxxxx");
$client->setClientId('xxxxxxxxxxx');
$client->setClientSecret('xxxxxxxxxx');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$client->setAccessType("online");
$client->setApprovalPrompt("auto");

if (isset($_GET['code'])) {
    $client->authenticate($_GET['code']);
    $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
    header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));

}

if (!$client->getAccessToken() && !isset($_SESSION['token'])) {
    $authUrl = $client->createAuthUrl();
    print "Connect with google to upload file!";

    }

    if (isset($_SESSION['token'])) {
    $service = new Google_Service_Drive($client);
    $file = new Google_Service_Drive_DriveFile();
    $file->setTitle($name);
    $file->setDescription('Document');
    $file->setMimeType('application/pdf');
    $data = file_get_contents('./uploads/'.$name);
    $createdFile = $service->files->insert($file, array(
          'data' => $data,
          'mimeType' => 'application/pdf',
          'uploadType' => 'multipart'
        ));

A: You'll have to check out Service Accounts. Service Accounts are accounts that belong to the application rather than the user. It acts on the user's behalf to call the APIs so they're accounts aren't really involved.
This way, the uploaded file will go to the email set on the service account which you can control. Once done, you can set the Share settings of the Service Account to with your main account just like what this dev did.
Hope this helps!


text:
Q: How to get first gap in a column containing sequential int values I have a column in a SQL Server database table, there is a column containing integer values and I would like to get the max value unless there is a gap in the series, then I would like to get the first missing value.
For example from the below table, I am looking to get value 4
1
2
null
3

The above is simple, however if the table contains data like below, how can I find which id I am missing, in this case it would be 8
1
3
2
4
null
5
7
6
null
10
9

//////////////////
Edit:
I Initially implemented @podiluska's answer and was going to accept it however when I tested with a table with over 10K rows it was quite slow, so I have taken @vmvadivel's answer and changed it slightly as shown below and it works quite fast, but still not 100% what I wanted:
SELECT Number
FROM
(
    SELECT ROW_NUMBER() OVER(ORDER BY iValue) AS Number
    FROM tblNumbers WHERE iValue IS NOT NULL
) temp
WHERE Number NOT IN
(
    SELECT iValue FROM tblNumbers WHERE iValue IS NOT NULL
)

This works quite well however if all the iValue fields are null then I don't get anything back, but I want it to return 1 as it will be the first value in series, obviously I can handle this in the C# code but I am sure there must be a way of returning 1 if the above query does not return a row?
I have changed the top level Select Number with SELECT Coalesce(Number, 1) but it did not work, any ideas how to solve this?
Thanks

A: If #t is your table
select min(t1.number)+1
from #t t1
left join #t t2
           on t1.number = t2.number-1
where t2.number is null

A: SELECT
    t1.number + 1 AS range_start,
    MIN(t2.number) - 1 AS range_end
FROM test t1
INNER JOIN test t2
    ON t2.number > t1.number
WHERE t1.number IS NOT NULL
GROUP BY t1.number
HAVING t1.number + 1 <= MIN(t2.number) - 1

If you add a number 15 to the table, the output will be:
range_start  range_end
          8          8
         11         14

It finds each successive pair of numbers, with a gap of at least one. It then adds or subtracts one from this, so that the start_range and end_range is the range of the gap.

A: If you have a number table which has sequential int value in it then you can do something like this:
SELECT * FROM
(
    SELECT ROW_NUMBER() OVER(ORDER BY iValue) AS Number FROM tblNumbers
) temp
WHERE Number NOT IN
(
    SELECT [ID] FROM tblFindGaps
)
GO


text:
Q: Output of sybase query in pipe separated format I need some assistance to figure out if its possible to get the output of a sybase sql query in pipe | separated format.
select top 10 * from  mytable

The data returned is as follows
I am using sybase  ASE 15 as my DB to run queries.
name age number
sam 20 1233456

I need the data in below format
name|age|number
sam|20|123456

Thanks in advance

A: This question is not about the database itself but about the client - isql. For isql you can achieve this result but writing the query like that:
select top 10
  name || '|' || convert(varchar, age) || '|' || convert(varchar, number)
from  mytable

Or, like GMB has statet in the comment you can use a client which allows formatting the output. Something other than isql.

A: If you're going to use isql, the best advice is RTFM.  It looks like the -s option will do what you want.  If it leaves trailing blanks, you can pipe it into sed with something like:
isql -s '|' ... | sed -E 's/ +\|//g'


text:
Q: Functional Derivative In Chapter 1 of Lancaster's Quantum Field Theory for the Gifted Amateur, he gives an example of taking the derivative of a functional but doesn't show much work. I was confused how he got the answer.
$$\int g[f(x) + \epsilon \delta(x - x_0)] dx= \int (g[f(x)] + \epsilon \delta(x - x_0) g'[f(x)])dx$$
What rules allow you to do this?

A: The answer can simply be seen by applying Taylor series:
$$
 g[x] = g[x_0] + g'[x_0] \cdot (x-x_0) + ...
$$
In your case we should take $x_0 = f(x)$ and $x=f(x)+\epsilon \delta(x - x_0)$.
You are maybe wondering why is Lancaster using an equal sign (=) when he only took the first (and zeroth) term in Taylor series? The reason for that is because Lancaster is calculating the functional derivative:
$$ \tag{1}
\frac{1}{\epsilon} \lim_{\epsilon \rightarrow 0} \int \left(
g[f(x) + \epsilon \delta(x-x_0)] - g[f(x)]
 \right) \mathrm{d}x
$$
and here it is sufficient to take only the first (and zeroth) term of the Taylor series because all the other term will not contribute to the end result anyway because we have $\lim_{\epsilon \rightarrow 0}$.
The other thing that you may be wondering is, why are we allowed to take Taylor series? Well it turns out that $g[f(x) + \epsilon \delta(x-x_0)]$ is actually defined by the corresponding Taylor series:
$$
g[f(x) + \epsilon \delta(x-x_0)] := g[f(x)] +  \epsilon \delta(x - x_0) g'[f(x)]+...
$$
The reason we particularly like the expression $g[f(x) + \epsilon \delta(x-x_0)]$ is because:

*

*it is compact

*In that form we have very nice analogy between functional derivative and ordinary derivative

A: The best way to think about this is to think about the definition of a derivative. Start with $$g(x + h) \approx g(x) + h\times g'(x).$$ In the limit as $h$ goes to zero, this is the definition of a derivative of a function. Now, replace $x$ with $f(x)$ and replace $h$ with $\epsilon \delta(x-x_0)$. You get: $$ g(f(x + \epsilon \delta(x-x_0)) \approx g(f(x)) + \epsilon \delta(x-x_0)\times g'(f(x)).$$ In calculus of variations, this is known as a 'functional derivative'...in the limit as $\epsilon$ goes to zero.


text:
Q: Setup up own STUN/TURN server or use Twilio STUN/TURN servers? I'm developing a video/voice call app that would be published on Play Store. I've set up the app, but I need to setup STUN/TURN servers.
Which solution would be more effective in terms of handling traffic and cost.
Using STUN/TURN serves provided by Twilio, Xirsys or setting up my own servers.
Could someone please help me understand which is the way to go?


text:
Q: MySQL Query still executing after a day..? I'm trying to isolate duplicates in a 500MB database and have tried two ways to do it. One creating a new table and grouping:
CREATE TABLE test_table as
SELECT * FROM items WHERE 1 GROUP BY title;

But it's been running for an hour and in MySQL Admin it says the status is Locked.
The other way I tried was to delete duplicates with this:
 DELETE bad_rows.*
        from items as bad_rows
        inner join (
                select post_title, MIN(id) as min_id
                from items
                group by title
                having count(*) > 1
        ) as good_rows on good_rows.post_title = bad_rows.post_title;

..and this has been running for 24hours now, Admin telling me it's Sending data...
Do you think either or these queries are actually still running? How can I find out if it's hung? (with Apple OS X 10.5.7)

A: You can do this:
alter ignore table items add unique index(title);

This will add a unique index and at the same time remove any duplicates, which will prevent any future duplicates from occurring. Make sure you do a backup before running this command.


text:
Q: The command I assigned for scroll direction in Flutter does not work       child: Scaffold(
  body: SingleChildScrollView(
    child: Column(
      children: [
        _cardList(context),
        Column(
          children: [
            Expanded(
              child: ListView.builder(
                scrollDirection: Axis.vertical,
                shrinkWrap: true,
                itemCount: 3,
                itemBuilder: (context, index) {
                  return Card(
                    child: Image.asset('assets/images/horizontal.jpg'),
                  );
                },
              ),
            )
          ],
        ),

I created a list and added 3 images under each other. But I can't scroll down. I thought because I did Column in Column. But nothing changed when I deleted the Bottom Column.

A: Wrap your ListView with Expanded for better performance, instead of using   shrinkWrap: true
body: Column(
  children: [
    Expanded(
      child: ListView.builder(
        scrollDirection: Axis.vertical,
        itemCount: 3,

A: you need to disable SingleChildScrollView scroll physic like this:
SingleChildScrollView(
        physics: NeverScrollableScrollPhysics(),//<-- add this
        child: Column(
          children: [
            ListView.builder(
              scrollDirection: Axis.vertical,
              shrinkWrap: true,
              itemCount: 3,
              itemBuilder: (context, index) {
                return Card(
                  child: Image.asset('assets/images/horizontal.jpg'),
                );
              },
            )
          ],
        ),
      ),

both list are scroll vertically you need disable one of them which is SingleChildScrollView.


text:
Q: Is it any way to throw errors inside promises in node.js? js Gurus,
I am writing a parser in nodejs (actually iojs) and I have a typical callback pyramid of doom handled with promises. The issue taking 70% of my time is finding errors inside promises.
    function parseHomeData(home, web) {
      var deferred = Q.defer();
      var homepage = web.url(home).then(function () {
// any error here dies silently
        parser.getHomeInfo(homepage).then(function (parsedHome) {
            console.log(parsedHome);
            deferred.resolve(parsedHome);

        }, function (err) {
            console.log(err);
            throw new Error(err);
        });
    }, function (err) {
        console.log(err);
    });
    return deferred.promise;
};

If I uncomment "any errors here dies silently" it will do. The only way, is to wrap inside try/catch block but even there I can only console.log(error) throw new Error does not work. Is it any way to run iojs with automatic failure option?
Thx

A: Promises catch exceptions and turn them into rejections.  So, if you are inside a .then() handler and you throw an exception, that will generate the same result as returning a rejected promise.  This is how promises work.
So, to make your code work, you just need to return the actual promise that web.url() is creating.  This will also get rid of some antipatterns you have where you are creating promises unnecessarily.
function parseHomeData(home, web) {
    return web.url(home).then(function () {
        // any exception error here becomes the rejected promise
        return parser.getHomeInfo(homepage).then(function (parsedHome) {
            console.log(parsedHome);
            return parsedHome;
        }, function (err) {
            // this handler is only needed if you need the console.log(err) here
            console.log(err);
            throw new Error(err);
        });
    }, function (err) {
        // this handler is only needed if you need the console.log(err) here
        console.log(err);
        throw err;
    });
};

In fact, without the console.log() statements, the code could all just collapse to this:
function parseHomeData(home, web) {
    return web.url(home).then(parser.getHomeInfo.bind(parser));
}

This code block combines several things:

*

*Returns the web.url() promise so if it is rejected for any reason (such as a throw in your .then() handler, that will be returned as a rejected promise from your parseHomeData() function.

*No need to create your own Q promise when you already have one you can just return.

*Once you implement items 1) and 2) above, then rather than resolve() and reject(), you can just return or throw from within the .then() handler.
You can read more about promise anti-patterns in these references:
Promise Anti-patterns (Bluebird github)
Promise Anti-patterns (Tao of Code)
Promise Patterns & Anti-Patterns


text:
Q: Syncfusion PDF on Xamarin.ios Issue Ive just started out using Syncfusion PDF for my Xamarin.ios project and am having an issue with PdfGridImagePosition not working. I have tried all the options but the one I want to use is the 'Fit' option to allow me to keep the aspect ratio of the image.
I have tried both landscape and portrait images with no success. Below is the code Im using to insert the image and try to keep its aspect ratio:
PdfGridRow documentInformationGridSignatureRow = documentInformationGrid.Rows.Add();
        documentInformationGridSignatureRow.Cells[0].Value = "Signature";
        documentInformationGridSignatureRow.Cells[1].Value = " ";
        documentInformationGridSignatureRow.Cells[1].Style.BackgroundImage = CreatePDFImage(signature);

documentInformationGridSignatureRow.Height = 40;
        documentInformationGridSignatureRow.Cells[1].ImagePosition= PdfGridImagePosition.Fit;

Ive tried changing the order around like setting the style for the image position first but it doesn't make any difference.
Hopefully somebody can help.
Many Thanks
Jamie

A: The reported issue is not reproduced from our side and it is working as expected. Please find below the sample which we have tried in our side for your reference.
Sample link: http://www.syncfusion.com/downloads/support/directtrac/214995/ze/PdfGridSample-132405018
Output PDF: http://www.syncfusion.com/downloads/support/directtrac/214995/ze/output306100801
 Note: I work for Syncfusion.


text:
Q: Issue with recursive click on same element Recurivesly called onclick on same element only twice but click action doesn't follow default action,
Idea is that when user click on <input />
it should not popup the file explorer but at first do some async task and
then call click action without user gesture, which in turn open file explorer.
Sample problem
https://jsbin.com/zuzinen/edit?html,js,console,output
<body>
  <input id="inp" type="file" />
</body>

var clicked = false;

function takePermission(cb) {
  setTimeout(function() {
      clicked = true;
      cb();
    }, 2000);
}

function handleClick(e) {
  console.log(clicked)
  if (!clicked) {
    e.preventDefault();
    takePermission(function() {
      document.getElementById('inp').click();
    });

  }
}

document.getElementById('inp').onclick = handleClick;

A: After the first click you assign clicked to true, this means that your if statement does not fire.
So there is no more calls to click() after the first one.


text:
Q: Java TCP split packets I am using spring-integration TCP connections. From the Serializer implementation i write some bytes directly to the given OutputStream.
The first byte seems to be sent on its own (in it's own TCP packet, which is by the way reported malformed by wireshark) and then the remaining bytes in the next packet.
Changing the first two bytes to be written in one call (two byte long array) causes these two bytes to be sent in a seperate packet (not malformed) and the remaning in the next packet. This outcome is reproducible.
Is this something I can (or should) affect? It is causing problems on the reading end, because that equipment apparently expects the entire message to be contained in a single TCP packet.

A:
Is this something I can (or should) affect? It is causing problems on the reading end, because that equipment apparently expects the entire message to be contained in a single TCP packet.

Then the author of this application has no idea of TCP. TCP is a stream based and not a packet based protocol. This means that a single write can result into multiple packets on the wire or multiple writes can result in a single packet.

...which is by the way reported malformed by wireshark...

If you capture the packets on the sender system you probably see the effects of offloading the checksum computing to the network card. In this case wireshark will report the checksums wrong. If you capture the packets in-between or on the receiving end you should see the correct checksum because the network card on the senders machine calculated the checksum before forwarding the packet.


text:
Q: Mac application asking for accessibility permission repeatedly I have created a Mac application written in electron-vue.
It requires keyboard access and screen recording access.
Ideally, when I give permission it should start working immediately.
But my app sometimes work after restarting.
Sometimes, It keeps asking for permission after every restart even though we have given the permission.
I am not able to understand what is being done wrong.
Can you please help?
My package.json.
    "name": "pramod-dektop-creator",
    "version": "0.0.1",
    "description": "pramod-desktop-creator",
    "author": "Pramod <pramod@xyz.com>",
    "scripts": {
        "build": "node .electron-vue/build.js && electron-builder",
        "build:clean": "cross-env BUILD_TARGET=clean node .electron-vue/build.js",
        "build:dir": "npm run build:clean && node .electron-vue/build.js && electron-builder --dir",
        "build:web": "cross-env BUILD_TARGET=web node .electron-vue/build.js",
        "dev": "node .electron-vue/dev-runner.js",
        "pack": "npm run pack:main && npm run pack:renderer",
        "pack:main": "cross-env NODE_ENV=production webpack --progress --colors --config .electron-vue/webpack.main.config.js",
        "pack:renderer": "cross-env NODE_ENV=production webpack --progress --colors --config .electron-vue/webpack.renderer.config.js",
        "postinstall": "electron-builder install-app-deps",
        "rebuild": "electron-rebuild -f -w sqlite3"
    },
    "main": "./dist/electron/main.js",

    "build": {
        "afterSign": "notarize.js",
        "asar": true,
        "productName": "pramod-dektop-creator",
        "appId": "org.pramod.desktop-creator",
        "protocols": {
            "name": "pramod-dektop-creator",
            "schemes": [
                "pramod"
            ]
        },
        "directories": {
            "output": "build"
        },

        "dmg": {
            "sign": false,
            "contents": [
                {
                    "x": 410,
                    "y": 150,
                    "type": "link",
                    "path": "/Applications"
                },
                {
                    "x": 130,
                    "y": 150,
                    "type": "file"
                }
            ]
        },
        "mac": {
            "icon": "build/icons/icon.icns",
            "gatekeeperAssess": false,
            "entitlements": "info.plist",
            "entitlementsInherit": "info.plist",
            "hardenedRuntime": true
        },
        "win": {
            "icon": "build/icons/icon.ico"
        }
    },
    "iohook": {
        "targets": [
            "node-72",
            "electron-70"
        ],
        "platforms": [
            "win32",
            "darwin",
            "linux"
        ],
        "arches": [
            "x64",
            "ia32"
        ]
    },
    "license": "",
}

A: Please check whether you have given permissions to correct application.
How?
Go to Security & Privacy settings.

Right click on your application and select the option.
It will take you to the application for which permission is given.
Cross check whether it is the correct application you are giving access to.
For me, installed application was different than what I gave permission to.
I deleted duplicate application and gave permissions again. After that it started working.
May or may not solve your issue but worth a try.


text:
Q: Bootstrap3 container with responsive image I am new to BS3 and i'm trying to use a responsive image with the img-responsive class that spans the width of the container across all screen sizes and devices. What I have so far works apart from screen break points between 768px and 992px where the image doesn't retain its 100% width. I'm not quite sure where I am going wrong. plus I can not seem to remove  left/right padding so it covers the complete width of the container. Ive tried using Jumbatron with no success.
I simply have an image in my outer container like so: -

Do I need to use rows and column classes for this?


text:
Q: Best Practice for VueJs using laravel mix and placement app.js with bootstrap and app.css from sass I'm trying to figure out the best practice for this, I have bootstrap loaded into my app.js using the line
import 'bootstrap/dist/css/bootstrap.css';

The problem is that my app.js is at the bottom of the page and my placed app.css, generated from sass, is in the header, so bootstrap is taking over all the styles I wrote to over-ride bootstrap.
In the head of my laravel layout template:
<link href="{{ asset('css/app.css?v=1.5') }}" rel="stylesheet">

and in the footer:
<script src="{{ asset('js/app.js?v=1.5') }}"></script>

What's the best practice? Should I somehow be mixing in the bootstrap css using sass - I tried finding that as a solution with no luck. Or maybe I pull my custom css into my js as well - I tried that, but the bootstrap file I merge in comes from my source repository and the app.css is being generated into the public directory.
I'm obviously a bit new to this, and I'm just trying to sort out the best way, working with Laravel, mix and VueJs.
Here's my mix file:
let mix = require('laravel-mix');

mix.js('resources/assets/js/app.js', 'public/js')
 .sass('resources/assets/sass/app.scss', 'public/css');

mix.autoload({
  jquery: ['$', 'window.jQuery', 'jQuery'],
  'popper.js/dist/umd/popper.js': ['Popper']
})

mix.autoload({
    'jquery': ['$', 'window.jQuery', 'jQuery'],
    'vue': ['Vue','window.Vue'],
    'moment': ['moment','window.moment'],
  })

What is the right way to do this, so that my css is after, and therefore takes precedence over, the bootstrap css?

A: You simply have to do following in your app.scss file:
// Bootstrap
@import '~bootstrap/scss/bootstrap';
That will load the bootstrap style dependencies which you immidiatly can use, if you want to overwrite some styling you can create a new file and import that to your scss file under the main bootstrap file.
For instance you create this file inside resources/sass/_custom_bootstrap.scss
now you import that in your app.scss like this:
...
// Bootstrap
@import '~bootstrap/scss/bootstrap';

// custom
@import 'custom_bootstrap';
...

You don't have to add the file in your mix since app.scss is already in the mix file and compiles.


text:
Q: Breeze and Data Access SOA In evaluating Angular + Breeze, does it support tracking changes with the consumed DTOs from services back to the backend Entity Framework?

A: Yes and no.  Breeze tracks the changes on the client, and when you call saveChanges(), it sends the changed entities (with information about what properties changed) to the server.  What happens on the server is up to you, so you could use the received data to modify the states of entities in an existing EF context, and accumulate change tracking info in EF until you decide to save it to the DB.
The provided EF + WebApi server-side components don't do that, however.  They are built to streamline the following use case:

*

*Client performs add/update/delete operations on entities and calls saveChanges().

*Server creates a new EF DbContext and applies the changes to it.

*Server applies validation rules (in the BeforeSaveEntities method), and rejects the save if they fail.

*Server DbContext saves the changes to the database.

In this scenario, there is no long-lived EF DbContext tracking the changes; the change tracking is done on the client, and EF is used to process those changes on the server and save them in the DB.
That probably covers 90% of what most applications require, but there are hooks in place to intercept the save and make server-side changes before the save, and you can override any parts that don't fit your needs.


text:
Q: iFrame doesn't work in Frameset in IE I have an iFrame in an HTML page that is loaded into a frameset frame. The source of the iFrame is a local HTML file. It works fine in Firefox and Chrome but not in IE 11. The iFrame is blank.  The HTML page with the iFrame works fine in IE outside of the frameset.
Is there a solution to the problem?


text:
Q: Cubic and non convex optimisation problems in portfolio optimisation I have the following cost function for portfolio allocation, which considers also the skweness,

w are the weights to be found, mu is the return vector, Sigma is the covariance matrix, K is the co-skewness matrix, gamma is the risk aversion (let's say is a constant number).
This problem is not convex as far as I know and not quadratic but cubic..so how can I minimise it, in order to fall the global minimum rather that a local one?
I guess I cannot use cvxpy, what are the alternatives for such example or ingeneral for higher order moments?

A: I don't think this is convex either. That would imply you need a global MINLP solver (such as Baron, Couenne or Antigone). An alternative is to reformulate the problem as a non-convex quadratic problem (some extra variables and constraints are needed for this). This would allow you to use Gurobi.


text:
Q: BQ google update columns - Exceeded rate limits Scenario is to update column descriptions in tables(About 1500 columns in 50 tables).  Due to multiple restrictions I have been asked to use the bq query command to execute the ALTER TABLE sql for updating column descriptions, thorugh cloud CLI. query -
bq query --nouse_legacy_sql \ 'ALTER TABLE `<Table>` ALTER COLUMN <columnname> SET OPTIONS(DESCRIPTION="<Updated Description>")';
Issue is if I bunch the bq queries together for 1500 columns it is 1500 sql statements.
This is causing the standard Exceeded rate limits: too many table update operations for this table error.
Any suggestions on how to execute it better.

A: You are hitting the rate limit:

Maximum rate of table metadata update operations per table: 5 operations per 10 seconds

You will need to stagger the updates to make sure it happens in batch of 5 operations per 10 seconds. You could also try to alter all the columns in a single table with a single statement to reduce the number of calls required.


text:
Q: ASP.NET MVC ViewModel for collections best practice I have EF classes, for each of them I made model (no inheritance from EF poco classes) with various DAL functionality (get, set, order and etc...).
The BL would be inside the controllers.
Everything looks fine for single instance of model, but now I need to bind to view a list of data.
Below is an example of how I did it.
I'm new to MVC and not sure if it's the best practice to do it:
The Model:
public class CustomerWishlistModel
{
    static storeDataEntities db = new storeDataEntities();

    //Some properties of the model
    public int CustomerID { get; set; }

    public int ProductID { get; set; }

    public string ProductName { get; set; }

    public string BrandName { get; set; }

    public CustomerWishlistModel(){}

    //Get wishlists by customer
    public static List<CustomerWishlist> GetCustomerWishLists(int customerID)
    {
         return db.CustomerWishlists.Where(x => x.CustomerID == customerID).ToList();
    }

    //Convert wishlist to model
    public static CustomerWishlistModel GetWishListModel(CustomerWishlist thisWishList)
    {
        CustomerWishlistModel thisWishListModel = new CustomerWishlistModel()
        {
            CustomerID = thisWishList.CustomerID,
            ProductID = thisWishList.ProductID,
            BrandName = thisWishList.Product.Supplier.BrandName,
            ProductName = thisWishList.Product.Name
       };

       return thisWishListModel;
    }
}

The Controller:
[Authorize]
[HttpGet]
public ActionResult Index(string id)
{
    //Get all wishlists to current customer
    List<CustomerWishlist> thisWishList = CustomerWishlistModel.GetCustomerWishLists(int.Parse(id));

    //Get language from url
    Language thisLanguage = LanguageModel.GetLanguageByCulture(RouteData.Values["language"].ToString());

    if (Session["UserID"] != null && Session["UserID"].ToString() == id && thisWishList != null && thisLanguage != null)
    {
        List<CustomerWishlistModel> thisWishlistModel = new List<CustomerWishlistModel>();

        //Get all wishlists that their status is online and language equals to current
        foreach (CustomerWishlist item in thisWishList)
        {
            if (item.Product.Status == (int)EnumModel.ProductStatus.Online && item.Product.LanguageID == thisLanguage.ID)
            {
                thisWishlistModel.Add(CustomerWishlistModel.GetWishListModel(item));
            }
        }

        return View(thisWishlistModel);
    }
    else
    {
        return RedirectToAction("Login", "Customer");
    }
}

The View:
@model IEnumerable<Store.Models.CustomerWishlistModel>
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
    ViewBag.Title = Resources.Store.WishList;
}
@using (Html.BeginForm())
{
    <h2>@Resources.Store.WishList</h2>

    foreach (Store.Models.CustomerWishlistModel item in Model.ToList())
    {
         item.BrandName...... and other markup tags
    }
}

A: The best practice is to remove any business logic from your controllers, they are only suppose to handle calling appropriate services and passing model data to the view. You models should not have any data access code and instead it's better to abstract gathering data to another class and return a clean model. For example, one of the most popular patterns to abstract DAL is a repository pattern that returns data via simple interface like Customer CustomerRepository.GetCustomer(int id).
All your business logic should also be contained inside services which will call repositories to get required data and the process the data based on your business rules. The service will return a clean model object which your controller will pass to the view. Simple and clean.


text:
Q: Best way to replace text in string Looking for better algorithm / technique for replacing strings in a string variable. I have to loop through an unknown number of database records and for each one, I need to replace some text in a string variable. Right now it looks like this, but there has to be a better way:
using (eds ctx = new eds())
{
    string targetText = "This is a sample string with words that will get replaced based on data pulled from the database";

    List<parameter> lstParameters = ctx.ciParameters.ToList();
    foreach (parameter in lstParameters)
    {
        string searchKey = parameter.searchKey;
        string newValue = parameter.value;
        targetText = targetText.Replace(searchKey, newValue);
    }
}

From my understanding this is not good because I'm over writing the targetText variable, over and over in the loop. However, I'm not sure how structure the find and replace...
Appreciate any feedback.

A:
there has to be a better way

Strings are immutable - you can't "change" them - all you can do is create a new string and replace the variable value (which is not as bad as you think).  You could try using a StringBuilder as other suggest, but it's not 100% guaranteed to improve your performance.
You could change your algorithm to loop through the "words" in targetText, see if there's a match in parameters , take the "replacement" value and build up a new string, but I suspect the extra lookups will cost more than recreating the string value multiple times.
In any case, two important principles of performance improvement should be considered:

*

*Start with the slowest part of your app first - you may see some improvement but if it does not improve the overall performance significantly then it doesn't matter that much

*The only way to know if a particular change will improve your performance (and by how much) is to try it both ways and measure it.

A: StringBuilder will have less memory overhead and better performance, especially on large strings. String.Replace() vs. StringBuilder.Replace()
using (eds ctx = new eds())
{
    string targetText = "This is a sample string with words that will get replaced based on data pulled from the database";

    var builder = new StringBuilder(targetText);

    List<parameter> lstParameters = ctx.ciParameters.ToList();
    foreach (parameter in lstParameters)
    {
        string searchKey = parameter.searchKey;
        string newValue = parameter.value;
        targetText = builder.Replace(searchKey, newValue);
    }
}

A: Actually, there is a better answer, assuming you're doing a large number of replacements. You can use a StringBuilder. As you know, strings are immutable. So as you said, you're creating strings over and over again in your loop.
If you convert your string to a StringBuilder
StringBuilder s = new StringBuilder(s, s.Length*2); // Adjust the capacity based on how much bigger you think the string will get due to replacements. The more accurate your estimate, the better this will perform.

  foreach (parameter in lstParameters)
    {
        s.Replace(parameter.searchKey, parameter.value);
    }
  string targetString = s.ToString();

Now a caveat, if your list only has 2-3 items in it, this might not be any better. The answer to this question provides a nice analysis of the performance improvement you can expect to see.


text: Q: How to send newly created user info from keycloak to spring application? I'm running my application on tomcat,I tried to integrate it to keycloak for SSO.I used spring security adapter for keycloak integration.Now I modified the registration page of keycloak as per my need.The user created succesfully in keycloak.What is the way to send that user info to spring application inorder to store it in my application database.What's the thing I need to do in keycloak to transmit data and What I need to do in spring to retrieve this information.


text:
Q: Tab Bar Hides when Navigate I have Four Tabs in My Project By Default First tab is selected which is Home Class When user navigate to any other class by selecting any tab i have to check that time that if user is loggedin in my application then he will navigate to class which he selected else he move to Login Screen.
 if(appDelegate.sessionId==0)
            {

                Login *objLogin=[[[Login alloc] initWithNibName:@"Login" bundle:nil] autorelease];

                [self.navigationController pushViewController:objLogin animated:YES];

            }
            else
            {
                CreatePoll *objLogin=[[[CreatePoll alloc] initWithNibName:@"CreatePoll" bundle:nil] autorelease];
                [self.navigationController pushViewController:objLogin animated:YES];

            }

}
IF i navigate to Login Screen my tab bar gets Hidden and when i debug the code i came to know that Create Poll class is also get called in background i check this link to show tab bar which is hidden but cant get success. Please help me guys i m stucked with this problem from last 3 days.
Cant see my tabbar in Login Screen.Please Help

A: just write this code in viewWillAppear: method to hide and show the UITabBar
AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
[appDelegate.tabBarController.tabBar setHidden:NO];

UPDATE:
post these method in AppDelegate.m file and when you want to show and hide the Tabbar at that time create AppDelegate object and call this method
- (void) hideTabBar:(UITabBarController *) tabbarcontroller {

    int height = 480;

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];

    for(UIView *view in tabbarcontroller.view.subviews) {
        if([view isKindOfClass:[UITabBar class]]) {
            [view setFrame:CGRectMake(view.frame.origin.x, height, view.frame.size.width, view.frame.size.height)];
        }
        else {
            [view setFrame:CGRectMake(view.frame.origin.x,view.frame.origin.y, 320, 436)];
        }
    }
    [UIView commitAnimations];
}

- (void) showTabBar:(UITabBarController *) tabbarcontroller {

    int height = 480;

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];

    for(UIView *view in tabbarcontroller.view.subviews) {

        if([view isKindOfClass:[UITabBar class]]) {
            [view setFrame:CGRectMake(view.frame.origin.x, height, view.frame.size.width, view.frame.size.height)];
        }
        else {
            [view setFrame:CGRectMake(view.frame.origin.x, view.frame.origin.y, view.frame.size.width, height)];
        }
    }

    [UIView commitAnimations];
}