text:
Q: Error When Creating Contacts in Sandbox Environment I'm new to Salesforce Administration and I've recently created a sandbox environment to test changes before deploying them to my company, and I've run into a bit of a snag.
In our production environment, there are no problems adding Contacts, however in my Sandbox environment, when I try to add a contact (I've already successfully created an Account), I get the following Error:

Apex trigger ContactTrigger caused an unexpected exception, contact your administrator: ContactTrigger: execution of BeforeInsert caused
  by: System.QueryException: List has no rows for assignment to SObject:
  ()

Below is our ContactTrigger handler. Is there something I'm missing?
public with sharing class ContactTriggerHandler  {
    public static void ValidateNewContacts(List<Contact> newContacts)
    {
        (new ContactService()).ValidateContacts(newContacts);
    }

    public static void CreateClientContacts(List<Contact> newContacts)
    {
        (new ContactService()).CreateClientContacts(newContacts);
    }

    public static void UpdateContactsExternalId(List<Contact> newContacts)
    {
        (new ContactService()).UpdateContactsExternalId(newContacts);
    }

    public static void CorrectContactsAccountsContactCount(List<Contact> contactsToCorrectAccounts)
    {
        (new ContactService()).CorrectContactsAccountsContactCount(contactsToCorrectAccounts);
    }

    public static void CorrectContactsAccountsContactCountOnUpdate(List<Contact> contactsToCorrectAccounts)
    {
        Set<Id> accountIdSet = new Set<Id>();
        Set<Id> contactsThatChangesAccounts = (new Map<Id, sObject>(contactsToCorrectAccounts)).keySet();

        for(Id contactId : contactsThatChangesAccounts)
        {
            accountIdSet.add((Id)Trigger.OldMap.get(contactId).get('AccountId'));
            accountIdSet.add((Id)Trigger.NewMap.get(contactId).get('AccountId'));
        }

        (new AccountService()).CorrectAccountsContactCount(accountIdSet);
    }
}

I appreciate any help provided.
Edited to provide the Trigger itself
trigger ContactTrigger on Contact (before insert, after insert, before update, after update, after delete)
{
if(Trigger.isBefore && Trigger.isInsert)
{
    Filters.ITriggerComparisonFilter contactFilter = new Filters.AllNewRecords();
    List<sObject> newContacts = new List<sObject>(contactFilter.FilterResults(Trigger.new, Trigger.oldMap));
    ContactTriggerHandler.ValidateNewContacts(newContacts);
}

if(Trigger.isAfter && Trigger.isInsert)
{
    Filters.ITriggerComparisonFilter contactFilter = new ContactFilters.ContactsWithClientNumbersTriggerFilter();
    List<sObject> newContacts = new List<sObject>(contactFilter.FilterResults(Trigger.new, Trigger.oldMap));
    ContactTriggerHandler.CreateClientContacts(newContacts);

    contactFilter = new Filters.AllNewRecords();
    newContacts = new List<sObject>(contactFilter.FilterResults(Trigger.new, Trigger.oldMap));
    ContactTriggerHandler.CorrectContactsAccountsContactCount(newContacts);
}

if(Trigger.isBefore && Trigger.isUpdate)
{
    Filters.ITriggerComparisonFilter contactFilter = new ContactFilters.ContactsWithChangedEmailsTriggerFilter();
    List<sObject> contactsWithUpdatedEmails = new List<sObject>(contactFilter.FilterResults(Trigger.new, Trigger.oldMap));
    ContactTriggerHandler.UpdateContactsExternalId(contactsWithUpdatedEmails);
}

if(Trigger.isAfter && Trigger.isUpdate)
{
    Filters.ITriggerComparisonFilter contactFilter = new ContactFilters.ContactThatHaveBecomeITKAdminsTriggerFilter();
    List<sObject> newContacts = new List<sObject>(contactFilter.FilterResults(Trigger.new, Trigger.oldMap));
    ContactTriggerHandler.CreateClientContacts(newContacts);

    contactFilter = new ContactFilters.ContactsWithChangedAccountsTriggerFilter();
    newContacts = new List<sObject>(contactFilter.FilterResults(Trigger.new, Trigger.oldMap));
    ContactTriggerHandler.CorrectContactsAccountsContactCountOnUpdate(newContacts);
}

if(Trigger.isAfter && Trigger.isDelete)
{
    Filters.ITriggerComparisonFilter contactFilter = new Filters.AllOldRecords();
    List<sObject> oldContacts = new List<sObject>(contactFilter.FilterResults(Trigger.new, Trigger.oldMap));
    ContactTriggerHandler.CorrectContactsAccountsContactCount(oldContacts);
}

A: I don't see it happens in the code you've posted, but that exception means that somewhere you have a query which returns no rows being assigned directly to an sObject variable, probably similar to this:
Account a = [SELECT ... FROM Account WHERE Id = contact.AccountId LIMIT 1];

The issue can be easily fixed by finding the offending query and restructuring it to assign into a list instead, because a list won't get mad if you have no rows to fill it. That would look like this:
Account[] accounts = [SELECT ... FROM Account WHERE Id = contact.AccountId LIMIT 1];
if(!accounts.isEmpty()){
    Account a = accounts[0];
    //whatever else you need to do with it
}

Most likely, it should actually be written to loop over multiple query results, but this example should suffice to fix your problem.


text:
Q: Slow response time getting json data from Flask application from javascript I have a Flask application that takes requests from javascript, queries a database, then sends the data back to be visualized using D3.js. Calls to the database return rougly 5mb of data. I am getting very slow response times (roughly 20 seconds) between when the response is sent from flask until when it has finished loading into a javascript variable in d3.
Any idea why it is so slow to get data sent between my d3 and Flask?
If I simply print the json string to a blank page in the browser the response is nearly instantaneous. I get similar (fast) performance if I just write the json string to a static file then load that with d3. I am fairly certain the problem is simply piping the data directly through to d3. I have also tried calling flask using $.getJSON in a query and the results are similarly slow. Why is Flask slow at returning the json string but not just rendering it to the browser?
In D3 I call:
d3.json("/test", function(data) {
    console.log(data);
});

Example Flask call
@app.route('/test')
def get_json_object():
    a = {....some large dictionary....}
    return jsonify(**a)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to know if a certain amount of time has passed while user is using my app? I want to send an event to firebase if user spend a minimum of 20sec on my app. This looks simple enough as I only have to create a timer. Here is what I've done so far:
Subscription sessionEvent = Observable.timer(20, TimeUnit.SECONDS)
            .subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(aLong -> Log.v("tag", "hello"));

I am subscribing inside the onResume of my activity while unsubscribing inside onPause.
This is however a problem since if my activity started another activity, onPause will also be called. That means that the timer will stop even though the user is still on my app.
What I'm looking for is when the user closed the app, that's when the timer will stop. I already tried using the onUserLeaveHint, unfortunately, starting another activity will also call that method.

A: You can use ActivityLifecycleCallbacks to monitor the state of all activities in your app.  You can register one with Application.registerActivityLifecycleCallbacks() and it will be called for every Activity that goes through its lifecycle methods.  When you have a total of 0 started activities, you can be sure that the user is not looking at your app, but it's also entirely possible that they might switch back in at any time from the task switcher.

A: I dont think that there is a direct way to detect if your app is on foreground or background if you have multiple activities. However you can use OnResume and OnPause to track the state of each activity. Use boolean Shared Preferences to track the state of each activity and periodically run a background service using repeating alert to simply check if there is at least on activity on screen. StartTime-StartTime = duration.

A: Here is an example Application implementation that uses the ActivityLifeCycleCallbacks mentioned in Doug Stevenson's answer.  The onTrimMemory() method is used to detect when the app is backgrounded:
public class MyApplication extends Application
        implements Application.ActivityLifecycleCallbacks {

    private static final String TAG = "MyApplication";

    private Handler handler;
    private final Runnable generateEvent = new Runnable() {
        @Override
        public void run() {
            Log.d(TAG, "User engagement is 20 secs");
            // Generate analytics event
        }
    };

    private boolean mAppInForeground;

    @Override
    public void onCreate() {
        super.onCreate();

        registerActivityLifecycleCallbacks(this);
        handler = new Handler(getMainLooper());
        mAppInForeground = false;
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);

        if (level >= ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) {
            Log.i(TAG, "onTrimMemory: App in background");
            handler.removeCallbacks(generateEvent);
            mAppInForeground = false;
        }
    }

    @Override
    public void onActivityStarted(Activity activity) {
        // Called when any activity is started
        Log.d(TAG, "onActivityStarted: Was foreground=" + mAppInForeground);
        if (!mAppInForeground) {
            mAppInForeground = true;
            handler.postDelayed(generateEvent, 20 * 1000);
        }
    }

    // Remaining ActivityLifecycleCallbacks are not used
    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {}
    @Override
    public void onActivityResumed(Activity activity) {}
    @Override
    public void onActivityPaused(Activity activity) {}
    @Override
    public void onActivityStopped(Activity activity) {}
    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {}
    @Override
    public void onActivityDestroyed(Activity activity) {}
}

A: I ended up using <uses-permission android:name="android.permission.GET_TASKS"/> to check if the app is on foreground. here is the method that I used:
public boolean isAppForeground(Context context) {
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

    if (am == null) return false;

    if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
        List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();

        if (processInfos != null && !processInfos.isEmpty()) {
            ActivityManager.RunningAppProcessInfo info = processInfos.get(0);
            if (info == null || info.processName == null || !info.processName.contentEquals(context.getPackageName()))
                return false;
        } else {
            return false;
        }
    }
    else{
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);

        if (tasks != null && !tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (topActivity == null || topActivity.getPackageName() == null || !topActivity.getPackageName().equals(context.getPackageName())) {
                return false;
            }
        } else {
            return false;
        }
    }

    return true;
}

The method is located in my custom Application class. I used registerActivityLifecycleCallbacks to check inside the onActivityPaused if the app is on foreground, I will not stop the timer, but if it's not, I will stop the timer.


text:
Q: Trying to restrict access to New and Upload in document library I am trying to restrict access to both adding a new file and uploading a file to a SharePoint Online Document Library, but without removing permissions from users, I just need those two buttons to disappear, or just the full toolbar to disappear, and I also need to remove the edit functionality, then again, without removing permissions. If nothing happened when the buttons were pressed, it would also be fine. Is it possible to do this? Please note I'm a beginner at SharePoint and I may need a more detailed answer. I have been looking around with SharePoint Designer with no luck, I managed to get rid of the new and edit forms in a List but I can't figure out how do to it in a document library.
EDIT: Any solution will work as long as access is restricted.
EDIT 2: The reason why I need to do this is because I am accessing this document library from a K2 form outside SharePoint Online, and users should not be able to directly access the library.
EDIT 4: Sorry for the edit 3, I needed to block metadata editing, I just created a blank edit form for the library.

A: Yes, you can do this easily. New/Upload buttons for a Document library are available at two locations. We will work on those seperately

*

*In top Ribbon under "File" tab. At this location you can use script editor webpart and hide the section completely. Click on site setting Icon -> EditPage -> Insert a webpart -> choose Script editor under Media and content -> and insert below script:

 #Ribbon.Documents.New{
   display: none;
 }

*Hide from Library action ribbon. This we can simply do by setting "No toolbar" in web part properties. Click on site setting Icon -> Edit page -> Click on Edit web part -> select "no toolbar" -> Apply & OK

Edit location for Edit Page


text:
Q: react-router v6 removes useHistory, but useNavigate misses implementation I have a scenario where we have a CustomHistory object, it's a hack in an electron application, so that certain routes are not stored in the history.
Previously we would use
const customHistory = useHistory() as CustomHistory;

This history object was provided to the router.
Is it no longer possible to access this through useNavigate?
Likewise, the history object would provide canGo(x) which would return a boolean. The useNavigate does not provide this functionality. I.e. to disable navigation buttons within an electron app. I wasn't able to find this in the migration documentation or the v6 documentation.


text:
Q: Azure Service Bus File Streaming I have a little console service running on my server that exposes it's endpoint to an azure service bus namespace.  I am using webHttpRelayBinding in Streamed mode.  I am using the microsoft sample just for testing located here: http://code.msdn.microsoft.com/windowsazure/Relayed-Messaging-Bindings-a6477ba0#content.
I have a console app client running on another computer that connects to my service bus namespace and makes a call to my service interface.  I am using the sample call GetImage and in that method all I am doing is returning Stream of a 5MB PDF file.
On the server that is hosting my service I have a 20MB upload/download fiber line.  It's wide open and extremely fast.  When I open a browser and hit my service as so: https://namespace.servicebus.windows.net/Image/GetImage it pulls the 5MB PDF file correctly however it will only stream the file to me at 90K to 100K per second.  I thought at first I was being restricted by upload speeds from the server but with a 20MB fiber up and down that is hard to justify.  So I moved the service to my home computer with a measly 750K upload speed.  I fired up the service and the relay is hosted.  I then had a friend of mine hit the service from his browser at his house to pull the same 5MB PDF file and lo and behold it transfers the file to him at 90K to 100K per second.
I am stumped as to why this is.  Can someone please give me insight here?  I can show you all the code you need but thought it sufficient to give the description entirely to the problem and reference the microsoft sample I am using.
Thank you in advance.

A: A much later response however I found this question relevant to what I'm working on right now.
As suggested, I recommend trying NetTcpRelayBinding with Hybrid connection mode.
http://msdn.microsoft.com/en-us/library/microsoft.servicebus.tcprelayconnectionmode.aspx
By default NetTcpRelayBinding uses Relay which means that traffic goes through Azure. In Hybrid only handshake is done via Azure and then direct connection is established. Keep in mind though that you will loose transfer security with Hybrid setup which may or may not require to setup message level security.
If you try this approach, please let us know is speed increases.
Thanks!

A: A few things to consider:

*

*When using service bus relay, under the worst connectivity conditions (NAT on both sides, firewalls, no direct connections), all of your requests will go through Service Bus's datacenters. While the download/upload speeds of your server are important, you also should consider the networking capabilities of the datacenter in between. Where are you hosting your relay? Have you tried using a datacenter that's closer to you and your users?

*How are you hosting your service, is it WCF or on IIS? You might want to do a benchmark without the relay involved to validate that the slowdown indeed comes from SB, and not some other factors.

*Are you constraint to using only http-based protocols? You might have a better performance if you use netTcpRelayBinding instead (I'm not completely sure about it streaming capabilities though).


text:
Q: Fatal error: Class 'Varien_Data_Collection_Filesystem' when taking backup We kept the scheduled backup in night.
but when we checked this , we are getting an error under System > Tools > Backup

Fatal error: Class 'Varien_Data_Collection_Filesystem' not found in /app/code/core/Mage/Backup/Model/Fs/Collection.php on line 35

We have checked in var folder, there also no backup folder.

A: Filesystem.php is a library class file which  basically exit at  your magentoDir/lib/Varien/Data/Collection.
May be some reason it does not exist at  your magentoDir/lib/Varien/Data/Collection
So my suggestion is to copy this file from a default magento instance and put that at  your error system.


text:
Q: How to add a new column to a set of Function records I'm creating a function that returns a set of records from a table titled "Sequence". As part of this table, I am also analyzing another table ("Log_Alpha") and inserting appropriate information into the record. To date what I have done is overwrite an existing columns data, and then rename the column afterwards in my select call to the function (IE SELECT * FROM Production1(parameters) as tbl(xxx,xxx,xxx,NewColumnName Real,xxx,xxx...)
This works very well, however I need to retain the original data and therefore would prefer to rather add a new column to the record. But how do I do this, as the record is grabbing its column names directly from the table "Sequence".
My code shows rc."seqLogsIn" being the column where (average daily SED) data is being captured. This then gets called from the database by the SELECT query seen at the bottom of this code, where the column is renamed to "AvLogSED".
Here is the complete function, however you really only need to focus on the SELECT AVG("logSED") section.
To clarify, I want to create a new column in the record (called AvLogSED, as part of the function) and inject the data into that new column, instead of "misappropriating" seqLogsIn. How do I do that?
I am running PostgreSQL 9.2.9, compiled by Visual C++ build 1600, 64-bit on a Windows 7 desktop PC (local server copy also running on desktop).
-- Function: production1(timestamp without time zone, timestamp without time zone)
-- DROP FUNCTION production1(timestamp without time zone, timestamp without time zone);

CREATE OR REPLACE FUNCTION production1(tme1 timestamp without time zone, tme2 timestamp without time zone)
  RETURNS SETOF record AS
$BODY$
DECLARE
  rc Record;
  tmeA timestamp without time zone;
  tmeB timestamp without time zone;
  AverageSED Real;

BEGIN

tmeA := tme1 + '1 day'::interval;
tmeB := tme2 + '1 day'::interval;

-- get average SED for all logs in time/date range
SELECT AVG("logSED")::Real
  FROM "Log_Alpha"
  WHERE "logTime" >= DATE_TRUNC('DAY', tme1) AND "logTime" < DATE_TRUNC('DAY', tme2 + '1 day'::interval) -- Calculate average for each day from 00:00 hours from first day thru to 23:59:59.99 for last day
  INTO averageSED;

  FOR rc IN
    SELECT *, averageSED
    FROM "Sequence"
    WHERE "Sequence"."seqMinute" = 150 AND "Sequence"."seqTime" >= tmeA AND "Sequence"."seqTime" <= tmeB
    ORDER BY "Sequence"."seqTime"

  LOOP
    rc."seqTime" = rc."seqTime" - '1 day'::interval;

    -- Use a subquery to calculate the average SED for all logs for the day pertaining to this record date field
    SELECT AVG("logSED")::Real into rc."seqLogsIn" FROM "Log_Alpha" -- Replace column seqLogsIn data from sequence table with Daily Average SED data. The column title can be renamed in function (SELECT) call as required
      WHERE "Log_Alpha"."logTime" >= DATE_TRUNC('DAY', rc."seqTime") and "Log_Alpha"."logTime" < (DATE_TRUNC('DAY', rc."seqTime") + '1 day'::interval); -- Date truncated (always start at 00:00 hours of the day) to counter offset induced by mn variable

    RETURN NEXT rc;
  END LOOP;
END
$BODY$
  LANGUAGE plpgsql STABLE
  COST 100
  ROWS 1000;
ALTER FUNCTION production1(timestamp without time zone, timestamp without time zone)
  OWNER TO postgres;

This is the select function call that "renames" the appropriate column to AvLogSED.
select * from production1('2016-02-27 00:00:00','2016-03-11 00:00:00') as tbl(seqTime timestamp without time zone,seqMinute integer,AvLogSED Real,seqLogVolIn Real,seqFinishedVol Real,seqChipTonnes Real,seqSawdustTonnes Real,seqBinSortVol Real,seqTraySortVol Real,seqFlitchSortVol Real,seqBinSortPieces Real,seqTraySortPieces Real,seqFlitchSortPieces Real,seqBinSortRejects Real,seqBinSortSlash Real,seqTraySortRejects Real,seqTraySortSlash Real,seqCanterCants Real,seqSecBandCants Real,seqSecBandRecycled Real,seqCS1Cants Real,seqCS3Cants Real,seqE1Pieces Real,seqE1ManualRejects Real,seqE1OperatorRejects Real,seqE1ThicknessRejects Real,seqE1NoSortRejects Real,seqE1VolumeIn Real,seqE1VolumeOut Real,seqE2Pieces Real,seqE2ManualRejects Real,seqE2OperatorRejects Real,seqE2ThicknessRejects Real,seqE2NoSortRejects Real,seqE2VolumeIn Real,seqE2VolumeOut Real,seqE1Bypass Real,seqE2Bypass Real,seqBSVolumeIn Real,seqPrimaryRuntime Real,seqBinLugSpeed Real,seqBinLugFill Real,seqTrayLugSpeed Real,seqTrayLugFill Real,seqCompressor1kWh Real,seqCompressor2kWh Real,seqCompressor3kWh Real,seqCompressor4kWh Real,seqKiln1and2GJ Real,seqKiln3GJ Real,seqKiln4GJ Real,seqKiln5GJ Real,seqKiln6GJ Real,seqKiln7GJ Real,seqKiln8GJ Real,seqKiln9GJ Real,seqKiln10GJ Real,seqKiln11GJ Real,seqKiln12GJ Real,seqFlitchTray10 Real,seqFlitchReturn Real,seqBSLiftOut Real,seqSecCantRuntime Real,seqSecBandRuntime Real,seqSecCS1Runtime Real,seqSecCS3Runtime Real,seqEdger1Runtime Real,seqEdger2Runtime Real,seqBinSorterRuntime Real,seqTraySorterRuntime Real,seqFlitchSorterRuntime Real,seqReEntryE1Minutes Real,seqReEntryChipMinutes Real,seqAwaitingLogs Real,seqBSUtilisation Real,seqTSUtilisation Real,seqFSUtilisation Real,seqDebarkerRuntime Real,seqReEntryChipCount Real,seqReEntryE1Count Real,Reserved2 Real,Reserved3 Real,Reserved4 Real,Reserved5 Real,Reserved6 Real,AverageSED Real)

A: You can return an arbitrary record like this:
RETURN NEXT ROW(val1, val2, ...);

That way you are not limited by an existing type.

A: The solution was found to be as follows:
FOR rc IN
    SELECT *, AverageSED, avDailySED
    FROM "Sequence"
    WHERE "Sequence"."seqMinute" = mn AND "Sequence"."seqTime" >= tmeA AND "Sequence"."seqTime" <= tmeB
    ORDER BY "Sequence"."seqTime"
  LOOP

By adding AverageSED and avDailySED to SELECT, these columns were automatically added to the rc record. One hook that I discovered was that I had to also explicitly push data into avDailySED in record rc. By this I mean my existing line of code:
SELECT AVG("logSED")::Real into avDailySED FROM "Log_Alpha" -- Store average SED value in new column

Would result in a blank avDailySED column. Changing to this solved the issue:
SELECT AVG("logSED")::Real into rc.avDailySED FROM "Log_Alpha" -- Store average SED value in new column


text:
Q: How to escape "/" in a sed command in Puppet script? In a config file, I'm trying to replace PREFIX=/jenkins with, say, PREFIX=/foobar.
On the (bash) command line, this works fine:
sed -i.bak s/PREFIX=\\/jenkins/PREFIX=\\/foobar/g /etc/default/jenkins

However, in a Puppet script (.pp file):
exec { 'Change-prefix':
  command => "sed -i.bak s/PREFIX=\\/jenkins/PREFIX=\\/foobar/g /etc/default/jenkins",
  path    => ["/bin"],
}

produces:
err: /Stage[main]//Exec[Change-prefix]/returns: change from notrun to 0 failed:
sed -i.bak s/PREFIX=\/jenkins/PREFIX=\/foobar/g /etc/default/jenkins
returned 1 instead of one of [0]

How to escape the sed command properly? Or is something else the matter?
I also tried with \\\/, but that yields: warning: Unrecognised escape sequence '\/'

A: In cases where your sed expression contains a '/', you may want to consider using a different delimiter. I chose the pipe symbol in this example.
sed -i.bak 's|PREFIX=/jenkins|PREFIX=/foobar|g' /etc/default/jenkins
Using this syntax in your Puppet manifest would be a lot cleaner and more readable, in my opinion.

From the sed info page:

\%REGEXP%'
       (The%' may be replaced by any other single character.)
 This also matches the regular expression REGEXP, but allows one to
 use a different delimiter than `/'.  This is particularly useful
 if the REGEXP itself contains a lot of slashes, since it avoids
 the tedious escaping of every `/'.  If REGEXP itself includes any
 delimiter characters, each must be escaped by a backslash (`\').

A: On many versions of sed you can use a different character as a delimiter to avoid having to escape / e.g it's quite common to use | or #
sed -i.bak 's#PREFIX=/jenkins#PREFIX=/foobar#g' /etc/default/jenkins

A: Whoa, whoa... hang-on! Sed in a puppet manifest is a bit crazy. You should be using the file_line resource, from the puppetlabs stdlib.
(you should install the entire module, but here is the custom resource type)
https://github.com/puppetlabs/puppetlabs-stdlib/blob/master/lib/puppet/type/file_line.rb
Example:
  file_line { 'sudo_rule':
    path => '/etc/sudoers',
    line => '%sudo ALL=(ALL) ALL',
  }

A: Turns out \\\\/ works.
For example:
exec { 'Change-prefix':
  command => "sed -i.bak s/PREFIX=\\\\/jenkins/PREFIX=\\\\/foorbar/g /etc/default/jenkins",
  path    => ["/bin"],
}

Edit: ...but of course using a different delimiter, as Kenny and Iain suggested, is a lot cleaner solution!


text:
Q: Spring configuring bean with component scan - Field userRepository in service.UserService required a bean of type 'repository I have checked many examples but they are generally about marking the classes with @Repository or @Service etc...For example here it is about the packages to scan and I am not sure where and in which method I should make scan.
I have a simple application and a User model, UserRepository extending JPA repository and a service. When I try to connect db it is ok by default settings but whenever I want to use custom configuration then the program cannot find the UserRepository class even if I mark it as @Repository. The program still needs repository class configuration bean.
Here is my service method:
@Service
public class UserService {
    @Autowired
    UserRepository userRepository;
    public User findById(Long id) {
        return userRepository.findById(id).get();
    }
}

The model is:
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Builder
@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    private String name;
    private Date birthday;
}

UserRepository class:
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}

And here is the configuration that I try to achieve:
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactory",
        transactionManagerRef = "transactionManager")
public class UserDbConfig {

    @Primary
    @Bean("dataSource")
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/testSchema");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        return dataSource;
    }

    @Primary
    @Bean(name = "entityManagerFactory")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(
            EntityManagerFactoryBuilder builder,
            @Qualifier("dataSource") DataSource dataSource
    ) {
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setGenerateDdl(true);

        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);
        factory.setPackagesToScan("com.practice.multiDatabase.model");
        factory.setDataSource(dataSource());
        return factory;
    }

    @Bean("transactionManager")
    public PlatformTransactionManager transactionManager(@Qualifier("entityManagerFactory") EntityManagerFactory entityManagerFactory) {

        JpaTransactionManager txManager = new JpaTransactionManager();
        txManager.setEntityManagerFactory(entityManagerFactory);
        return txManager;
    }
}

Here is my project structure and main method(I haven't add anything special)

The output is:
***************************
APPLICATION FAILED TO START
***************************

Description:

Field userRepository in com.practice.multiDatabase.service.UserService required a bean of type 'com.practice.multiDatabase.repository.UserRepository' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.practice.multiDatabase.repository.UserRepository' in your configuration.

Extra notes:
When I add this to main method
@SpringBootApplication(scanBasePackages = {
        "com.practice.multiDatabase.repository",
        "com.practice.multiDatabase.controller",
        "com.practice.multiDatabase.service",
        //"com.practice.multiDatabase.config"
        //, "com.practice.multiDatabase.model"
})
public class MultiDatabaseApplication {

    public static void main(String[] args) {
        SpringApplication.run(MultiDatabaseApplication.class, args);
    }

}
The program is working but probably it is ignoring the config file because I have explicitly write the controller-sevice-repository and if I uncomment the config folder as well then still getting same error.

A: Omg. I have found it. I have just added
basePackages = {"com.practice.multiDatabase.repository"}

to config and it is working now.
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        basePackages = {"com.practice.multiDatabase.repository"},
        entityManagerFactoryRef = "entityManagerFactory",
        transactionManagerRef = "transactionManager")
public class UserDbConfig {


text:
Q: mariabackup from remote mariadb10.3 galera | '/var/lib/mysql/' (Errcode: 2 "No such file or directory") The following setup applies:

*

*3 node galera cluster in docker

*backup container that should run mariabackup to get the data out of the galera cluster

*network is fine. backup container can ping galera

*mariadb/mariabackup version 10.3

*the backup container only has mariabackup installed.

The command that i used
mariabackup --backup --host=<service_name> --port=3306 --user=root --password=<pass> --target-dir=/backup

When trying to backup from galera-cluster from within the backup-container i get the following error
00] 2019-09-15 23:38:34 Connecting to MySQL server host: mdb_mariadb, user: root, password: set, port: 3306, socket: /var/run/mysqld/mysqld.sock
[00] 2019-09-15 23:38:34 Using server version 10.3.18-MariaDB-1:10.3.18+maria~bionic-log
[00] 2019-09-15 23:38:34 Warning: option 'datadir' points to nonexistent directory '/var/lib/mysql/'
[00] 2019-09-15 23:38:34 Warning: MySQL variable 'datadir' points to nonexistent directory '/var/lib/mysql/'
[00] 2019-09-15 23:38:34 Warning: option 'datadir' has different values:
  '/var/lib/mysql/' in defaults file
  '/var/lib/mysql/' in SHOW VARIABLES
mariabackup based on MariaDB server 10.3.18-MariaDB debian-linux-gnu (x86_64)
[00] 2019-09-15 23:38:34 uses posix_fadvise().
mariabackup: Can't change dir to '/var/lib/mysql/' (Errcode: 2 "No such file or directory")
[00] 2019-09-15 23:38:34 my_setwd() failed , /var/lib/mysql/

What i tried.

*

*researching various gists for clues

*researching the mariadb scripts provided by the server install

*trying different option combinations, but always the same error.

Question:

*

*Has anyone made remote backups and can tell me how you succeeded?

*Is the approach wrong and is there a better way to make hot backups once per day and incremental during the day?

A: Wrong approach - mariabackup isn't designed to work remotely. See also MDEV-15075.
So you need to run mariabackup locally on one of the nodes in the cluster.
To prevent the backup from slowing down the cluster, you can prevent the node from engaging Flow Control and allow it to fall behind the other nodes by doing:
SET GLOBAL wsrep_desync=ON;

Once the backup is completed, you can do:
SET GLOBAL wsrep_desync=OFF;

(See wsrep_desync in the MariaDB knowledge-base.)
Obviously, don't direct any database traffic at the node while you're running the backup.


text:
Q: Can't build a go file with flag buildmode=plugin on mac I'm doing a MIT lecture lab
I ran in to errors with the line
go build -race -buildmode=plugin ../mrapps/wc.go, the error is :
In file included from _cgo_export.c:3:
/usr/local/include/stdlib.h:181:5: error: 'TARGET_OS_EMBEDDED' is not defined, evaluates to 0 [-Werror,-Wundef-prefix=TARGET_OS_]```


text:
Q: SonarQube 5.4 svn lines of commit In SonarQube 5.4 is it possible to get the number of commits per user from the svn and who introduced the violation.

A: Number of commits per user - no. Not currently.
Who introduced an issue - with high probability*. New issues will automatically be assigned to the last committer on the relevant line.
* Note that the last committer on the line where the issue is raised is not always the one responsible for the issue.


text:
Q: find values from key,val object by giving its key I am trying to find values from KEY,VALUE pair of object by giving the KEY.
The key is in array.
var arr = ["1398","1392","1390"];
var objects = { 1384: "registerItem", 1386: "createGroups", 1388: "vipNumbers", 1390: "targetNumbers", 1392: "ignoredNumbers", 1394: "globalConstants", 1396: "Users", 1398: "systemConfiguration", 1400: "applicationErrors" };

I need to find all the values from objects whose key is in array. How can i do this ?
So far I did this :
for (var a=0; a<arr.length;a++) {
    console.log(arr[a]);
}

for (var k in objects){
    if (typeof objects[k] !== 'function') {
         console.log(k + ", " + objects[k]);
    }
}

A: You can find the value by objects[ arr[ 0 ] ] will return systemConfiguration
Where 0, 1 and 2 are the key of arr

You can loop to find all. Like:

var arr = ["1398", "1392", "1390"];
var objects = {
  1384: "registerItem",
  1386: "createGroups",
  1388: "vipNumbers",
  1390: "targetNumbers",
  1392: "ignoredNumbers",
  1394: "globalConstants",
  1396: "Users",
  1398: "systemConfiguration",
  1400: "applicationErrors"
};

for (var key in arr) {
  if( typeof objects[arr[key]] != 'undefined' ) console.log(objects[arr[key]]);
}

A: You can use underscore.js pick method.

var arr = ["1398","1392","1390"];
var objects = { 1384: "registerItem", 1386: "createGroups", 1388: "vipNumbers", 1390: "targetNumbers", 1392: "ignoredNumbers", 1394: "globalConstants", 1396: "Users", 1398: "systemConfiguration", 1400: "applicationErrors" };

console.log(_.pick(objects,arr))

//For Values
console.log(_.chain(objects).pick(arr).values().value());
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

A: you can loop your array and then check if the current index is in your object:

var objects = { 1384: "registerItem", 1386: "createGroups", 1388: "vipNumbers", 1390: "targetNumbers", 1392: "ignoredNumbers", 1394: "globalConstants", 1396: "Users", 1398: "systemConfiguration", 1400: "applicationErrors" };
var arr = ["1398","1392","1390"];
arr.forEach(function(entry) {
    if(entry in objects) console.log(objects[entry]);
});

A:
How can i do this ?

Just use map method by passing a callback function.

var arr = ["1398", "1392", "1390"];
var objects = {
  1384: "registerItem",
  1386: "createGroups",
  1388: "vipNumbers",
  1390: "targetNumbers",
  1392: "ignoredNumbers",
  1394: "globalConstants",
  1396: "Users",
  1398: "systemConfiguration",
  1400: "applicationErrors"
};

console.log(arr.map(a => objects[a]));

A:
I need to find all the values from objects whose key is in array.

In an ES5 environment, I'd probably use forEach and push, checking with in or hasOwnProperty (depending on whether you want to check the prototype) to see if the object had the key:

var arr = ["1398","1392","1390"];
var objects = { 1384: "registerItem", 1386: "createGroups", 1388: "vipNumbers", 1390: "targetNumbers", 1392: "ignoredNumbers", 1394: "globalConstants", 1396: "Users", 1398: "systemConfiguration", 1400: "applicationErrors" };
var values = [];
arr.forEach(function(key) {
    if (key in objects) {
        values.push(objects[key]);
    }
});
console.log(values);

In an ES2015+ environment, I'd probably use for-of instead of forEach:

const arr = ["1398","1392","1390"];
const objects = { 1384: "registerItem", 1386: "createGroups", 1388: "vipNumbers", 1390: "targetNumbers", 1392: "ignoredNumbers", 1394: "globalConstants", 1396: "Users", 1398: "systemConfiguration", 1400: "applicationErrors" };
const values = [];
for (const key of arr) {
    if (key in objects) {
        values.push(objects[key]);
    }
}
console.log(values);

Finally, if you already know the object contains the properties and don't need a check at all, you could use map:

var arr = ["1398","1392","1390"];
var objects = { 1384: "registerItem", 1386: "createGroups", 1388: "vipNumbers", 1390: "targetNumbers", 1392: "ignoredNumbers", 1394: "globalConstants", 1396: "Users", 1398: "systemConfiguration", 1400: "applicationErrors" };
var values = arr.map(function(key) {
    return objects[key];
});
console.log(values);

...which in ES2015+ could be use concise arrow function:

const arr = ["1398","1392","1390"];
const objects = { 1384: "registerItem", 1386: "createGroups", 1388: "vipNumbers", 1390: "targetNumbers", 1392: "ignoredNumbers", 1394: "globalConstants", 1396: "Users", 1398: "systemConfiguration", 1400: "applicationErrors" };
const values = arr.map(key => objects[key]);
console.log(values);

A: Try reducing the array, and either create a new object {} and take the key,value pairs for those keys which are exists in the object, or create a new array [] and keep pushing the values for those keys which are exists in the object. depends on your requirement.
arr.reduce(function(init, key) {
    if(objects[key]) { init[key] = objects[key]; };
    return init;
}, {});

OR
arr.reduce(function(init, key) {
        if(objects[key]) { init.push(objects[key]); };
        return init;
}, []);

and using underscore or lodash better to iterate from the array side and use the object as map, instead of iterating from object side, here you go:
_(arr).map(k=>objects[k]).compact().value()


text:
Q: Where do raid items go if your Inventory is full? I'm getting to the point where I'm running out of inventory room for my favorite Exotic and Legendary weapons.  I know that when you miss a rare or better engram drop in an activity they show up in the Post Office to pick up latter.
Does this also hold true for mission rewards, chest loot, and raid boss drops?
Not just for engrams, but named items like the raid armors and weapons as well?  I need to know if I need to vault items when I run the raid to make sure I have the available inventory space.

A: I don't know about raids from personal expedrience but I know that end of mission rewards from other things (eg story and strikes) can have things sent to you by post office. I would assume it is the same for raid rewards and  Link of Origin has confirmed it in comments.
My opinion would be to always make room to be on the safe side anyway.


text:
Q: Limiting diversity of attributes in Wikidata / SPARQL Query I want to create a dataset of 100 paintings querying from Wikidata.
With my current query, for each painting I retrieve the artist (creator), the movement, the year it was painted (inception) and so on.
I would like to fix a limit to the number of different movements in my data set. Same for the artists. (i.e. I will have only paintings from n random genres at unspecified proportions).
So for example if I limit to 2 movements I would have only Pop-Art and Cubist paintings or Neoclassic and Impressionist, etc.
SELECT ?itemLabel ?pic ?movementLabel ?creatorLabel ?inception
WHERE
{
?item wdt:P31 wd:Q3305213 .
?item wdt:P135 ?movement .
?item wdt:P170 ?creator .
?item wdt:P18 ?pic .
?item wdt:P571 ?inception
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
}
LIMIT 100


text:
Q: Are BOOST_LIKELY and __builtin_expect still relevant? I understand what is explained here as well as these would include hints to CPU for static branch prediction.
I was wondering how relevant are these on Intel CPUs now that Intel CPUs have dropped support for static prediction hints as mentioned here. Also if I understand how it works now, the number of branch instructions in the path would be the only thing that the compiler can control and which branch path is predicted, fetched and decoded is decided at runtime.
Given this, are there any scenarios where branch hints in code are still useful for software targeting recent Intel processors, perhaps using conditional return or for avoiding the number of branch instructions in the critical path in case of nested if/else statements?
Also, if these are still relevant, any specifics on gcc and other popular compilers are appreciated.
P.S. I am not for premature optimization or for peppering the code with these macros, but I am interested in the topic as I am working with some time critical code and still like to reduce code clutter where possible.
Thanks

A: As in the comments section for your question you correctly figure out that:

*

*There are no static branch prediction hints in opcode map anymore on Intel x86 CPUs;

*Dynamic branch prediction for "cold" conditional jumps tend to predict the fallthrough path;

*The compiler can use __builtin_expect to reorder what path of the if-then-else construct will be placed as a fallthrough case in generated assembly.

Now, consider a code base being compiled for multiple target architectures, not just Intel x86. A lot of them do have either static branch hints, dynamic branch predictors of different complexity, or both.
As an example, Intel Itanium architecture does offer an extensive system of prediction hints for all types of instructions: control flow, load/store etc. And Itanium was designed to have code being extensively optimized by a compiler with all these statically assigned instructions slots in a bundle and hints.
Therefore, __builtin_expect is still relevant for (rare) cases when 1) correct branch prediction information was too hard to deduce automatically by a compiler, and 2) the underlying hardware on at least one of target architectures was also known to be unable to reliably predict them dynamically. Given that certain low-power processors include primitive branch predictors that do not track branch history but always choose the fallthrough path, it starts to look beneficial. For modern Intel x86 hardware, not so much.


text:
Q: RAID 1 Mirror Error with Two Western Digital 500GB Drives I have Windows 7 Ultimate 64 bit installed on a Western Digital 500GB drive (WD5000BEVT-22ZAT0) that was partitioned automatically by Windows as 100MB System Reserved and 465.66GB drive C.
There is also an unallocated second Western Digital 500GB drive (WD5000BPVT-22HXZT1) that I want to use for RAID 1 to mirror the first drive but I get an error message stating

"ALL DISKS HOLDING EXTENTS FOR A GIVEN VOLUME MUST HAVE THE SAME SECTOR SIZE, AND THE SECTOR SIZE MUST BE VALID."

I uninstalled Windows patch KB-982018 but I still get the same error message. Could you please let me know how to resolve this?

A: The problem is that fsutil does not really report everything as some "helpers" and KB articles tell you. I just had that case: Combining a WD-RED 3 TB with an Seagate Barracuda XT 3 TB.
fsutil fsinfo ntfsinfo <drive_letter> showed both as identical 512 bytes per sector. The Sysinternals ntfsinfo does the same.
But then I used smartctl.exe -a /dev/sda from smartmontools (get it from here: https://sourceforge.net/projects/smartmontools/files/smartmontools/ ).
And THAT one finally showed the real reason, which Windows does not show...
For the WD-RED WD30EFRX-68AX9N0, smartctl -a /dev/sda says:
Sector Sizes:     512 bytes logical, 4096 bytes physical

For the Seagate ST33000651AS, smartctl -a /dev/sdb says:
Sector Sizes:     512 bytes logical, 512 bytes physical

So for everyone having that problem and not knowing why Windows refuses to mirror even if fsutil confirms the same "sector size", use smartctl to see the REAL stuff.

A: It looks like you are having trouble with Advanced Format.
The WD5000BPT uses advanced format, while your current drive, WD5000BEVT, does not.
Advanced format simply means that the sector size of these newer drives are now 4k bits instead of 512 bits. This allows drive manufacturers to build larger, cheaper drives. More info.
Western Digital has an alignment tool that can be found here. It may help your issue.

A: Cameron did give you excellent info on the topic. Using the alignment tool should enable you to freely use both drives.
A couple of notes from me:
 - Having two different drives in a RAID array potentially increases the chances that a drive would drop out of the array due to differences in the firmware, speed, etc. I'd try to have as similar drives as possible for the most stable RAID array and better data safety.
 - WD Blue isn't really recommended for RAID usage as it does not have the required features such as TLER for safer and more stable performance in RAID environments. I'd try to stick to NAS/RAID class drives for better safety and stability (WD Red is a good example).
Post back if you need more info!
Captain_WD.


text:
Q: Setting the height as % of its parent with height: auto I wrote this codepen that does not work.
HTML

  variable content length  variable content length  variable content length  variable content length  variable content length  variable content length  variable content length

CSS
.a{
  height: 500px;
  width: 70px;

}

.c{
  height: 50%;
  background-color: red;
  display: inline-block;
}

a is just a container
b is the content div with variable content size.
is there a way to do it? c can have whatever position as well. But: .c must be half the size of its variable parent

A: Give a height to b too :
.b {
   height: 100%;
}

To set the height of an element in %, its parent must have a height property too (in px or in % (same rule in case it's %)).
If the height is dynamic, set the overflow property of the a-element to auto.

A: Here's a working solution. Notice I changed some of the colors for clarity, sorry about that.
http://codepen.io/anon/pen/WrvLJv
.a{
  height: 500px;
  width: 70px;
  background:blue;
  overflow-y:hidden;
}

.b{
  width:100%;
  background:grey;
  position:relative;
}

.c{
  position:absolute;
  top:0;
  left:0;
  width:100%;
  height: 50%;
  background-color: red;
  display: inline-block;
  z-index:99999;
}

Changes introduced:
1. Added position:relative to .b and position:absolute to .c, while positioning .c on the top left corner.
2. Added a width and height of, respectively, 100% and 50% to .c.
If i recall correctly, the rest is just for demonstrative purposes. Hope I understood your question and helped. By the way, try adding more content to the text, see if it works for you.


text:
Q: Smoothing contour lines in a levelplot and ignoring values less than 0 I am trying to make a "smoothed" contour plot using the lattice package and curious if is any way to "ignore" half of the values in my matrix.  A little difficult to explain but hopefully my code clarifies this question.
link to my data
https://www.dropbox.com/s/a1todt21f1wzkuk/data.matrix.xlsx
code:
#load necessary packages
require(xlsx)
require(lattice)
require(latticeExtra)

#import data
my.data<-read.xlsx("C:/Users/eckmannm/dropbox/data.matrix.xlsx", sheetName="1",row.names=TRUE)
my.data.matrix<-as.matrix(my.data)

#make ranges for axis
Max.Depth.Values<-(c(1,2,4,6,8,10,12,14,16,18,20))
Trap.Depth.Values<-(c(1,2,4,6,8,10,12,14,16,18,20))

#specify color ramp
col.l <- colorRampPalette(c('red', 'orange', 'yellow', 'green', 'cyan', 'blue'))

#make lattice plot
(colorplot<-
levelplot(
my.data.matrix,
row.values=(Trap.Depth.Values),
column.values=(Max.Depth.Values),
col.regions=col.l,
at=seq(from=0,to=18,length=101),
lattice.options=list(key=list(cex=4)),
aspect = "fill",
xlim=c(1,20),
ylim=c(1,20),
panel = panel.2dsmoother,
ylab=list("Trap Depth (m)",cex=1.4),
xlab=list("Max Depth",cex=1.4),
main=list("CPUE of Redside Shiners at Different Depths",cex=1.6),
colorkey=list(at=seq(from=0, to=18, length=80),
              labels=list(at=c(0,3,6,9,12,15,18),
                          labels=c("0","3", "6", "9","12", "15", "18")))))

With the code panel=panel.2dsmoother, I am able to create a smoothed image (see image 1 below), but this graph is completely misleading because I am trying to ignore all the values that are less than 1 (they should be left uncolored).  When I don't use panel=panel.2dsmoother, I get a more "correct" image but it is very pixelated because I have too few values (see image 2 below).

Are there any suggestions or is this even possible?

A: R handles NA sensibly. Try to replace your negatives
my.data.matrix[my.data.matrix <0]=NA


text:
Q: Complex Structure on Manifold of Maps Suppose $M$ is a compact smooth manifold and $V$ is a compact complex manifold. I want to show that the spaces $C^{k,\alpha}(M,V)$ and $W^{k,p}(M,V)$ (the latter for $kp>\dim M$) are complex analytic Banach manifolds, compatibly with the tautological complex structure on the tangent spaces of these smooth Banach manifolds (for $f:M\to V$, the tangent space at $f$ is the space of sections of $f^*T_V$ of regularity $C^{k,\alpha}$ or $W^{k,p}$).
I saw this statement in a paper of Douady (available here: http://www.numdam.org/item/SB_1964-1966__9__7_0). It is stated in the beginning of section 3 without any indication of proof.
Why does the manifold of maps have a complex structure if the target is complex?

A: The usual way to give charts on $C^{k,\alpha}(M,V)$ or $W^{k,p}(M,V)$ is to fix a connection (usually coming from a metric) on the tangent bundle $T_V$, and then using exponentiation with respect to this. It is easy to see that what we need for holomorphicity of this chart is the holomorphicity of the individual exponential maps $\exp_x:T_xV\to V$ (at least near $0$). Below, I show how to construct a smooth map $e:T_V\to V$ (defined on a neighborhood of the zero section) such that each $e_x:=e|_{T_xV}$ maps $0$ to $x$, has derivative equal to identity at $0$ and is holomorphic near $0$. This will clearly suffice.
Let $x\in V$ be any point. Pick a local holomorphic coordinate system $z_1,\ldots,z_n$ near $x$ which identifies $x$ with $0$ and a neighborhood $U$ of $x$ with an open set $\Omega\subset \mathbb C^n$. Without loss of generality, let us assume that $B_2=\{z\in\mathbb C^n\;|\;\|z\|\le 2\}\subset\Omega$. Choose a cutoff function $\chi:\mathbb C^n\times\mathbb C^n\to\mathbb R$ which is $1$ in a neighborhood of $B_1\times B_1$ and zero outside $B_2\times B_2$. Then, defining $\sigma(z,w) = (z,\chi(z,w)\cdot(w-z))$ gives a function $\sigma:\mathbb C^n\times \mathbb C^n\to\mathbb C^n\times\mathbb C^n = T_{\mathbb C^n}$ which has the following properties. For each $z$, $\sigma(z,z)=(z,0)$, $w\mapsto\sigma(z,w)$ is holomorphic for $w$ close to $z$ (for $z\in B_1$) and $\frac{\partial\sigma}{\partial w}(z,z) = (\text{Id},\text{Id})$ for all $z\in B_1$.
We can view $\sigma$ (after extension by zero) as a map $\sigma:U\times V\to T_U\subset T_V$ with the following properties. For all $y\in U$ and $y'\in V$, we have  $\sigma(y,y')\in T_yV$ with $\sigma(y,y)=0$, $\sigma(y,\cdot):V\to T_yV$ holomorphic near $y$ (for $y$ close to $x$) and finally, $\nabla\sigma(y,\cdot)|_y:T_yV\to T_yV$ is the identity map (for $y$ close to $x$). As a result, we conclude that given any point in $V$, we can find for it an open neighborhood $U$ and a smooth map $\sigma_U:U\times V\to T_U$ with the following properties: (1) $\sigma_U(y,y')\in T_yV$ for all $y\in U$, $y'\in X$,
(2) For any $y\in U$, denoting $y'\mapsto\sigma_U(y,y')$ by $\sigma_{U,y}:V\to T_yV$, we have $\sigma_{U,y}(y) = 0$ and $\nabla\sigma_{U,y}|_y = \text{Id}:T_yV\to T_yV$, and, (3) $\sigma_{U,y}$ is holomorphic in a neighborhood of $y$.
Now, choose a finite open cover of $V$ by such open $U$'s (each equipped with a corresponding $\sigma_U$). Let $\{\rho_U\}$ be a partition of unity on $V$ subordinate to this cover. Now, define $\sigma:V\times V\to T_V$ by the equation
\begin{align*}
 \sigma(y,y') = \sum_U\rho_U(y)\sigma_{U}(y,y')
\end{align*}
Note that $\sigma$ maps the diagonal of $V\times V$ identically onto the zero section of $T_V$ and that its derivative along the diagonal is the identity map. Thus, applying the inverse function theorem, we get an open neighborhood $\mathcal U\subset T_V$ of the zero section and a smooth map $\tilde\sigma:\mathcal U\to V\times V$ which is inverse to $\sigma$. Let $e:\mathcal U\to V$ be the projection of $\tilde\sigma$ onto the second coordinate of $V\times V$. This $e$ is the desired fibrewise holomorphic exponential map.


text:
Q: How to call Apify Google Search Scraper Task Using JQuery/Ajax? I am learning to use apify/google-search-scraper through their API call. The document is given here.
I am bit confused with their documentation as I am new. Especially I need the help to configure the call. It
$.ajax({
   url : '',
   method : "POST",
   contentType: "application/json; charset=utf-8",

   data : {

   },
   success:function(response) {
     console.log(response.data);
   }

 });

url: what should I write here?
data : Should I pass parameters here?
Thanks in advance.

A: You need to use run task API endpoint to run it. You can use synchronous run same as asynchronous.
If you want to run the endpoint using AJAX you can use:
$.ajax({
   url : 'https://api.apify.com/v2/actor-tasks/<your task name>/runs?token=<your api token>',
   method : 'POST',
   contentType: 'application/json; charset=utf-8',
   success:function(response) {
     console.log(response.data); // Actor run object
   }

 });

If you need to get data from task run as well you need to wait until it finishes. Then get data from default dataset using get dataset items API endpoint. The good thing is that you can use waitForFinish param in calling run and it waits for it finishes.
const getItemsFromDataset = (datasetId) => {
    $.ajax({
       url : `https://api.apify.com/v2/datasets/${datasetId}/items?format=json`,
       method : 'GET',
       contentType: 'application/json; charset=utf-8',
       success:function(response) {
         console.log(response); // Items from dataset
       }

     });
}

$.ajax({
   url : 'https://api.apify.com/v2/actor-tasks/<your task name>/runs?token=<your api token>&waitForFinish=120',
   method : 'POST',
   dataType: 'json',
   data : JSON.stringify ({
      "queries" : "query you want to"
   }),
   success:function(response) {
     console.log(response.data); // Actor run object
     getItemsFromDataset(response.data.defaultDatasetId)
   }

 });

You need to finish error handling in examples.
EDIT: Added queries param to override query you want to scrape.


text:
Q: Show pop up on each table row I want show a popup when I click the text "lihat" on the table row. The code I use is this:
<?php
$no=1;
while($result = mysql_fetch_array($query)){
    echo"
";
    echo"" .$no. "	";
    echo"" .$result[create_time]. "	";
    echo"" .$result[mesin]. "	";
    echo"" .$result[part]. "	";
    echo"" .$result[indikasi]. "	";
    echo"" .$result[pelapor]. "	";
        if($result[status]=='BELUM DIKERJAKAN'){
            echo''.TUNGGU.'	';}
        elseif($result[status]=='DIKERJAKAN'){
            echo''.DIKERJAKAN.'	';}
        elseif($result[status]=='TUNDA'){
            echo''.DITUNDA.'	';}
        else{
            echo''.SELESAI.'	';}
    echo"Lihat	";
    echo"
";
$no++;
}

Any solution?

A: The general solution would be to use ajax to send a request ( either get or post ) to your pltd-siantan/home_wo.php page and the callback assigned to the ajax function would then display the popup. You can get many different javascript routines to create the popup, probably the best known is Lightbox which you can find here


text:
Q: system.out of object to string Very new to Java so all help is appreciated, but please give the more direct answer possible.
I am trying to change a System.out.println statement to one that will be displayed in a JOptionPane. This is my first attempt at GUI, and find myself hopelessly lost.
I have Strings being printed through several methods in order to display one snippet of output. The part of the output I want to go in one pane, so I think the easiest way might be to concatenate a string.
I have an ArrayList  hard that holds a Card value. I overloaded the toString method in Card for the ranks, and the Suit enum that the Card uses returns Strings ("Heart", Spade", etc.)
for(int x = 0; x < hand.size(); x++){
    System.out.println(hand.get(x));
} //correctly prints the code

I was trying to do
        String handString = "";
    for(int x = 0; x < hand.size(); x++){
        handString = handString.concat(hand.get(x)); //also tried concat(toString(hand.get(x))
    }

Can anyone tell me why I am not able to change the Card toString and why it prints to the console, but why I can't put it to a string? I have a feeling this is very obvious but nothing I can find online seems to help with my combination of enums and class objects.
Also, how would I go about turning several printings to the console to one printing in a JOptionPane?

A: Can you try:
for(int x = 0; x < hand.size(); x++){
   handString += hand.get(x);
   handString += "\n";
}

The plus(+) operator takes care of conversion to String (using the toString() method for objects - which you have overriden).
You can also use the foreach loop here (much shorter, personal preference though):
for (Card card : hand) {
    handString += card;
    handString += "\n";
}

A: You might want to explicitly call .toString() on the Card-object:
for(int x = 0; x < hand.size(); x++){
    handString = handString.concat(hand.get(x).toString());
}

Afterwards, of course, you need to also update whatever is tied to handString.

Cleaner version:
for (Card c : hand) {
    handString += c;
}


text:
Q: ListView SelectedIndexChanged items getting inserted twice I have a list of clauses in my database and a listview in my custom pane in VSTO.
When I select or drag and drop a list item, it gets copied twice. I found this answer.
 Listview ItemSelectionChanged fires twice?
But I dont have a isSelected method for my EventArgs e.
Below is my code, please help me out, I want the data/text to be copied only once.
private void clauseList_SelectedIndexChanged(object sender, EventArgs e)
{
    ListView.SelectedListViewItemCollection col = clauseList.SelectedItems;

    string temp = clauseList.FocusedItem.Text;
    clauseList.DoDragDrop(temp, DragDropEffects.Move);

    Microsoft.Office.Interop.Word.Selection currentSelection = Globals.ThisAddIn.Application.Selection;
    Microsoft.Office.Interop.Word.Range range = currentSelection.Range;
    currentSelection.TypeText(temp);
    currentSelection.TypeParagraph();
    clslst(select);
}

public void clslst(object s)
{
    DataAccess data = new DataAccess();
    List<ClauseDetails> details = new List<ClauseDetails>();
    details.AddRange(data.ClausesRelated(s));

    string FromtextFromDoc;
    FromtextFromDoc = Globals.ThisAddIn.Application.Selection.Text;
    Microsoft.Office.Interop.Word.Document docs = Globals.ThisAddIn.Application.ActiveDocument;
    List<string> clslist = new List<string>();
    string aa = "";
    int f = 0;

    string tempindex = "";
    foreach (Paragraph paragraph in docs.Paragraphs)
    {
        Style style = paragraph.get_Style() as Style;
        string styleName = style.NameLocal;
        //var sty = style.Font;
        //fontstyle = sty.Name;
        //fontsize = sty.Size;
        if (styleName.Equals("Heading 1"))
        {
            f += 1;
            if (f == 2)
            {
                tempindex = aa;
                f = 0;
                clslist.Add(tempindex);
                aa = "";
            }
        }
        if (f > 0)
        {
            aa += paragraph.Range.Text;
        }
    }
    clslist.Add(aa);
    List<string> ClausesNotPresent = new List<string>();
    List<string> ClausesPresent = new List<string>();

    for (int i = 0; i < clslist.Count; i++)
    {
        for (int j = 0; j < details.Count; j++)
        {
            if (clslist[i].Contains(details[j].clausetitle) || clslist[i].Contains(details[j].clause))
            {
                ClausesPresent.Add(details[j].clausetitle + "\n" + details[j].clause);
            }
        }
    }
    List<string> test = new List<string>();

    for (int z = 0; z < details.Count; z++)
    {
        test.Add(details[z].clausetitle + "\n" + details[z].clause);
    }
    if (ClausesPresent.Count < details.Count)
    {
        ClausesNotPresent.AddRange(test.Except(ClausesPresent));
    }
    for(int m=0;m<ClausesNotPresent.Count;m++)
    {
        ClausesNotPresent[m] = "\n"+ ClausesNotPresent[m];
    }

    clauseList.Clear();
    for (int i = 0; i < ClausesNotPresent.Count; i++)
    {
        clauseList.Items.Add(ClausesNotPresent[i]);
    }
}


text:
Q: How can we create a cylindrical viewpager? I am trying to implement a cylindrical view pager something like this(Instead of square pages I need circular pages).

I tried ViewPager with previous and next page boundaries
How can I make a view like this?

A: I suggest you to use Fancy Cover Flow, this is exactly what you looking for
<it.moondroid.coverflow.components.ui.containers.FeatureCoverFlow
        android:id="@+id/coverflow"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        coverflow:coverHeight="@dimen/cover_height"
        coverflow:coverWidth="@dimen/cover_width"
        coverflow:maxScaleFactor="1.5"
        coverflow:reflectionGap="0px"
        coverflow:rotationThreshold="0.5"
        coverflow:scalingThreshold="0.5"
        coverflow:spacing="0.6" />

A: Use viewpager with padding, and use PageTransformer  for this purpose.refer this quiz


text:
Q: Pub/sub in web2py? When user joins (database insert) how do I get notified immediately? Creating a web2py app in which users log in by scanning a UPC-equipped card or sign up as new customers and when those things happen, I'd like to be informed immediately.
For example, a customer scans in and we find she needs to update her membership because it's near expiration, so that notification would appear in the admin console in real time.
What is the best way to do obtain instant notifications in web2py when a database record is inserted?

A: If the database insert is handled via a particular controller action, just add some code to the controller to send the email notification. If the inserts can happen via multiple different avenues, you can instead use an _after_insert callback in the model definition.
To send the email message asynchronously, you can use the built-in scheduler to queue the email to be sent by a worker process.

A: OK, it looks like the solution I'm looking for is tornado+comet_messaging, [here on Github][1].
[1] https://github.com/abhayashenoy/pycon-apac/blob/master/web2py/gluon/contrib/comet_messaging.py


text:
Q: jQuery Children giving undefined result So, I have the following markup:

Content

jQuery(document).on( 'click', '.rhpcon', function(e) {
    var rhccont= jQuery(this).children().find('.rhccont').html();
    alert(rhccont);
});

However, I keep getting "Undefined" as the alert.
I am guessing it is the children that is wrong.
Any suggestions?

A: You don't need .children() as .find() searches the descendant elements. Use:
var rhccont= jQuery(this).find('.rhccont').html();

jQuery(document).on('click', '.rhpcon', function(e) {
  var rhccont = jQuery(this).find('.rhccont').html();
  alert(rhccont);
});

Content

You could also use .children() instead of .find() like:
var rhccont= jQuery(this).children('.rhccont').html();

But again, not both together. As the documentation on these functions states:

The .find() and .children() methods are similar, except that the
  latter only travels a single level down the DOM tree.


text:
Q: How to Make a Single Subscription Box for Multiple Feeds Well I was wondering How can I make a single subscription for multiple feeds so that visitors can sign up to whatever blog they like. Well I have multiple blogs on various niche topics and I need a subscription box that gives user the option of choosing from feeds which they like by using tick options method. So for example I have three niche blogs like Web trends, Holiday Blog and Photography Blog and I want a single subscription box with a ticker option to choose what all feeds they wish to subscribe too.
Example:
Subscribe by Email:
Choose what topic you wish to Subscribe to:

*

*Web Trends

*Holidays

*Photography

(Tick options available for topics)

Instead of managing three subscription boxes giving users a choice of subscribing to blogs they like. I am using feedburner subscription on blogs.
So is there a way of doing this instead of maintaining multiple subscription boxes. Also can we make a feed count for the combined feed subscription to make it more viral and eye catching. All I want is some code or if there is any site or tool which performs this then please redirect me there. A bit of CSS charm is also welcomed.:) BTW I HAVE multiple blogs on weebly and Blogger with three on weebly itself. (http://geniusknight.weebly.com) An answer will be much appreciated. :)

A: I believe there are 2 questions in yours:

*

*How can my site offer the ability to pick the content my readers want to subscribe to?

*How can I allow my readers to pick a channel that suits them in a list of options?

The first question should probably be addressed by the subscription tool. As Feedbin does in your screenshot, when you try to subscribe, they show you that the source has multiple feeds and that you can pick one or many. Right now the boxes don't show any label. You probably have to add a title to the feed <link> tags in your HTML.
The second question can be addressed with tools like SubToMe. This is a univeral "follow" button. When the user clicks on it, they can pick their favorite tool to perform the subscription. Some tools are just plain RSS readers like Feedbin, some other tools use emails like Blogtrottr.


text:
Q: Failed to open error in libchart library in php I'm using Libchart library in my project to generate graphs. I'm trying to execute example in libchart but I'm getting following error.

imagepng(generated/demo1.png): failed to open stream: No such file or
  directory in
  C:\xampp\htdocs\test\fileupload\libchart\classes\view\plot\Plot.php on
  line 284

this is my code
include "libchart/classes/libchart.php";
$chart = new VerticalBarChart(500, 250);
$dataSet = new XYDataSet();
$dataSet->addPoint(new Point("Jan 2005", 273));
$dataSet->addPoint(new Point("Feb 2005", 321));
$dataSet->addPoint(new Point("March 2005", 442));
$dataSet->addPoint(new Point("April 2005", 711));
$chart->setDataSet($dataSet);
$chart->setTitle("Monthly usage for www.example.com");
$chart->render("generated/demo1.png");

when I change the last line of code to $chart->render(); then it opens binary format in my browser.
Could any one please help me to solve this error?

A: this is my complete code
<?php
include "libchart/classes/libchart.php";

class fileupload
{

  var $htmlID_type = "type";
  var $type_uploadfile = 0;
  var $type_generategraphs = 1;
  var $content_html = "";

    function __construct()
    {
        $this->__switch();
        $this->__print();
    }

  function __switch()
 {

    enter code here
        $this->param_type = $this->getParamType();

        switch ($this->param_type)
        {`enter code here`
            case $this->type_uploadfile :
                $this->selectFileUplaod ();
                break;

            case $this->type_generategraphs :
                $this->generateGraphs();
                break;

        }

    }

    function __print()
    {
        print <<<HEREDOC

        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

                        {$this->content_html}

HEREDOC;
    }

  function getParamType()
    {
        if (isset ( $_GET [$this->htmlID_type] ))
        {
            return $_GET [$this->htmlID_type];
        }
        else
            return $this->type_uploadfile;
    }

    function selectFileUplaod()
    {

       $con=mysqli_connect("localhost","root","","test");
      // Check connection
        if (mysqli_connect_errno())
        {
               echo "Failed to connect to MySQL: " . mysqli_connect_error();
          }

        $result = mysqli_query($con,"SELECT
              income_id,
              month,
              paint_cost,
              parts_cost,
              repair_cost,
              excess_Suspense,
              sublet,
              remove_refit_cost
              FROM income");
        echo "
Bundamba Income
";
        echo "

         Paint
         Parts
         Remove Refit Cost
         Repair
         Excess Suspense
         Sublet

";

      while($row = mysqli_fetch_array($result))
      {
       echo "
";
       echo "" . $row['paint_cost'] . "	";
       echo "" . $row['parts_cost'] . "	";
       echo "" . $row['remove_refit_cost'] . "	";
       echo "" . $row['repair_cost'] . "	";
        echo "" . $row['excess_Suspense'] . "	";
        echo "" . $row['sublet'] . "	";
       echo "
";
      }
      echo "
";
      echo "
";
      $result1 = mysqli_query($con,"SELECT
              cost_of_saleID ,  paint_liquid ,
              paint_consumables,
              workshop_consumables,
              parts_purchased,
              wages_paintshop,
              wages_workshop,
              suplier_discount,
              sublet_cost
              FROM  cost_of_sale
                LIMIT 0 , 30");
        echo "
Bundamba cost of sale
";
        echo "

         Paint Consumables
         Paint Liquid
          Parts Purchased
          Workshop Consumables
          Wages - Paintshop
          Wages - Workshop
          Supplier Discounts
          Sublets Costs

";

      while($row = mysqli_fetch_array($result1))
      {
       echo "
";
       echo "" . $row['paint_consumables'] . "	";
       echo "" . $row['paint_liquid'] . "	";
       echo "" . $row['parts_purchased'] . "	";
       echo "" . $row['workshop_consumables'] . "	";
       echo "" . $row['wages_paintshop'] . "	";
       echo "" . $row['wages_workshop'] . "	";
       echo "" . $row['suplier_discount'] . "	";
       echo "" . $row['sublet_cost'] . "	";
       echo "
";
      }
      echo "
";
    $this->content_html = <<<End_Of_String

            <FORM action="uploadFile.php?{$this->htmlID_type}={$this->type_generategraphs}" method="POST" />
             <input type="submit" value="Income vs Cost" style="margin-top:20px">
             <input type="submit" value="Income vs Cost Ratio" style="margin-top:20px">
            </FORM>

End_Of_String;

   // mysqli_close($con);

}

    function generateGraphs()
    {
        echo  getcwd();
        print "rrrrr";
       header("Content-type:image/png");

       $chart = new VerticalBarChart(500, 250);

       $dataSet = new XYDataSet();
       $dataSet->addPoint(new Point("Jan 2005", 273));
       $dataSet->addPoint(new Point("Feb 2005", 321));
       $dataSet->addPoint(new Point("March 2005", 442));
       $dataSet->addPoint(new Point("April 2005", 711));
       $chart->setDataSet($dataSet);
       $chart->setTitle("Monthly usage for www.example.com");

        $chart->render("demo/generated/demo1.png");
        readfile("demo/generated/demo1.png");

       // $im = imagecreatefrompng("demo/generated/demo1.png");
       // header('Content-Type: image/png');
       //imagepng($im);
       //imagedestroy($im);

    }

}

$obj = new fileupload();
?>

A: I got the same error now when trying to plot the piechart using LibChart library.  The problem is that you would not have created a folder named 'generated' in your current folder.. but the name given for the image is generated/demo1.png which says that generated is a folder containing the file "demo1.png". So, just give 'demo1.png' instead of 'generated/demo1.png' and try running the snippet.. I got the output just now!!


text:
Q: Can I differentiate between "Delete Post Permanently" and "Empty Trash" and do something for each accordingly? I'm currently working on developing a plugin with a custom post type of "Dealer Location". (Not relevant to question, just a bit of background)
When a post is in the trash and "delete permanently" is pressed, I need to remove this piece of meta from each user.
When a post/posts are in the trash and "empty trash" is pressed, I need to run through EACH location being deleted and do something.
I have an extremely basic function just to test when it runs right now, as I have all the other nuts & bolts (removing user meta, etc) figured out..:
public function wcmdl_remove_deleted_location_users(){

    die;
}

And the action I'm using is..:
$this->loader->add_action('before_delete_post', $plugin_admin, 'wcmdl_remove_deleted_location_meta');

I've tried using the hook 'delete_post' too and in both cases the function fires when expected. However, it fires on BOTH "delete permanently" AND "empty trash".
Is there any sort of hook or if statement I can use to differentiate between mass-deleting and single-deleting in this instance? If not, would it be viable to pass some value via ajax/js depending on which button is pressed, and use it to determine the action taken in a function via an if/else statement?

A: So as leymannx pointed out in his comment, the "delete_post" hook actually handles both scenarios I was looking for, as it seems to know to run a "for each post deleted, do x" when "Empty Trash" is clicked and will also "do x" when "Delete Post Permanently" is clicked!
My final code ended up looking something like..:
    public function wcmdl_remove_deleted_location_users(){

      $currentpost    = get_the_ID();
      $parentid       = wp_get_post_parent_id( $currentpost );

      if( get_post_type() == 'dealer_location' ) {
        //do stuff involving $currentpost and $parentid here...
      }
    }

Keeping in mind that this is being used within a standard plugin boilerplate format and NOT directly in the functions.php file of a child theme, this hook was placed in the "includes>class-[plugin name].php" file..:
        $this->loader->add_action('delete_post', $plugin_admin, 'wcmdl_remove_deleted_location_users');

If you were to be trying to do the same via your functions.php, the structure for this would instead be:
add_action('delete_post', 'wcmdl_remove_deleted_location_users');


text:
Q: How to control shine bugs Early game shine bugs are very useful and can often be sufficient to support enough plants to feed your dupes. However controlling the shine bugs has proven impossible for me.
If I'm lucky enough to lock them in with doors in the same room as the plants in time, they usually stay in. However I haven't been able to catch them in a room with plants if they start outside. I usually end up using lights to grow my plants.
Attacking the shine bugs just destroys them, it cannot be used to chase them in a particular direction.
Is there a way to 'push' them in a room with plants?

A: There are several options to do this.

*

*Building a room around the shinebugs (as you already mentioned)
ideally there are already some plants (Bristle Berries in that room)

*Same as before but contents of room dont matter. Add a critter drop-off to that room and change it to auto-wrangling and 0 critters. Add another critter drop-off to a different room, where you want the critters to go. As soon as you have a rancher, they will wrangle and move all the critters to the other drop-off. (Argueably this is some kind of weak exploit)

*Build a critter lure (quite mid-tech, requires plastic) and lure the shine bugs with some phosphorite to the lure. This seems to be the (developer) intended way to move flying critters. However it is rather slow, short-ranged and requires advanced resources (plastic). Once the critters are around the lure, it is quite stable though.

*Just wait for the critters to lay eggs and move those eggs to the room you want them to go and hatch them there.

A: Mealwood doesn't need light for growth, so early game just feed your dupes with mealwood, controlling the shine bugs won't matter.


text:
Q: Override configuration properties in micronaut I have a micronaut application in which I want to override the default configuration properties based on a profile I pass through an environment variable.
Tha application has a default application.yml
I am currently passing:
MICRONAUT_CONFIG_FILES=classpath:application.yml,/path/to/application-prod.yml
MICRONAUT_ENVIRONMENTS=prod

However just application-prod.yml is taken into account (unlike for Spring Boot where it updates the defaults).
What is the best way to achieve the update? The only solution so far is to replicate all the settings in application-prod.yml but it seems pretty anti-DRY.


text:
Q: Cassandra data model approach Forgive me for asking something that is probably explained elsewhere, but I am having trouble designing a data model in Cassandra.
I am storing transactions. These transactions each have a source (user), a timestamp, and some associated keywords. I need to be able to find transactions given the source and a date range and (optional) keywords. Cassandra is attractive because I need to store billions of transactions.
I have been unable to find a resource that explains how to do this type of thing. My initial thoughts involve having a few CFs - a transaction CF, a keyword_transaction CF, a source_transaction CF, and possible a day_transaction CF (or something similar). This would make it very straight forward to find transactions based on any one of the above items, but it doesn't seem like it will let me search on all of the above items.
Any thoughts?

A: Start by thinking your query and then to your data model. Read here and here as this help when you plan for your data model.
cf : transactions
rowkey : source/uuid (suggestion)
  cn : source
  cv : UTF8
  cn : keyword
  cv : UTF8
  cn : date
  cv : DateType
  cn : time
  cv : DateType

cf : keywords
rowkey : keyword
   cn : source
   cv : UTF8

where you will have a standard column family called transactions and a few column name (cn) and its corresponding column value (cv). Each of these transaction are identify by the rowkey. Another standard column family is the keywords where the rowkey would be the keyword.
You can search by source, timestamp or keyword but you do need to index them for the query to work. For example with the above suggestion data structure, you can do these:

*

*get all transaction where source is equal to ''

   get transactions where source = ''

*get all transaction where source is equal to '' and your date > ''

   get transactions where source = '' and date > '';

*get all transaction for date x

   get transactions where date = '';

*get all source name based on keyword

   get keywords['keyword'];


text:
Q: CDAP spark phoenix application connection issue We have a cdap application to connection to phoenix table from spark using phoenix driver. I have the phoenix version 4.7 in our environment. As per the standard spark2 phoenix connectivity, it requires only the phoenix-spark2 as a dependency and all other dependencies will be picked up from the classpath and hbase-site.xml properties.
Now what are the dependencies required by cdap spark phoenix application and how can i use hbase-site.xml with the cadp application to make the successful connection.

A: This is an answer for Spark-version and not CDAP, if someone lands here could use this maybe.
I currently use Phoenix version 4.7 and spark version 2.3 in production,
I have the following dependencies related to Phoenix in my pom.xml
<phoenix-version>4.7</phoenix-version>

<dependency>
        <groupId>org.apache.phoenix</groupId>
        <artifactId>phoenix-spark2</artifactId>
        <version>4.7.0.2.6.5.3007-3</version>
        <exclusions>
        <exclusion>
            <groupId>sqlline</groupId>
            <artifactId>sqlline</artifactId>
        </exclusion>
        </exclusions>
</dependency>

<dependency>
        <groupId>org.apache.phoenix</groupId>
        <artifactId>phoenix-client</artifactId>
        <version>4.14.1-HBase-1.1</version>
</dependency>

Also, say for example I want to retrieve a table from Phoenix into Spark Dataframe I would use the following Spark code:
val sqlContext = spark.sqlContext
val table = sqlContext.load("org.apache.phoenix.spark",
  Map("table" -> s"NAMESPACE.TABLE_NAME",
    "zkUrl" -> zookeeperUrl))

Let me know if this doesn't work out


text:
Q: can not append new data to a pd dataframe im trying to save some data in a dataframe, the first row of the dataframe should be ('Tom',.99, 'tom2'), supose i need to add ('mart',.3, 'mart2') row to the dataframe , i've tried to use append but is adding nothing this is my code
    import pandas as pd
    trackeds = {'Name':['Tom'], 'proba':[.99],'name2':['tom2']}
    df_trackeds = pd.DataFrame(trackeds)
    df_trackeds.append(pd.DataFrame({'name':['mart'],'proba': [.3],'name2':['mart2']}))
    print(df_trackeds)

the output is
Name  proba name2
0  Tom   0.99  tom2

i also tried to use
df_trackeds.append({'name':['mart'],'proba': [.3],'name2':['mart2']},ignore_index=True)

and
df_trackeds.append(pd.DataFrame({'name':['mart'],'proba': [.3],'name2':['mart2']}))

but nothing, i hope you can help me, thanks in advance

A: Pandas function DataFrame.append not working inplace like pure python append, so is necessary assign back:
df = pd.DataFrame({'Name':['mart'],'proba': [.3],'name2':['mart2']})
df_trackeds = df_trackeds.append(df, ignore_index=True)
print(df_trackeds)
   Name  proba  name2
0   Tom   0.99   tom2
1  mart   0.30  mart2


text:
Q: Appending a string before an HTML Element I am able to create an input field in a Leaflet popup that edits a GeoJSON property by following the solution posted here:
Edit feature attributes in leaflet
I would like to add a constant string in the popup, so that the popup reads something like, 'EDIT YOUR DATA HERE: [input with editable data]'
When I try to do this the input box fails and returns the string '[object HTMLInputElement]' instead.
How to avoid this?
var input = L.DomUtil.create('input', 'my-input');

input.value = feature.properties.datatoedit;
L.DomEvent.addListener(input, 'change', function() {
  feature.properties.datatoedit = input.value;
});

var popupcontent = "Edit Data Here:
" + input;

layer.bindPopup(popupcontent);

A: Welcome to SO!
You have to realize that "Edit Data Here:
" + input is trying to concatenate a string with an HTML Element.
When doing so, the JS engine will try to cast input into a string, which renders your '[object HTMLInputElement]' string.
Instead, you should convert your "Edit Data Here:
" part as an HTML Element (could be a fragment as well), so that you can insert it alongside your input and provide them as HTML nodes for your popup content.
// Create an HTML Element container for both your string and input.
var popupContent = document.createElement('div');

// Fill it first with your raw HTML code.
// It will automatically be parsed and converted as HTML nodes.
popupContent.innerHTML = "Edit Data Here:
";

// Now you can append your `input` which is already an HTML Element.
popupContent.appendChild(input);

layer.bindPopup(popupContent);

Demo: http://plnkr.co/edit/W11Z95Y9dQZThBu2dKQz?p=preview


text:
Q: How can I make searchbar float or stick on screen even while scrolling?
I want both the app bar and the search textbox to stick on screen even while I scroll down

A: By using bottom property of appbar
bottom: PreferredSize(
          preferredSize: Size.fromHeight(70),
          child: Container(
            //width: MediaQuery.of(context).size.width*0.90,
            height: 70,
            width: MediaQuery.of(context).size.width,
            padding: EdgeInsets.symmetric(vertical: 14,horizontal: 20),
            color: Colors.white,
              child: TextFormField(
                 decoration: InputDecoration(
                 prefixIcon: Icon(Icons.search_rounded,color: Colors.grey,size: 40,),
                   border: InputBorder.none,
                 fillColor: Colors.grey.shade300,
                   enabledBorder: OutlineInputBorder(borderSide: BorderSide(
                     color: Colors.grey.shade500,
                   ),borderRadius: BorderRadius.circular(10),),
                   filled: true,
                     focusedBorder: OutlineInputBorder(
                       borderRadius: BorderRadius.circular(10),
                           borderSide: BorderSide(
                         color: Colors.grey.shade300
                     )
                 ),hoverColor: Colors.black,

          ),
        ),
      ),'


text:
Q: Tronweb authentication I want to build a webapp that uses the wallet address as  account, but yet I want to store the user in my db to allow specifying a nickname.
The problem I'm dealing with is that I want to call different apis, where the user needs to be authenticated / authorized in order to gain access .
Since the authentication happens 100% client side in my case (through the tronlink extension and TronWeb), I don't see another way as to add supplementary authentication for my webapp specifically.
If the user logs in to my app with a different password (not using the private key of the wallet), it seems like bad user experience as the user needs to authenticate twice (through Tronweb AND my webapp with a password).
How do you solve this problem?

A: It seems that the way to handle this is to foresee a separate login flow for the web app after all.
Even when the user already has logged in into Tronlink, it needs to obtain a token to authenticate rest calls.
The way it would appear to work is by generating a random nonce and storing this nonce along with the public key in the User table.
The login flow then consists of signing the  nonce in the front-end, and verifying the signature in the backend after which the token will be generated and returned.


text:
Q: Prove $|a − x| < |a − b|$ Prove that if $a, b, c$ are distinct points of $\mathbb R^d$
such that $∠abc < π/2$, then there is a $x$ on the open segment $(b, c)$ with $|a − x| < |a − b|$.
I tried to take these points as three vertices of an acute-angled triangle such that $∠abc < \pi/2$, and tried to take the property of sum of two sides is greater than the third side i.e. $ab +bc > ac$ then I draw a line from the point $a$ which intersect $bc$ at $x$. Then again I took the sum of two sides property such that $ab + ax > bx$ and after trying all the possibilities I am not unable to prove the above.
Can someone please help me?
Thanks in advance.

A: Consider the triangle $abx$.  You are asking that $a$ is closer to $x$ than it is to $b$, or in other words that the line segment $ax$ is shorter than the line segment $ab$.  This would be true if and only if the measure of $\angle x$ is greater than the measure of $\angle b$.
There is certainly a point $x$ on the line segment $bc$ that satisfies that.  As noted in comments, the projection would work.  Alternatively, you could just choose an $x$ so close to $b$ that $m\angle a$ is insignificant, which would make $\angle x$ the largest angle in the triangle (since we are given that $\angle b$ is acute).


text:
Q: Equallogic two subnet's iscsi conection I buy one Dell Equallogic PS 6010, and don't buy fiber switch.
There are 3 servers, a domain controler with other financial software and yet another with sql server and IIS.
The DC and SQL server is connected whits equallogic by fibra channel, and the equallogic dont have order fiber channel.
My real problem is to connect the server via iscsi that this financial network 192.168.1.x LAN with fiber network 192.168.100.x.
DC runs Windows server 2003
Financial runs windows server 2008

Sorry any erros types
Ty for any helps

A: You really need a switch (ideally two, for redundancy) between your storage array and your hosts.  Otherwise you're limited to the number of ports on your array.


text:
Q: How to insert name of file and modified time using batch/shell script and sql loader I have a requirement to insert bulk data into an Oracle database from a CSV file. Now table columns specs match those of the CSV file's header with the exception of three additional fields in database:

*

*A Primary Key field (for which a simple SEQUENCE.NEXTVAL is called)

*A field for the name of the CSV file

*A field for the last modified date+time of the file

The following stack question address an extra column issue, but the solution is pretty easy because it used Oracle sysdate which is internally available. I need to pass a parameter from either batch script/shell script.
Insert actual date time in a row with SQL*loader
Can PARFILE help here somehow?
My other alternative would be to do the whole task in two steps by writing a small java code:

*

*Use SQL Loader for bulk upload leaving out data for the filename and
modified time

*And then run a separate update statement to populate the newly
created rows

But I'm looking for something which will get the job done in one shot. Any advice??

A: I'm affraid it's not possible with sqlldr alone.
There is no tools for this in sqlldr.
You'd need some sort of script or a program to dynamically create a .ctl file for each load.
Here is a bash script to help you get started:
#!/bin/bash -xv
readonly MY_FILENAME=$1
readonly DB_BUF_TABLE=$2
readonly SQLLDR_CTL="LOAD DATA
CHARACTERSET UTF8
APPEND INTO TABLE $DB_BUF_TABLE
FIELDS TERMINATED BY ';'(
  filename \"$MY_FILE_NAME\",
  col_foo,
  col_bar
)"

echo "$SQLLDR_CTL" > "loader.ctl"
sqlldr control=loader.ctl parfile=loader.par data="$MY_FILENAME"
sqlldrReturnValue=$?

You'd needsome locking with this.. or path separation for concurrent loads to be sure sqlldr starts with proper ctl file


text:
Q: Cambiar evento hover a click y viceversa según la resolución de pantalla con jQuery Sucede que estoy haciendo un menú el cual tiene dos subniveles, donde en pantallas mayores a 800px el evento que aplico para mostrarlo es hover y si la pantalla es menor a 800px el evento será click.
Hice un código que funciona parcialmente es decir si al cargar el menú el viewport es mayor a 800px se aplica el evento hover pero si luego se redimensiona el viewport a menos de 800px el evento ya no cambia hasta que se recargue la página, lo mismo sucede si hago el proceso inverso.
Para solucionar esto estuve probando con el método resize() para desencadenar el evento de acuerdo al tamaño del viewport pero sucede que este no se ejecuta hasta que no cambie el tamaño de pantalla del navegador.
Ahora cuando uso resize y cambio el viewport a más de 800px se aplica el evento hover tanto para escritorio como para móvil y al redimensionar supuestamente debería cambiar al evento click pero no lo hace sino por el contrario los submenú se descontrolan, creo que el problema se encuentra en los if ya que realiza una comparación por cada px que cambia el viewport estoy investigando pero no logro dar con la solución.
El código funciona pero solo recargando la página cada vez, si se descomenta las líneas de ambos extremos se ejecutará el método resize pero se altera el funcionamiento de los submenu.
Asimismo dejo el enlace del menú que hice para que puedan probar a detalle lo que menciono líneas arriba. Espero alguien pueda iluminarme aquí el enlace del código.

A: Una forma mas simple de resolver este problema es tener 2 navbar, uno lo muestras en dispositivos móviles y otro en escritorio, y así en lugar de usar código jquery puedes mostrar y ocultar elementos solo con css con:
@media screen and (max-width: 800px)

para resoluciones pequeñas menores a 800px y
@media screen and (min-width: 800px)

para resoluciones mayores a 800px.
Estos navbar los puedes diferenciar con un id, y también habrá que diferenciar las clases de los elementos que contienen (para esto vasta con agregar un "2") y habrá que hacer los respectivos ajustes en el css, pero luego el código jquery queda mas simple.
Puedes ver y comprobar el resultado del código funcionando:

$(document).ready(function (){

  /*HABILITAMOS EL TOGGLE DEL MENÚ*/
  $('.toggle').click(function () {
      $('#nav1').slideToggle();
  });
  /*ESTE ES EL EVENTO CLICK QUE QUIERO APLICAR EN MÓVIL*/
    $('.sub').click(function () {
        $('.submenu').slideDown();
        $(this).mouseleave(function () {
            $('.submenu').slideUp();
        });
    });
    $('.sub-sub').click(function () {
        $('.sub-submenu').slideToggle();
        $(this).mouseleave(function () {
            $('.sub-submenu').slideUp();
        });
    });
/*ESTE EVENTO HOVER LO QUIERO APLICAR SOLO PARA ESCRITORIO PORQUE
    EN MÓVIL NO SE PUEDE SELECCIONAR EL PROYECTO 3 */
    /*SEGUNDO NIVEL*/
    $('.sub2').mouseenter(function () {
        $('.submenu2').slideDown();
    });
    $('.sub2').mouseleave(function () {
        $('.submenu2').slideUp();
    });
    /*TERCER NIVEL*/
    $('.sub-sub2').mouseenter(function () {
        $('.sub-submenu2').slideDown();
    });
    $('.sub-sub2').mouseleave(function () {
        $('.sub-submenu2').slideUp();
    });
})
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
.logo {
    display: none;
    justify-content: space-between;
    padding: 1em;
    background: rgb(65, 138, 243);
}
.empresa {
    font-size: 1.5em;
    font-weight: bold;
}
.toggle {
    width: 25px;
    cursor: pointer;
}
ul {
    list-style: none;
}
.menu {
    background: rgb(62, 208, 44);
    display: flex;
    line-height: 2;
}
li {
    flex: auto;
    text-align: center;
}
.sub, .sub-sub,.sub2, .sub-sub2 {
    position: relative;
}
.submenu, .submenu2 {
    display: none;
    position: absolute;
    background: rgb(212, 52, 186);
    width: 100%;
}
a {
    text-decoration: none;
    color: rgb(0, 0, 0);
    font-weight: bold;
    font-size: 1.3em;
    display: block;
}
a:hover {
    background: rgb(243, 176, 65);
}
/*SUB-SUBMENU NIVEL 3*/
.sub-submenu, .sub-submenu2 {
    display: none;
    position: absolute;
    left: 100%;
    top: 0;
    background: rgb(44, 208, 186);
    width: 80%;
}
@media screen and (max-width: 800px) {
    #nav1 {
        display: none;
    }
    #nav2 {
         display: none;
    }
    .logo {
        display: flex;
    }
    ul {
        flex-direction: column;
    }
    .menu > li, .menu > li:hover {
        border-bottom: 1px solid red;
    }
    .submenu {
        width: 100%;
        position: static;
    }
    .submenu li:first-child {
        border-bottom: 1px solid red;
    }
    .submenu li:nth-child(2) {
        border-bottom: 1px solid red;
    }
    .sub-submenu {
        width: 100%;
        position: static;
    }
}
@media screen and (min-width: 800px) {
    #nav1{
         display: none;
         visibility: hidden;
    }
    #nav2{
         display: block;
    }
    .logo {
        display: none;
    }
}

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>

Diego Gallo

Inicio

Quienes Somos

                        Proyectos

Proyecto 1

                                Proyecto 2

HTML5

CSS3

Javascript

Proyecto 3

Blog

Contacto

Inicio

Quienes Somos

                        Proyectos

Proyecto 1

                                Proyecto 2

HTML5

CSS3

Javascript

Proyecto 3

Blog

Contacto

Espero que resuelva tu problema, saludos.


text:
Q: How can I avoid explicitly setting each variable to False? I often run into the case that I have to set a variable to False. My last case is that one here:
@cached_property
def dynamic_pricing(self):
    self.dynamic_pricing_active = False
    test = self.request.event.tickets.filter(dynamic_pricing__activated=True)
    for ticket in test:
        if ticket.is_available():
            self.dynamic_pricing_active = True
            break

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['dynamic_pricing_active'] = self.dynamic_pricing_active
    return context

Is there a way to avoid setting self.dynamic_pricing_active = False?
I have other cases where I had to define up to four variables with False due to the same reason as here.

A: You can use any which will shortcut as well once it encounters a true value:
self.dynamic_pricing_active = any(ticket.is_available() for ticket in test)


text:
Q: Netty Pipeline object parsing Currently I have a single handler at the end of my netty pipeline that does almost all the request logic. (Parsing a object from json using jackson, authentication, rate limiting, etc. Would it be a better use of the pipeline structure to put these at stages along the pipeline after the executer?

A: It's matter of re-usability etc. Often you have a handler for decoding, one for encoding and one for the business logic. This allows for better re-usability and also for easier testing.


text:
Q: jQuery POST To Delete File On Button Click I wonder whether someone can help me please.
I've put together this page which allows users to view a gallery of their uploaded images.
I'm now working on the deletion functionality, so that users can delete any image. From some really useful guidance from members of this site here, I've been looking at the jQuery POST method, unlinking the images from the server where they're stored.
From their guidance and subsequent research I've been doing, I think I can use the relative path  i.e. $path.
I've come up with the following which I've tried to add to my script: