text:
Q: Can I have dependent pick lists in design attributes I'm working on a case where I want to show picklists in design attributes. Here, in my case, I want to show them dynamically. i.e. let us take that there 2 picklists in design attributes, first to select parent and the second to select child element. When I select Account in first picklist, the second picklist should show only the object names having lookup to Account. I was trying out code, but my code is limited only to the current picklist, is there a way that I can have dependent picklists?
Here is my code.
global class MyCustomPickList extends VisualEditor.DynamicPickList {
  global override VisualEditor.DataRow getDefaultValue() {
    VisualEditor.DataRow defaultValue = new VisualEditor.DataRow('account', ' Account');
    return defaultValue;
  }

  global override VisualEditor.DynamicPickListRows getValues() {
    VisualEditor.DataRow value1 = new VisualEditor.DataRow('account', 'Account');
    VisualEditor.DataRow value2 = new VisualEditor.DataRow('contact', 'Contact');
    VisualEditor.DynamicPickListRows myValues = new VisualEditor.DynamicPickListRows();
    myValues.addRow(value1);
    myValues.addRow(value2);
    return myValues;
  }
}

Please let me know how I achieve this dynamic dependent design attributes.
Thanks

A: Unfortunately, this is not possible. You'll want to vote on this Idea.


text:
Q: Java Named Query I'm trying to create a Java named query which does the following postgres query:
select * from call_attempt where result is NULL and id like '0000000101%';

The 0000000101 is set to id in my code, so this is what I want to do, but it's malformed:  (I'm not sure how to set the id field while using the % and it has to be inside ' ')
@NamedQuery(name = AttemptEntity.JQL.NOTENDED,
                       query = "SELECT ae FROM AttemptEntity ae WHERE ae.result IS NULL,"
                             + " ae.correlationId LIKE '=:id%'")

A: First, you forgot the and, and replaced it by a comma.
Second, the % must be passed as part of the argument:
SELECT ae FROM AttemptEntity ae WHERE ae.result IS NULL
and ae.correlationId LIKE :id

And then, when executing the query:
String id = "0000000101%";
query.setParameter("id", id);

A: You can't have the % in the NamedQuery, but you can have it in the value you assign the parameter.
query.setParamter("id", 0000000101+ "%");

You also need to add AND and remove the comma after NULL.
Reference: Named Query with like in where clause

redpajama_set_name: RedPajamaStackExchange


text:
Q: Angular, named outlet need to add slash to path I have layout named admin-panel
<app-top-panel></app-top-panel>
<app-side-bar-n></app-side-bar-n>
<div id="content" class="content">
  <router-outlet></router-outlet>
  <router-outlet name="moneyComingModal"></router-outlet>
</div>

when I call the named outlet from any component for example overview.component like this:
    <a [routerLink]="[ { outlets: { moneyComingModal:addMoneyComingModal } }] ">
      test
    </a>

its work's good, but when I call this outlet from the sidebar component the link loose slash '/'
link is: overview(moneyComingModal:addMoneyComingModal)

how I can add the slash after overview path?
code from sidebar:
 <a [routerLink]="['', { outlets: { moneyComingModal:'addMoneyComingModal' } }] ">
   test
 </a>

output: ---> overview(moneyComingModal:addMoneyComingModal)

What I need:
overview/(moneyComingModal:addMoneyComingModal)


text:
Q: non-deterministic content model error DTD Given:
<!ELEMENT diagnostic-tracks (hookup*, (%step;)*, ((diagnostic-track-automated, diagnostic-track-manual) | diagnostic-track-automated | diagnostic-track-manual), evaluate*, disconnect*)>

and
<!ELEMENT diagnostic-track-automated (((%step;) | diagnostic_group)*, diagnostic_group, evaluate*)>

<!ENTITY % step "((%figtab;) | step1 | step1-alt)">
<!ENTITY % figtab "figure | figure-alt | table | table-alt | lubetab">

I am getting non-deterministic content model errors that diagnostic-track-automated and diagnostic_group could simultaneously match two or more tokens.
I changed to:
<!ELEMENT diagnostic-tracks (hookup*, (%step;)*, diagnostic-track-automated?, diagnostic-track-manual?, evaluate*, disconnect*)>

and
<!ELEMENT diagnostic-track-automated (((%step;) | diagnostic_group+)*, evaluate*)>

which eliminated the error messages, but I don't think my changes, especially for diagnostic-track-automated, are correct.
I appreciate any suggestions for improvement.

A: I think what you came up with for diagnostic-tracks appears to be what you were trying to accomplish with the original non-deterministic model:

zero or more hookup elements followed by  zero or more elements
  from %step; followed by  zero or one
  diagnostic-track-automated element followed by  zero or one
  diagnostic-track-manual element followed by  zero or more
  disconnect elements

However I think the fix for diagnostic-track-automated is not what you originally intended.
What you propose now is:

zero or more elements from %step; or diagnostic_group followed
  by  zero or more evaluate elements

What I think you meant was:

zero or more elements from %step; followed by  one or more
  diagnostic_group elements followed by  zero or more evaluate
  elements

Which would be:
<!ELEMENT diagnostic-track-automated ((%step;)*, diagnostic_group+, evaluate*)>

Here's a full/testable example...
DTD (so.dtd)
<!ENTITY % figtab "figure | figure-alt | table | table-alt | lubetab">
<!ENTITY % step "%figtab; | step1 | step1-alt">

<!ELEMENT diagnostic-tracks (hookup*, (%step;)*, diagnostic-track-automated?, diagnostic-track-manual?, evaluate*, disconnect*)>

<!ELEMENT diagnostic-track-automated ((%step;)*, diagnostic_group+, evaluate*)>

<!ELEMENT table EMPTY>
<!ELEMENT table-alt EMPTY>
<!ELEMENT diagnostic_group EMPTY>
<!ELEMENT step1-alt EMPTY>
<!ELEMENT evaluate EMPTY>
<!ELEMENT figure EMPTY>
<!ELEMENT figure-alt EMPTY>
<!ELEMENT lubetab EMPTY>
<!ELEMENT step1 EMPTY>
<!ELEMENT diagnostic-track-manual EMPTY>
<!ELEMENT disconnect EMPTY>
<!ELEMENT hookup EMPTY>

XML
<!DOCTYPE diagnostic-tracks SYSTEM "so.dtd">
<diagnostic-tracks>
    <diagnostic-track-automated>
        <diagnostic_group/>
    </diagnostic-track-automated>
    <diagnostic-track-manual/>
</diagnostic-tracks>


text:
Q: How To Auto-Tag A Docker Image with Git Commit Hash through a Jenkinsfile Pipeline So I have a Jenkins instance that I need to automatically tag a Docker Image with using a Jenkinsfile Pipeline that automatically tags the image with the commit hash and then pushes it to the Docker Repository. Jenkins is configured correctly, but my pipeline is still failing. At first, I tried using the following command, which returns the current commit hash of my repository.
git rev-parse --short=10 HEAD

Then I noticed this was returning more than one line, so I started using this:
git rev-parse --short=10 HEAD | tail -n +2

Which returns a commit hash similar to this:
338fcaa318b17c40dacf81dcf7a5826e3e3f0160

My goal is to tag my docker images with this hash using a Jenkinsfile:
pipeline {
    agent any
    environment {
        tag = sh(returnStdout: true, script: "git rev-parse -short=10 HEAD | tail -n +2")
    }

    stages {
        stage('Build core lodestone image') {
            steps {
                // TODO: proper tagging
                sh "docker build -f Dockerfile.lodestone -t mirantiseng/lodestone:${var.tag} ."
                withCredentials([usernamePassword(credentialsId: 'common-dockerhub-up', usernameVariable: 'HUB_USER', passwordVariable: 'HUB_PASS')]) {
                    sh "docker login -u ${HUB_USER} -p ${HUB_PASS} && docker push mirantiseng/lodestone:${var.tag}"
                }
            }
        }
        stage('Build core lodestone-comment image') {
            steps {
                // TODO: proper tagging
                sh "docker build -f Dockerfile -t mirantiseng/lodestone-comment:${var.tag} ."
                withCredentials([usernamePassword(credentialsId: 'common-dockerhub-up', usernameVariable: 'HUB_USER', passwordVariable: 'HUB_PASS')]) {
                    sh "docker login -u ${HUB_USER} -p ${HUB_PASS} && docker push mirantiseng/lodestone-comment:${var.tag}"
                }
            }
        }
        stage('Build core lodestone-mover image') {
            steps {
                // TODO: proper tagging
                sh "docker build -f Dockerfile.mover -t mirantiseng/lodestone-mover:${var.tag} ."
                withCredentials([usernamePassword(credentialsId: 'common-dockerhub-up', usernameVariable: 'HUB_USER', passwordVariable: 'HUB_PASS')]) {
                    sh "docker login -u ${HUB_USER} -p ${HUB_PASS} && docker push mirantiseng/lodestone-mover:${var.tag}"
                }
            }
        }
    }
}

The build works if I take out the :${var.tag} and the following block, but it just pushes latest. This leaves the working file looking like this:
pipeline {
    agent any

    stages {
        stage('Build core lodestone image') {
            steps {
                // TODO: proper tagging
                sh "docker build -f Dockerfile.lodestone -t mirantiseng/lodestone ."
                withCredentials([usernamePassword(credentialsId: 'common-dockerhub-up', usernameVariable: 'HUB_USER', passwordVariable: 'HUB_PASS')]) {
                    sh "docker login -u ${HUB_USER} -p ${HUB_PASS} && docker push mirantiseng/lodestone"
                }
            }
        }
        stage('Build core lodestone-comment image') {
            steps {
                // TODO: proper tagging
                sh "docker build -f Dockerfile -t mirantiseng/lodestone-comment ."
                withCredentials([usernamePassword(credentialsId: 'common-dockerhub-up', usernameVariable: 'HUB_USER', passwordVariable: 'HUB_PASS')]) {
                    sh "docker login -u ${HUB_USER} -p ${HUB_PASS} && docker push mirantiseng/lodestone-comment"
                }
            }
        }
        stage('Build core lodestone-mover image') {
            steps {
                // TODO: proper tagging
                sh "docker build -f Dockerfile.mover -t mirantiseng/lodestone-mover ."
                withCredentials([usernamePassword(credentialsId: 'common-dockerhub-up', usernameVariable: 'HUB_USER', passwordVariable: 'HUB_PASS')]) {
                    sh "docker login -u ${HUB_USER} -p ${HUB_PASS} && docker push mirantiseng/lodestone-mover"
                }
            }
        }
    }
}

But I need the docker images to be tagged. I read up on the Jenkinsfile and it said I could make an environmental variable using environment {<something>} to set global variables. I have a variable called tag that I would like to implement that tags the docker images with the commit hash. How can I accomplish this?

A: You could have used is just $GIT_COMMIT like this
sh "docker build -f Dockerfile.mover -t mirantiseng/lodestone-mover:${GIT_COMMIT} ."

A: So all I had to do was change the way tag was defined:
pipeline {
    agent any
    environment {
        tag = sh(returnStdout: true, script: "git rev-parse --short=10 HEAD").trim()
    }

    stages {
        stage('Build core lodestone image') {
            steps {
                // TODO: proper tagging
                sh "docker build -f Dockerfile.lodestone -t mirantiseng/lodestone:${tag} ."
                withCredentials([usernamePassword(credentialsId: 'common-dockerhub-up', usernameVariable: 'HUB_USER', passwordVariable: 'HUB_PASS')]) {
                    sh "docker login -u ${HUB_USER} -p ${HUB_PASS} && docker push mirantiseng/lodestone:${tag}"
                }
            }
        }
        stage('Build core lodestone-comment image') {
            steps {
                // TODO: proper tagging
                sh "docker build -f Dockerfile -t mirantiseng/lodestone-comment:${tag} ."
                withCredentials([usernamePassword(credentialsId: 'common-dockerhub-up', usernameVariable: 'HUB_USER', passwordVariable: 'HUB_PASS')]) {
                    sh "docker login -u ${HUB_USER} -p ${HUB_PASS} && docker push mirantiseng/lodestone-comment:${tag}"
                }
            }
        }
        stage('Build core lodestone-mover image') {
            steps {
                // TODO: proper tagging
                sh "docker build -f Dockerfile.mover -t mirantiseng/lodestone-mover:${tag} ."
                withCredentials([usernamePassword(credentialsId: 'common-dockerhub-up', usernameVariable: 'HUB_USER', passwordVariable: 'HUB_PASS')]) {
                    sh "docker login -u ${HUB_USER} -p ${HUB_PASS} && docker push mirantiseng/lodestone-mover:${tag}"
                }
            }
        }
    }
}

The main change was this
tag = sh(returnStdout: true, script: "git rev-parse --short=10 HEAD").trim()`


text:
Q: how to search a name of text-file c# windows phone I'm a newbie wp dev. I want to create a many text file name like 1.text 2.text 3.text ......1760.text and I want user to type the number in text box then click the button and the result is read that typed number.text. how can I do it ? please help

A: you can try this method:
1. put these txt-files into a path,like:TxtFiles/1.txt,2.txt...
2. when user type the number and click button, execute a method to combine file-path and read the file. and you should check the number first.
StreamResourceInfo resourceInfo = Application.GetResourceStream(new Uri(string.Format("yourFilePath/{0}.txt",userTypedNumber), UriKind.Relative));
using (StreamReader reader =  new StreamReader(resourceInfo.Stream))
{
    yourContentControl.Text = reader.ReadToEnd();
    reader.Close();
}


text:
Q: optimizing redundant call on immutable objects Consider this scala code
val word = str.toLowerCase
val chars = word.distinct.sorted

and then later
//chars.map(c => str.toLowerCase.count(_ == c))
chars.map(c => word.count(_ == c))

I created the val word to avoid creating a new lower case string for map. But, in theory, can the Scala compiler optimize it away? It knows that strings are immutable.

A: If the compiler somehow knew that .toLowerCase always returns the same result and does not have any side effects, it could optimize several calls to .toLowerCase on the same object to just one call. However, it can't know that and in your example it's not even true. For instance, depending on the default locale used, "I".toLowerCase might be "i" or "ı". Since the default locale can change between calls, such an optimization would not be valid.


text:
Q: Cannot fetch object from json response I am new to Angular, but I have been fighting this 5 hours and cannot figure it out: I am not able to fetch object from json request in Angular4 app.
I have following function in my service:
   getById(id: number) {
        return this.http.get('/api/users/' + id, this.jwt()).map((response: Response) => response.json());
    }

In my component I have:
export class EditUserComponent implements OnInit {
  appUser: User;
  id: number;
  private sub: any;

  ngOnInit(): void {
    this.sub = this.route.params.subscribe(params => {
      this.id = +params['id']; ;
    });
      this.userService.getById(this.id).subscribe((appUser: User) => {
      this.appUser = appUser;
    });
  }
   constructor(private auth: AuthenticationService, private userService:
UserService, private route: ActivatedRoute,
    private location: Location) {

  }
}

And I am displaying properties of User class on html view, like {{appUser.firstName}} and so on. Then i get ZoneAwareError:
   TypeError: Cannot read property 'firstName' of undefined
    at Object.eval [as updateRenderer] (ng:///AppModule/EditUserComponent.ngfactory.js:37:34)
    at Object.debugUpdateRenderer [as updateRenderer] (http://localhost:4200/vendor.bundle.js:12856:21)
    at checkAndUpdateView (http://localhost:4200/vendor.bundle.js:12235:14)
    at callViewAction (http://localhost:4200/vendor.bundle.js:12545:17)
    at execComponentViewsAction (http://localhost:4200/vendor.bundle.js:12491:13)
    at checkAndUpdateView (http://localhost:4200/vendor.bundle.js:12236:5)
    at callWithDebugContext (http://localhost:4200/vendor.bundle.js:13218:42)
    at Object.debugCheckAndUpdateView [as checkAndUpdateView] (http://localhost:4200/vendor.bundle.js:12758:12)
    at ViewRef_.detectChanges (http://localhost:4200/vendor.bundle.js:10327:63)
    at RouterOutlet.activateWith (http://localhost:4200/vendor.bundle.js:32148:42)
    at ActivateRoutes.placeComponentIntoOutlet (http://localhost:4200/vendor.bundle.js:31329:16)
    at ActivateRoutes.activateRoutes (http://localhost:4200/vendor.bundle.js:31310:26)
    at http://localhost:4200/vendor.bundle.js:31246:58
    at Array.forEach (native)
    at ActivateRoutes.activateChildRoutes (http://localhost:4200/vendor.bundle.js:31246:29)

A: When your view first displays, the component has not yet retrieved the data. That is why the appUser is undefined. There are several ways to prevent this error:
1) Initialize appUser to something so it is not undefined. This may not make sense for the business rules of your application.
2) Add an *ngIf = "appUser" on one of the top-level HTML elements of your view, such as a <div>. This will prevent displaying the view until the data is retrieved.
3) Add the safe navigation operator on appUser like this: {{appUser?.firstName}} The primary issue with this approach is that you need to add it to every usage of appUser on your page.


text:
Q: How to check if a parameter is passed to a function? I'm trying to figure out how to check if a dataframe is passed or not as a parameter
def mean_encoding_with_reg (df,var,alpha,y,test=False):

    if test!=False:
        test.set_index(var,inplace=True)
        test['cat_'+str(var)] = a.mean_y
        test.reset_index(inplace=True)
        test.drop(var,inplace=True,axis=1)

    return df,test

In case I pass a test param I get the following message:
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

A: Thanks @Spinor8 for your help. Here's how I implemented it:
def mean_encoding_with_reg (df,var,alpha,y,test=False):
if isinstance(test, pd.DataFrame):
    test.set_index(var,inplace=True)
    test['cat_'+str(var)] = a.mean_y
    test.reset_index(inplace=True)
    test.drop(var,inplace=True,axis=1)
    return df,test
return df

A: You will need to use isinstance() to check whether the "test" argument is a dataframe.
if isinstance(test, pandas.DataFrame):


text:
Q: How to use NHibernate to query by unique-key values I'd like to use Example.Create() to query just by the unique values of an instance. To do so I need to find out the value of the unique-key property that had been set inside the mapping file, like this:
  <property name="MyColumn">
    <column name="MyColumn" unique-key="MyUniqueKeyGroup"/>
  </property>

For better understanding - here is the important part of the code:
criteria.Add(Example.Create(myObject).SetPropertySelector(new MyPropertySelector()));

[...]

public class MyPropertySelector: NHibernate.Criterion.Example.IPropertySelector
{
    #region IPropertySelector Member

    public bool Include(object propertyValue, string propertyName, IType type)
    {
         /*  here is where I want to check if the property belongs
          *  to the unique-key group 'MyUniqueKeyGroup' and return true if so
          */
    }

    #endregion
}

What do I need to do, to find out if a property belongs to the unique-key group 'MyUniqueKeyGroup'?

A: You'll need to probe the Nhibernate.Cfg.Configuration object to get this.  You would have constructed this somewhere in order to create your ISessionFactory instance.  Something like this may work:
private NHibernate.Cfg.Configuration _configuration;

[...]

var selector = new MyPropertySelector<MyClass>(_configuration, "MyUniqueKeyGroup");
criteria.Add(Example.Create(myObject)
                    .SetPropertySelector(selector));

[...]

public class MyPropertySelector<T>: NHibernate.Criterion.Example.IPropertySelector
{
    private NHibernate.Cfg.Configuration _onfiguration;
    private IEnumerable<NHibernate.Mapping.Column> _keyColumns;

    public MyPropertySelector(NHibernate.Cfg.Configuration cfg, string keyName)
    {
        _configuration = cfg;
        _keyColumns = _configuration.GetClassMapping(typeof(T))
                                .Table
                                .UniqueKeyIterator
                                .First(key => key.Name == keyName)
                                .ColumnIterator);

    }

    public bool Include(object propertyValue, string propertyName, IType type)
    {
         return _configuration.GetClassMapping(typeof(T))
                          .Properties
                          .First(prop => prop.Name == propertyName)
                          .ColumnIterator
                              .Where(col => !col.IsFormula)
                              .Cast<NHibernate.Mapping.Column>()
                              .Any(col => _keyColumns.Contains(col)))
    }
}

I haven't actually compiled this to check it works, so YMMV.  And it could certainly be made more efficient!  It also doesn't do any trapping of error conditions (e.g. if you give it an incorrect key name, or an unmapped class type then it will crash).
Cheers,
John


text:
Q: position image so left half is visible and right half is behind div I have an image that I want to "peek" from behind a div: the left half of the image peeks from behind a div, and the rest is hidden - like this.
The div has the following css:
#div{
    float: left;
    position: relative;
    margin-left: 5%; }

For the peeker I have tried using:
#peeker {
    position: fixed;
    margin-left: 2.5%;
}

However, this only works when zoom is at 100%. When I zoom out, #peeker is no longer 50% shown.
Is it possible to do this without using javascript?

A: #peeker {
    position: fixed;
    margin-left: 2.5%;
    width: 5%;
}


text:
Q: Having trouble with sql LIKE I have the following query:
SELECT * FROM `alerts` WHERE `title` LIKE `%template%`

This should return at least 3 results with titles that includes the word 'template' but I'm getting the following error: -
1054 - Unknown column '%template%' in 'where clause'
As far as I can tell its syntactically correct and calling the correct column names. What am I missing?

A: Use single quotes for the %template%:
SELECT * FROM `alerts` WHERE `title` LIKE '%template%'


text:
Q: FTP timing out on Heroku Using Apache Commons FTPClient in a Scala application works as expected on my local machine, but always times out when running on Heroku. Relevant code:
val ftp = new FTPClient
ftp.connect(hostname)
val success = ftp.login(username, pw)
if (success) {
  ftp.changeWorkingDirectory(path)
  //a logging statement here WILL print
  val engine = ftp.initiateListParsing(ftp.printWorkingDirectory)
  //a logging statement here will NOT print
  while (engine.hasNext) {
    val files = engine.getNext(5)
    //do stuff with files
  }
}

By adding some loggings I've confirmed the client is successfully connecting, logging in, and changing the directory. But stops when trying to begin retrieving files (either via the above paged access or unpaged with ftp.listFiles) and throws a connection time out exception (after about 15 minutes).
Any reason the above code works fine locally but not on Heroku?

A: Turns out FTP has two modes, active and passive, and Apache-Commons' FTPClient defaults to active. Heroku's firewall presumably doesn't allow active FTP (which is why this was functioning properly locally but not once deployed) - changing to passive mode by adding ftp.enterLocalPassiveMode() resolved the issue.


text:
Q: convert PL/SQL to SQL - Connect By Statement
Possible Duplicate:
Simulation of CONNECT BY PRIOR of ORACLE in SQL SERVER

--I need to convert the below PL/SQL to SQL
SELECT  DataMapId, REPLACE((QtyType, '#'), '#') AS QtyTypes
            FROM    (
                        SELECT  DataMapId, '<QtyType>' + cast(DataTypeId as nvarchar(200)) + '</QtyType>' AS QtyType,
                                ROW_NUMBER() OVER (PARTITION BY DataMapId ORDER BY DataTypeId) AS rn
                        FROM    tblDataMapChannels
                    )
            WHERE   CONNECT_BY_ISLEAF = 1
            CONNECT BY  rn = PRIOR rn + 1
                AND     DataMapId = PRIOR DataMapId
            START WITH  rn = 1


text:
Q: Large 10000x11866 .PNG image still blurry in Android Studio I want to have an image show up in my Android application, but it always comes out blurry. What do I do? My image is 10000x11866 pixels, and I've made it big on purpose so that it wouldn't come out blurry, but it still does.
Here's my approach: right click the 'res' folder -> new image asset -> set icon type to 'action bar and tab icons'
What am I doing wrong?

A: Action bar and tab icons are much smaller than that, so the wizard is scaling down the image. Do not use the Image Asset Wizard for your image.
Instead, create a drawable-nodpi directory under your existing res directory in your module's main source set. Then, copy the image into that drawable-nodpi directory.
Note that you may run out of memory with an image that size, and there is no Android device with a screen resolution anywhere near that. I recommend that you reduce the resolution to something more reasonable, such as 1000x1186.

A: You can just copy the image and paste it in the drawable folder. Make sure the name of the image is in lowercase.
Also, make the dimensions smaller. There is no need for the picture to have such extreme dimensions. Especially if the image is not being zoomed. 1920 x 1080 1000 x 1000 are big enough trust me.
Post your code so we can see what's going on.


text:
Q: How to override the NSPersistentStoreCoordinator in UIManagedDocument I have an application that uses Core Data through UIManagedObjectDocument.  I am trying to add encryption to the underlying SQLite database by using Encrypted Core Data (https://github.com/project-imas/encrypted-core-data).  From the description for ECD, I need to create a new type of NSPersistentSroreCoordinator.  However, I cannot seem to do this with a UIManagedObjectDocument since it creates its own internal NSPersistenStoreCoordinator (which s marked private).
I create the database with this line:
UIManagedDocument* managedDoc = [[UIManagedDocument alloc] initWithFileURL:url];

I tried subclassing UIManagedDocument and creating it this way with no luck:
UIManagedDocument* managedDoc = [[EncryptedManagedDocument alloc] initWithFileURL:url];

And my implementation of the class:
@interface EncryptedManagedDocument()
@property (nonatomic,retain,readonly) NSPersistentStoreCoordinator *encryptedStoreCoordinator;
@end

@implementation EncryptedManagedDocument

@synthesize encryptedStoreCoordinator = _encryptedStoreCoordinator;

-(NSPersistentStoreCoordinator*)encryptedStoreCoordinator
{
    if (_encryptedStoreCoordinator)
        return _encryptedStoreCoordinator;

    _encryptedStoreCoordinator = [EncryptedStore makeStore:[self managedObjectModel]:@"SOME_PASSCODE"];
    return _encryptedStoreCoordinator;
}

-(NSPersistentStoreCoordinator*)persistentStoreCoordinator
{
    return self.encryptedStoreCoordinator;
}
@end

Does anyone know the right way to do this?
Thanks!

A: I'm going to say this is not possible.  UIManagedDocument wraps things up nicely and is a great time saver for the common case, but to enable my scenario I created an EncryptedManagedDocument class that is similar to UIManagedDocument but gave me control to create my own persistent store coordinator.
Thanks, everyone.


text:
Q: sed - command to match a line, and change only a numerical part? I have this as my target file:
#define NUMTHREADS 4
#define ar 1000
#define ac 1000
#define br 1000
#define bc 1000

I want to replace just the numbers in these lines with different numbers using sed (doing this is a bash script). However, I don't want to change these values anywhere else in the file. The script can't know the values directly because they may be different than listed above.
So basically:
Find line with #define ar then replace a general numerical match after it with a given number. Is this possible with sed?

A: Sure, that's pretty much the point of regular expressions:
sed [-i] 's/^#define ar [0-9]\+$/#define ar 12345/' <file>

The -i switch causes sed to operate on the file in-place; leave it off the first time to let it print to stdout and make sure it does what you want.
Of course, from your first description it sounds like you might want to match more than just #define ar. To match all two-letter #defines:
sed [-i] 's/^\(#define [a-z]\{2\}\) [0-9]\+$/\1 12345/`

The \1 is replaced by whatever was matched by the \(...\) group.


text:
Q: incoming IPV6 connections work on pi but not on Ubuntu Summary
Incoming IPV6 connection works on the pi but not on the Ubuntu.
Details
My home network is:
(internet)--|box|---+--------+
                    |        |
                   |pi|   |ubuntu|
                   /|\

*

*Pi serving as WiFi access point and hosting docker

*all connections are wired (RJ45) if that matters.

I have IPv4 access from outside just fine using NAT.
However, I can't access the Ubuntu server using a dedicated IPv6.
connection
accessing http://2001:0db8:0000:0000:ffff:xyz from a browser from ... to ...
All OK save from external to ubuntu.

local host
Pi
Ubuntu
4G

ubuntu
✓
✓
 (1)

Pi
✓
✓
✓

(1) I want to be able to connect to this host from outside.
I tested the connection from a python flask server on both hosts.
Outgoing connections to ipv6.google.com work fine.
I've redacted my IPv6 and local box address
host
lsb_release -a
ubuntu
Distributor ID: Ubuntu
Description:    Ubuntu 20.04.4 LTS
Release:        20.04
Codename:       focal

pi
Distributor ID: Raspbian
Description:    Raspbian GNU/Linux 10 (buster)
Release:        10
Codename:       buster

network interface
edited result of ip -6 address show dev $device
ubuntu
2: enp2s0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    inet6 2001:0db8:0000:0000:ffff:292c:2169:2be/64 scope global noprefixroute
       valid_lft forever preferred_lft forever
    inet6 2001:0db8:0000:0000:ffff:afce:b393:a1a6/64 scope global temporary dynamic
       valid_lft 577013sec preferred_lft 58112sec
    inet6 2001:0db8:0000:0000:ffff:7def:e93b:9721/128 scope global dynamic noprefixroute
       valid_lft 50536sec preferred_lft 50536sec
    inet6 2001:0db8:0000:0000:ffff:37af:30b9:1426/64 scope global temporary deprecated dynamic
       valid_lft 491116sec preferred_lft 0sec
    inet6 2001:0db8:0000:0000:ffff:63ae:6ede:cbcb/64 scope global dynamic mngtmpaddr noprefixroute
       valid_lft 604458sec preferred_lft 604458sec
    inet6 fe80::9b44:f31b:3c0d:9e07/64 scope link noprefixroute
       valid_lft forever preferred_lft forever

pi
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 state UP qlen 1000
    inet6 2001:0db8:0000:0000:ffff:7def:e93b:d67e/128 scope global dynamic noprefixroute
       valid_lft 54268sec preferred_lft 54268sec
    inet6 2001:0db8:0000:0000:ffff:ab8d:724e:d849/64 scope global dynamic mngtmpaddr noprefixroute
       valid_lft 604397sec preferred_lft 604397sec
    inet6 2001:0db8:0000:0000:ffff:c28:95b4:8/128 scope global
       valid_lft forever preferred_lft forever
    inet6 fe80::3448:1bbb:4a95:6158/64 scope link
       valid_lft forever preferred_lft forever

V6 route
edited result of ip -6 route show
ubuntu
::1 dev lo proto kernel metric 256 pref medium
2001:0db8:0000:0000:ffff:292c:2169:2be dev enp2s0 proto kernel metric 256 pref medium
2001:0db8:0000:0000:ffff:7def:e93b:9721 dev enp2s0 proto kernel metric 100 pref medium
2001:0db8::/64 dev enp2s0 proto ra metric 100 pref medium
2001:0db8::/64 dev enp2s0 proto kernel metric 256 pref medium
fe80::/64 dev enp2s0 proto kernel metric 100 pref medium
default via fe80::defa:ult:box:local dev enp2s0 proto ra metric 20100 pref high

Pi
::1 dev lo proto kernel metric 256 pref medium
2001:0db8:0000:0000:ffff:c28:95b4:8 dev eth0 proto kernel metric 256 pref medium
2001:0db8::/64 dev eth0 proto ra metric 202 mtu 1500 pref medium
fe80::/64 dev eth0 proto kernel metric 256 pref medium
fe80::/64 dev wlan0 (and docker ...) proto kernel metric 256 pref medium
default via fe80::defa:ult:box:local dev eth0 proto ra metric 202 mtu 1500 pref medium

sysctl
I compared values from sysctl
 < pi (eth0)
 > ubuntu (enp2s0)

42d41
< net.ipv6.conf.eth0.rpl_seg_enabled = 0
43a43
> net.ipv6.conf.enp2s0.seg6_require_hmac = 0
48c48
< net.ipv6.conf.eth0.use_tempaddr = 0
---
> net.ipv6.conf.enp2s0.use_tempaddr = 2
51c51
< net.ipv6.neigh.eth0.base_reachable_time_ms = 30000000
---
> net.ipv6.neigh.enp2s0.base_reachable_time_ms = 30000
59c59
< net.ipv6.neigh.eth0.retrans_time_ms = 10000
---
> net.ipv6.neigh.enp2s0.retrans_time_ms = 1000
61,62c61,62
< net.ipv6.neigh.eth0.unres_qlen = 91
< net.ipv6.neigh.eth0.unres_qlen_bytes = 180224
---
> net.ipv6.neigh.enp2s0.unres_qlen = 101
> net.ipv6.neigh.enp2s0.unres_qlen_bytes = 212992

All other things tested are equal on both hosts.
Did I miss some obvious thing?


text:
Q: Lambda & DynamoDB: "The parameter cannot be converted to a numeric value" Can anyone figure out why this number string cannot be converted to a number!!
I have the following Lambda function which is taking a set of data being sent from API Gateway and then configuring it to save it to DynamoDB.
// Load the AWS SDK for Node.js.
var AWS = require("aws-sdk");
// Set the AWS Region.
AWS.config.update({ region: "us-east-1" });

// Create DynamoDB service object.
var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" });

exports.handler = async (event) => {
  // response variables
  let body;
  let statusCode = "200";
  const headers = {
    "Content-Type": "application/json",
  };
  // request parameters
  let params = {
    TableName: "users_amazon_profiles",
    Item: {
      "user_id": { "S": "event.user_id" },
      "refresh_token": { "S": "event.refreshToken" },
      "profile_id": { "N": "event.profileArray[0].profileId" },
      "country_code": { "S": "event.profileArray[0].countryCode" },
      "currency_code": { "S": "event.profileArray[0].currencyCode" },
      "account_info": {
        "M": {
          "marketplaceStringId" : { "S": "event.profileArray[0].accountInfo.marketplaceStringId" },
          "id" : { "S": "event.profileArray[0].accountInfo.id" },
          "name" : { "S": "event.profileArray[0].accountInfo.name" },
          "type" : { "S": "event.profileArray[0].accountInfo.type" },
          "validPaymentMethod" : { "BOOL": event.profileArray[0].accountInfo.validPaymentMethod }
        }
      },
      "daily_budget": { "N": "event.profileArray[0].dailyBudget" },
      "timezone": { "S": "event.profileArray[0].timezone" },
    },
  };

//  request
  try {
    console.log("profileId:");
    console.log(event.profileArray[0].profileId);
    body = await ddb.putItem(params).promise();
  } catch (err) {
    statusCode = "400";
    body = err.message;

  }

//  dynamic response
  return {
    statusCode,
    body,
    headers,
  };
};

And here is the JSON test object being used for testing:
{
  "user_id": "g490754-49b9-9079-c63aba5cccf6",
  "refreshToken": "Atzr|IwEBIMvPPWsTFHLgvbEhgUn30P57Kake_nfIgVa-6GJeIe9vsW38GdoDcpzCXIlqd6-82YdC8JISNxuQJQ5QREGmSX0YRu6qJ4zteznkqoaygCPk1ZqHE2jPhcbDuDZiGRNOWpis0pPpKaS9ylJsp2Vquwa5lM6Olu_qhRanp8iewCLmK-k4W8FkjA0aiiCqJPyfb7dsloXO-TGDPK8WXSoLREnzhucaO5Xn-TnwicZzKrq0mYBHyhzm1XNvEGmSiDm1cxkgFcQr0TvkVhyOoTeLuKz3Cw-1iAQg6rbaXiEvgo18ganZYO71vpv4jy5S91h5NVZwCgtG7tJ73A5DzOBdRXjjhke5xJ7HHEZQncQUPjE_R0gZBtsXpKfJVaaPjY925m-GCMbdhe9aFR0gKYlaDz-q-Nbo_I-vUA",
  "profileArray": [
    {
      "accountInfo": {
        "marketplaceStringId": "OKE9KIKX0DER",
        "id": "OI9FU2GLDTTWKS",
        "name": "Test Seller",
        "type": "seller",
        "validPaymentMethod": true
      },
      "countryCode": "US",
      "currencyCode": "USD",
      "dailyBudget": "999999999",
      "profileId": "2591184040605621",
      "timezone": "America/Los_Angeles"
    },
    {
      "accountInfo": {
        "marketplaceStringId": "ATVERKIKX0DER",
        "id": "A3UJTRELDTTWKS",
        "name": "ACME",
        "type": "vendor",
        "validPaymentMethod": false
      },
      "countryCode": "US",
      "currencyCode": "USD",
      "dailyBudget": "10000",
      "profileId": "999918498705620",
      "timezone": "America/Los_Angeles"
    },
    {
      "accountInfo": {
        "marketplaceStringId": "ATVOIKIKX0DER",
        "id": "A3UJU6HLDTTWKS",
        "name": "Woolworths",
        "type": "seller",
        "validPaymentMethod": true
      },
      "countryCode": "US",
      "currencyCode": "USD",
      "dailyBudget": "999999999",
      "profileId": "111184040605621",
      "timezone": "America/Los_Angeles"
    }
  ]
}

So basically in the Lambda function, we are looking at the profileArray which has three objects in it, and we are taking data out of the first object and putting it into the params that we are going to save to DynamoDB.
The items specifically that we are having trouble with is:
"profile_id": { "N": "event.profileArray[0].profileId" },
We can see that we are specifying this piece of data to be a number, and we are inputting it as a string (as we should be) and in the test JSON object, we can see that it is a string. However, when we run this function we get the response:
{
  "statusCode": "400",
  "body": "The parameter cannot be converted to a numeric value: event.profileArray[0].profileId",
  "headers": {
    "Content-Type": "application/json"
  }
}

This is crazy because that item is DEFINITELY a number. I have tried everything I can think of. You can see in the request I console logged the item just to make sure it is coming in correctly and yes, we get the following in the console log:
2591184040605621
One thing that I thought could be the problem is that the profile_id is the sort key of the DynamoDB table, so I made sure that the data type of this sort key is number, so that is not the issue.
Can anyone figure out why this number string cannot be converted to a number!!

A: It can not be converted because you are actually passing it as a string.
Remove the quotes (") around the profileId from your JSON object where you are refencing the event.
...
"profile_id": { "N": event.profileArray[0].profileId }
...


text:
Q: Prove that the set of nonnegative numbers is denumerable

I need to show through a proof that the set of nonnegative numbers is denumerable

I know a set is denumerable if its members or elements can be put into an order and counted. I am supposed to show this through a proof as well.
I was considering using Induction possibly but I'm not sure if this is a viable or feasible method to use. Any help is great appreciated

A: The set of non-negative numbers: I assume you talk of non-negative integers.
The set would be $\{0,1,2,3...\}$.
Every element of the set can be associated with a natural number as $n-1$ where $n$ is the natural number.
That means: $0$ is associated with $1$, $1$ is associated with $2$ and so on. When every element of the given set can be associated with a natural number, It is denumerable (countably infinite).

A: Hint – Your set is $A=\mathbb N\cup\{0\}$. How would you proceed, using this?

A: Every subset of a denumerable set is either denumerable or finite. In particular , your set is an infinite subset of set of all integers and hence denumerable.


text:
Q: Unix zip command
Possible Duplicate:
Zipping folders and their contents into a .zip file in Linux

I need to zip a file on Unix machine. File is about 200MB. What is the best compression tool? and provide me the command to zip the file.
File structure:
- /home/testuser/myfolder/
                     |__  Myfile1.dat [200MB]
                     |__  MyFile2.dat [500MB]

A: One program to zip files would be:
$ zip

To zip a directory:
$ zip -r archive.zip yourdirectory

Other popular ones are tar in conjuction with, e.g. Lempel-Ziv (gzip) or Burrows–Wheeler (bzip) style compression.

A: Basically the "best" compression is lzma. The order of available compressions is lzma, bzip2, gzip and finally compress. Whe you are saying Unix; what do you mean? If you happen to have GNU tar and friends you best option is lzma.
lzma:
tar --lzma -cvf stuff.tar.lzma file1.dat file2.dat

bzip2:
tar -cvjf stuff.tar.bzip2 file1.dat file2.dat

gzip:
tar -cvzf stuff.tar.gz file1.dat file2.dat

Of course if you don't have GNU tools:
compress:
tar -cvf stuff.tar file1.dat file2.dat
compress stuff.tar

A: As already mentioned, binary files do not compress well compared to plain text. I'd just gzip or bzip the file and be done with it. The time spent compressing it to the max with LZMA for example may eventually outweight the time for the extra few MB's of transfer, depending on your transfer medium.
eg.
tar czvf myfolder.tar.gz /home/testuser/myfolder


text:
Q: Is there an approximation function for this function? The function is:
$$f(x,y)=\frac{x}{\log\left(1+\frac{1}{1+y}\right)}$$
where $x\in [0,1], y \in [0,1] $,and the approximation function can split $x$ and $y$.
The result is like this:$f(x,y) = f_1(x)+f_2(y)$.


text:
Q: get array length after splitting string in sql server I would like to be able to split a string in SQL Server . I have a sample string
1012,1012,1012,1012,1012,1012,1012,1012

Here need length after splitting this string.
Expected output: 8

A: I think, to just find the total items in the string you may no need to split the string. Just need to find the number of occurrence of ,.
Query
declare @string varchar(100)
set @string = '1012,1012,1012,1012,1012,1012,1012,1012'

select len(@string ) - len(replace(@string ,',', '')) + 1;

Demo

A: If you only need the number of items in a delimited string, you don't need to split it at all - here is how to do it:
You subtract the length of the string after removing all the delimiters from the length of the original string. This gives you the number of delimiters in the string. Then all you have to do is add one, since you have one more item then delimiters:
DECLARE @String varchar(50) = '1012,1012,1012,1012,1012,1012,1012,1012'

SELECT LEN(@String) - LEN(REPLACE(@String, ',', '')) + 1


text:
Q: Sharing a network port between two docker containers I am running a binary-protocol TCP server in a container.  In order to facilitate zero downtime upgrades, I have constructed a flow where an instance can forward its server socket to the server in the new container by way of a unix domain socket.  This works like a charm until the moment where the first container shuts down.  Since it is the container which has published the port, the port de-publishes once the container closes.  I'm trying to figure out the best way to handle this case.
Here's the basic rundown of what I'm doing:
# start the first container, starts listening on 3290
docker run -p 3290:3290 --name first /my/server/app

# start the second container, "steals" the server socket on 3290 from first
docker run --net container:first /my/server/app

# the second container, at this point, is handling connections from 3290
# when the first container is killed below, the port is de-published
# and the second container stops receiving connections
docker rm first

At first, I thought that a user-defined network would work best, but I cannot find a way to publish a port on a user-defined network.  Another option I am considering is to construct another container which handles the publishing of ports, then have all other containers borrow the network from that running container.  I think that approach will work, I just don't like the idea of having to have this extra container lying around for no other purpose.  Though perhaps that is the only solution, thoughts?

A: https://docs.docker.com/engine/swarm/:

Load balancing: You can expose the ports for services to an external load balancer. Internally, the swarm lets you specify how to distribute service containers between nodes.

Video at the bottom of this post maybe interesting for you: https://blog.docker.com/2016/06/docker-1-12-built-in-orchestration/.


text:
Q: changing uppercase file names in AWS S3 to lowercase I'd like to ask for help with changing uppercase file names in AWS S3 to lowercase.
I got two files, one's a list of file names from an AWS S3 bucket with upper case letter like so (lets call it uppercase.txt):
ABc.txT

aBCd.pHp

AbCdE.jpg

and a second file with a list of the translation of the names to lower case (lowercase.txt, easily done with tr '[:upper:]' '[:lower:]'):
abc.txt

abcd.php

abcde.jpg

I tried a bunch of for loops, the command I wish to repeat is 'aws s3 mv $first_list_value $second_list_value .
Tried this:
for i in `cat uppercase_file.txt`; do aws s3 mv $i `cat lowercase_file.txt`; done

no dice :-( The AWS S3 API is limited and doesn't take well to most linux commands.
Yelp?

A: Something like this should work:
paste uppercase_file.txt lowercase_file.txt | while read uc lc
do
  aws s3 mv $uc $lc
done


text:
Q: Session variable from Select Option I am trying to help users with filling form in the case if their submission was not successfully send.. The first part of the code down below works fine, but the second part is not "detected". Even if the statement is false Select Pair is not shown.
HTML output:
<option selected='selected'> </option>

This is just a small piece of my script.
Any suggestion how to fix this? Thanks!
if(isset($_SESSION['pair'])) {

echo "<option selected='selected'> " . $_SESSION['pair'] . "</option>";

} else {

echo "<option disabled='disabled'>Select Pair</option>";

}

A: unset($_SESSION['pair']);
And run the code again. Chances you didn't properly unset it hence only the first part work.


text:
Q: Sharing A File On Windows Phone 8.1 May someone help im coding my own universal windows store app i want my xaml page to select a file then share it using the share contract on windows phone 8.1 . The problem is my windows phone 8.1 app when i select a file it hits a break point and does no recognize this line of code  IReadOnlyList pickedFiles = await filePicker.PickMultipleFilesAsync(). This works on the Windows 8.1 version not the Windows Phone 8.1 version.
private async void SelectFilesButton_Click(object sender, RoutedEventArgs e)
    {
        FileOpenPicker filePicker = new FileOpenPicker
        {
            ViewMode = PickerViewMode.List,
            SuggestedStartLocation = PickerLocationId.DocumentsLibrary,
            FileTypeFilter = { "*" }
        };

        IReadOnlyList<StorageFile> pickedFiles = await filePicker.PickMultipleFilesAsync();

        if (pickedFiles.Count > 0)
        {
            this.storageItems = pickedFiles;

            // Display the file names in the UI.
            string selectedFiles = String.Empty;
            for (int index = 0; index < pickedFiles.Count; index++)
            {
                selectedFiles += pickedFiles[index].Name;

                if (index != (pickedFiles.Count - 1))
                {
                    selectedFiles += ", ";
                }
            }

            NotifyUser(String.Format("Picked files: ") + selectedFiles + ".", NotifyType.StatusMessage);

            ShareStep.Visibility = Visibility.Visible;
        }
    }
  private void Button_Click(object sender, RoutedEventArgs e)
    {

        DataTransferManager dataTransferManager = DataTransferManager.GetForCurrentView();
        dataTransferManager.DataRequested += new TypedEventHandler<DataTransferManager,
            DataRequestedEventArgs>(this.ShareStorageItemsHandler);
        // If the user clicks the share button, invoke the share flow programatically.
        DataTransferManager.ShowShareUI();

    }

    private async void ShareStorageItemsHandler(DataTransferManager sender,DataRequestedEventArgs e)
    {
        DataRequest request = e.Request;
        request.Data.Properties.Title = TitleInputBox.Text;
        request.Data.Properties.Description = DescriptionInputBox.Text;

        // Because we are making async calls in the DataRequested event handler,
        // we need to get the deferral first.
        DataRequestDeferral deferral = request.GetDeferral();

        // Make sure we always call Complete on the deferral.
        try
        {

            request.Data.SetStorageItems(this.storageItems);
        }
        finally
        {
            deferral.Complete();
        }
    }

A: The file picker API on Windows Phone 8.1 works slightly differently. Instead of FileOpenPicker.PickMultipleFilesAsync you need to call FileOpenPicker.PickMultipleFilesAndContinue. This article provides much more context: https://msdn.microsoft.com/en-us/library/windows/apps/xaml/dn631755.aspx. This is also covered in my Build talk here: http://channel9.msdn.com/Events/Build/2014/2-520.
Finally, the answer to this: Windows Phone, pick file using PickSingleFileAndContinue or PickMultipleFilesAndContinue StackOverflow question also has a sample.

A: In the preview of the Win10 SDK this works the same as on WinRT, so both Phone & anything else will just use PickMultipleFilesAsync


text:
Q: What is suitable ios version for the current Three20 sdk? I try to test one of my app in which I used Three20 sdk.
It worked on ios 4.2, 4.3.1 ipad
but exited immediately when started on ipod touch with ios 3.1.3
I just wonder what is suitable ios version for the current Three20 sdk?
Welcome any comment

A: The Developers at Three20 have set the iOS Deployment Target, which is actual the smalest version a project can run on, to iOS 3.0. So it should be o.k. to run your app on an iOS Version 3.0 or higher.
Three20 is not built to run on the iPad, so I think thats the reason why the app quits. In my own project, I always set the Deployment Target to iOS 4.0.


text:
Q: bind array in cursor using plsql declare
  cursor lc is
    select *
      from (select a.lin, a.pr,
                   b.name, sum(a.up) as u,
                   sum (a.d)         as d
              from li_dy_4 a,
                   p_list  b
             where a.pr=b.id
               and b.parent_id != 0
               and a.partitionid <= 308
               and a.partitionid >= 302
               and a.pr in (91,80)
             GROUP BY a.pr, b.name, a.lin
             order by d desc) ;
  rec lc%ROWTYPE;

BEGIN
  open lc;
  loop
    FETCH lc into rec;
    dbms_output.put_line(rec.pr);
    exit when lc%NOTFOUND;
  end loop;
  close lc;
END;

the above statement works fine for me. What I am not capable of finding anything hopeful is changing the value after the "in" statement which is a.pr in (91,80)
I have listed the values here manually, but I want to pass it to the cursor as an array of numbers for a.pr column. In short I want to do a.pr = idlist wher idlist is an array. Please anyone tell me if my idea is possible.

A: Just want to remind you, the IN clause supports 1000 items only. And that could be the primary reason ,there's nothing called BULK BINDING for SELECT Queries. We have FORALL INSERT/UPDATE, which is like BULK BINDING. Unfortunately select has none.
But still you can achieve your requirement in a different fashion.
You can try a global temporary table(GTT) which a temporary table with "scope of the data inserted" is only to that session.
You can FORALL INSERT all your data for IN clause into that table, and join the TABLE to your Query.
Else you can have a nested table (if oracle 10g) or a simple pl/sql type itself (if oracle 11g), with all your IN class items as records and join it to your Query.
Example: Using NESTED TABLE , effective for less number(<10000) of items
CREATE TYPE pr AS OBJECT
           (pr  NUMBER);
/
CREATE TYPE prList AS TABLE OF pr;
/

declare
  myPrList prList := prList ();
  cursor lc is
    select *
      from (select a.lin, a.pr,
                   b.name, sum(a.up) as u,
                   sum (a.d)         as d
              from li_dy_4 a,
                   p_list  b,
                   TABLE(CAST(myPrList as prList)) my_list
             where a.pr=b.id
               and b.parent_id != 0
               and a.partitionid <= 308
               and a.partitionid >= 302
               and a.pr = my_list.pr
             GROUP BY a.pr, b.name, a.lin
             order by d desc) ;
  rec lc%ROWTYPE;

BEGIN
  /*Populate the Nested Table, with whatever collection you have */
  myPrList := prList ( pr(91),
                       pr(80));
  /*
     Sample code: for populating from your TABLE OF NUMBER type

     FOR I IN 1..your_input_array.COUNT
     LOOP
          myPrList.EXTEND;
          myPrList(I) := pr(your_input_array(I));
     END LOOP;
  */
  open lc;
  loop
    FETCH lc into rec;
    exit when lc%NOTFOUND; -- Your Exit WHEN condition should be checked afte FETCH iyself!
    dbms_output.put_line(rec.pr);
  end loop;
  close lc;
END;
/

A: I don't know the exact structure of your global table but you can use the collection  in cursor like this
declare
 cursor c1 is
  select last_name ls  from empc;
 type x is table of employees.last_name%type;
 x1 x := x();
 cnt integer :=0;
begin
 for z in c1 loop
  cnt := cnt +1;
  x1.extend;
  x1(cnt) := z.ls;
  if x1(cnt) is NULL then-----------
   DBMS_OUTPUT.PUT_LINE('ASHISH');
  end if;
  dbms_output.put_line(cnt || ' '|| x1(cnt));
 end loop;
end;


text:
Q: Replacing comma by dot only in numbers in a texteditor using search and replace function i got a table as txt.file with all the variables beeing seperated by ;.
Lets say i got 3 Variables: ID, Size and Comment.
My Data could look something like this:
1;1.5;hello. how are you?
2;2.5;a comment.
3;2.1;another comment.

Now i would like to replace the comma-sign from dot to comma.
If i use the standard search and replace function in my text-editor it will change all . to , without any problem. But i want to change only those . to , which are surrounded by numbers left side and right side.
1.5 should be changed to 1,5 but hello. how are you? should not be changed to hello, how are you?
I found a regular expression for searching only dots surroundet by numbers:
[0-9][\\.][0-9]

Now i would like to replace those surroundet dots, but unfortunately it doesn't work yet. When replacing [0-9][\\.][0-9] by ,, 1.5 is changed to , only instead of 1,5.
Is there any nice way to use search and replace from a texteditor to solve this problem?
Thanks in advance!

A: EditPlus does not support lookbehinds, so you need to use groups.
(\d)\.(\d)

Substitution: \1,\2

*

*() Capturing group

*\d matches a digit (equal to [0-9])

*\1 \2 Capturing group 1. and group 2.


text:
Q: Read a csv file between 2 rows using php I am try to read a csv file which has 200000 records, and then using loop to insert the record which is quite very slow.
So I want to read the file by 10k. Like first read 1 to 10k and in second time read 10k to 20k and so on.
I have done the following
$row1 = fgetcsv($handle, $delimiter);
$endNumber = 8635;

for ($i = $start; $i < $endNumber; $i++) {
    fgets($handle);
}

It is used to skip the record but it is not working as i need and also used this
for($i = 8; $row = fgetcsv($handle, $delimiter); $i++) {
        if($i === $endNumber) {
            fclose($handle);
           return $rowy;
        }
}


text:
Q: Custom extension method in typescript Well I was trying to create an extension method for my interface Student
declare global {
  interface Student {
   CourseOpted(): String;
  }
 }

 Student.prototype.CourseOpted = function(): string {
  return 'some-string';
 }
 export {};

And when I place cursor on Student:- Getting this error
'Student' only refers to a type, but is being used as a value here.
Was referring this article:- https://www.c-sharpcorner.com/article/learn-about-extension-methods-in-typescript/#:~:text=Extension%2Dmethod%20gives%20you%20the,any%20data%2Dtype%20you%20want.
What I could notice is;- when we extend class for Interface like String, Number, Array..Extension method is possible. Then why not for the above example.
Please help me! Solve this error
Thanks a lot in advance :)
Edited:-
So we found this ts extension method repo:- https://github.com/staeke/ts-extension-methods

A: interface are a compiled time element. When you compile Typescript into Javascript it does not emit anything for an interface. The interface purely exist at compile time (to benefit typescript).
The reason why it works for String, Number, etc. because they exist at runtime.
If you want different implementation of the function

*

*then why not declare Student as a class with default function implementation and allow a sub-class to override the functional implementation as and when required.

If you want a static implementation

*

*then simply declare it as a static function inside the Student class

A: Student is an interface, not class you should create class and import it before making any changes. Maybe it is better just to create new class. You may also add serialization to it, if you take students data from server.
Typescript Playground Link
interface IStudent {
  id: number;
  firstName: string,
  lastName: string,
}

class Student implements IStudent {
  id: number;
  firstName: string;
  lastName: string;

  constructor(student: IStudent)
  constructor(id: number, firstName: string, lastName: string)
  constructor(idOrStudent: number | IStudent, firstName?: string, lastName?: string) {
    if (typeof idOrStudent === "object") {
      this.id = idOrStudent.id;
      this.firstName = idOrStudent.firstName;
      this.lastName = idOrStudent.lastName;
      return;
    }
    this.id = idOrStudent;
    this.firstName = firstName as string;
    this.lastName = lastName as string;
  }

  public foo() {
    return "bar";
  }
}

const student0 = new Student(0, "John", "Doe");
console.log(student0);
console.log(student0.foo());

const student1 = new Student({
  id: 1,
  firstName: "Milka",
  lastName: "Helgi"
});

console.log(student1);


text:
Q: Canvas - Get pixel color in multiple canvas superimpose I have multiple canvas on my page. I want to get the pixel color of all canvas when two or more canvas are superposed.
Please see my example below.
In this example, I want to get the pixel color of all red canvas borders, but because the canvas are superposed, it just return the first one.
I have tried with same z-index without success.

var c = document.getElementById("myCanvas-1");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.lineWidth=7;
ctx.arc(100, 100, 50, 0, 2 * Math.PI);
ctx.strokeStyle = '#ff0000';
ctx.stroke();

var c = document.getElementById("myCanvas-2");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.lineWidth=7;
ctx.arc(100, 100, 50, 0, 2 * Math.PI);
ctx.strokeStyle = '#ff0000';
ctx.stroke();

function findPos(obj) {
    var curleft = 0, curtop = 0;
    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
        return { x: curleft, y: curtop };
    }
    return undefined;
}

function rgbToHex(r, g, b) {
    if (r > 255 || g > 255 || b > 255)
        throw "Invalid color component";
    return ((r << 16) | (g << 8) | b).toString(16);
}

$('.can').mousemove(function(e) {
    var pos = findPos(this);
    var x = e.pageX - pos.x;
    var y = e.pageY - pos.y;
    var coord = "x=" + x + ", y=" + y;
    var c = this.getContext('2d');
    var p = c.getImageData(x, y, 1, 1).data;
    var hex = "#" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);
    $('#status').html(coord + "
" + hex + "
");
});

<canvas class="can"  id="myCanvas-1" width="300" height="200" ></canvas>
<canvas class="can"  id="myCanvas-2" width="300" height="200" style="position:relative;left:-250px" ></canvas>

A: You are using the same variable name for each canvas.
You can give them just two different global instance names.
var c1 = document.getElementById("myCanvas-1");
var c2 = document.getElementById("myCanvas-2");

Suposing your canvases are the same size you have to add the mousemove listener only to one.
Than get the pixel information from the two at the same pixel location inside the handler.
var ctx1 = c1.getContext('2d');
var ctx2 = c2.getContext('2d');
var p1 = ctx1.getImageData(x, y, 1, 1).data;
var p2 = ctx2.getImageData(x, y, 1, 1).data;
var hex1 = "#" + ("000000" + rgbToHex(p1[0], p1[1], p1[2])).slice(-6);
var hex2 = "#" + ("000000" + rgbToHex(p2[0], p2[1], p2[2])).slice(-6);


text:
Q: Execute query string and get result with varying number of columns I am trying to transform a list of correlation values into a correlation matrix.
But I can't get the result after executing a string query.
The list/table(named corrtemp) is like this:
| name | colname | value |
| ---- | ------- | ----- |
| a    | a       | 1     |
| a    | b       | 0.5   |
| a    | c       | 0.3   |
| b    | a       | 0.5   |
| b    | b       | 1     |
| b    | c       | 0.2   |
| c    | a       | 0.3   |
| c    | b       | 0.2   |
| c    | c       | 1     |

The output should be like this:
| name |  a  |  b  |  c  |
| ---- |-----| --- | --- |
| a    |  1  | 0.5 | 0.3 |
| b    | 0.5 |  1  | 0.2 |
| c    | 0.3 | 0.2 |  1  |

The number of distinct names is unknown. So I loop to generate a string query. I want to execute it and get the query result in the result console. Currently, my code is like this:
do $$
declare
    i integer := 0;
     sql0 varchar := 'SELECT DISTINCT temp0.name, cor0.value AS '||(SELECT DISTINCT name FROM corrtemp LIMIT 1)||' FROM corrtemp AS temp0'||chr(13);
     sql1 varchar := 'left JOIN corrtemp AS cor0 ON cor0.colname = temp0.name AND cor0.name = ''a'''||chr(13);
     sql2 varchar := 'WITH temp';
     sql4 varchar;
begin
    sql4 := sql0 || sql1 ||chr(13);
    i := i + 1;
    while i < (SELECT COUNT(DISTINCT name) FROM corrtemp) loop
        sql4 := chr(13)||
                sql2||
                CAST(i AS VARCHAR(5)) ||
                ' AS('||
                chr(13)||
                sql4||
                ')' ||
                'SELECT temp'|| CAST(i AS VARCHAR(5)) || '.*, cor'|| CAST(i AS VARCHAR(5)) ||'.value AS '||(SELECT DISTINCT name FROM corrtemp LIMIT 1 OFFSET i)||' FROM  temp'|| CAST(i AS VARCHAR(5))||chr(13)||
                'left JOIN corrtemp AS cor'|| CAST(i AS VARCHAR(5)) ||  ' ON cor'|| CAST(i AS VARCHAR(5)) || '.colname = temp'|| CAST(i AS VARCHAR(5)) || '.name AND cor'|| CAST(i AS VARCHAR(5)) || '.name = '''|| (SELECT DISTINCT name FROM corrtemp LIMIT 1 OFFSET i)||''''||chr(13);
        i := i + 1;
        end loop;
end$$

I tried EXECUTE sql4  inside the do and it only returns an 'OK' in the information console.
I need the query result to display in the result console just like after simply running SELECT * FROM corrtemp.

A: I tried creating function. It doesn't work. Here's the code:
CREATE FUNCTION list2matrix() RETURNS setof record LANGUAGE plpgsql AS $$
declare
   i integer := 0;
  sql0 varchar := 'SELECT DISTINCT temp0.name, cor0.value AS '||(SELECT DISTINCT name FROM corrtemp LIMIT 1)||' FROM corrtemp AS temp0'||chr(13);
  sql1 varchar := 'left JOIN corrtemp AS cor'|| CAST(i AS VARCHAR(5)) ||  ' ON cor'|| CAST(i AS VARCHAR(5)) || '.colname = temp'|| CAST(i AS VARCHAR(5)) || '.name AND cor'|| CAST(i AS VARCHAR(5)) || '.name = '''|| (SELECT DISTINCT name FROM corrtemp LIMIT 1 OFFSET i)||''''||chr(13);
  sql2 varchar := 'WITH temp';
  sql3 varchar := 'SELECT temp'|| CAST(i AS VARCHAR(5)) || '.*, cor'|| CAST(i AS VARCHAR(5)) ||'.value AS '||(SELECT DISTINCT name FROM corrtemp LIMIT 1 OFFSET i)||' FROM  temp'|| CAST(i AS VARCHAR(5))||chr(13) ;
  sql4 varchar;
begin
   sql4 := sql0 || sql1 ||chr(13);
  i := i + 1;
   while i < (SELECT COUNT(DISTINCT name) FROM corrtemp) loop
      sql4 := chr(13)||
            sql2||
        CAST(i AS VARCHAR(5)) ||
        ' AS('||
        chr(13)||
        sql4||
        ')' ||
        'SELECT temp'|| CAST(i AS VARCHAR(5)) || '.*, cor'|| CAST(i AS VARCHAR(5)) ||'.value AS '||(SELECT DISTINCT name FROM corrtemp LIMIT 1 OFFSET i)||' FROM  temp'|| CAST(i AS VARCHAR(5))||chr(13)||
        'left JOIN corrtemp AS cor'|| CAST(i AS VARCHAR(5)) ||  ' ON cor'|| CAST(i AS VARCHAR(5)) || '.colname = temp'|| CAST(i AS VARCHAR(5)) || '.name AND cor'|| CAST(i AS VARCHAR(5)) || '.name = '''|| (SELECT DISTINCT name FROM corrtemp LIMIT 1 OFFSET i)||''''||chr(13);
    i := i + 1;
     end loop;
         RETURN QUERY EXECUTE sql4;
end$$;

select list2matrix();

It sends the following error message to me:
ERROR:  set-valued function called in context that cannot accept a set
It seems like I still have to define the table structure, which I really can't because the correlation matrix always changes.

A: Unfortunately DO statement hasn't any input/output possibilities. You can change data inside DO statement, but you cannot to use DO statement to get any result.


text:
Q: How to fetch GCP billing by instance name? (Not by type) and is there any association between resource and billing sku id? Can I see GCP billing by instance name? (Not by type)
I am trying to filter GCP billing by instance name, is it possible? I only succeeded to filter by GCP Compute Engine and instance type (n1-standard) etc...
I am trying to programmatically match the machineType associated with a GCP compute instance to the corresponding billing SKU, but am unable to find a key for direct association. For example, here is the response from the machineType API:
{
 "kind": "compute#machineType",
 "name": "n1-standard-32",
 "description": "32 vCPUs, 120 GB RAM",
 "guestCpus": 32,
 "memoryMb": 122880,
 "imageSpaceGb": 0,
 "maximumPersistentDisks": 128,
 "maximumPersistentDisksSizeGb": "65536",
 "zone": "us-east1-b",
 "isSharedCpu": false
}

And here is the corresponding SKU from the cloudbilling APIs:
  "name": "services/XXXX/skus/XXXX",
  "skuId": "XXXX",
  "description": "Standard Intel N1 32 VCPU running in Americas",
  "category": {
    "serviceDisplayName": "Compute Engine",
    "resourceFamily": "Compute",
    "resourceGroup": "N1Standard",
    "usageType": "OnDemand"
  },
  "serviceRegions": [
    "us-central1",
    "us-east1",
    "us-west1"
  ],
  "pricingInfo": [
    {
      "summary": "",
      "pricingExpression": {
        "usageUnit": "h",
        "usageUnitDescription": "hour",
        "baseUnit": "s",
        "baseUnitDescription": "second",
        "baseUnitConversionFactor": 3600,
        "displayQuantity": 1,
        "tieredRates": [
          {
            "startUsageAmount": 0,
            "unitPrice": {
              "currencyCode": "USD",
              "units": "1",
              "nanos": 520000000
            }
          }
        ]
      },
      "currencyConversionRate": 1,
      "effectiveTime": "2018-02-22T12:00:16.647Z"
    }
  ],
  "serviceProviderName": "Google"

There doesn't seem to be a field with value n1-standard-32 in the billing SKU. How do we tie these two together as this page seems to do: https://cloud.google.com/compute/pricing?

A: You can create labels and add to your instances in order to get a breakdown of the charges per instance. This label needs to be added on each instance, once added, you will be able to see the charges per instance on the billing reports by sorting it per label.
Creating and managing labels can be found here
You can use the Resource Manager API and perform a request such as
POST https://cloudresourcemanager.googleapis.com/v1beta1/projects

{
 "labels": {
  "color": "red"
 },
 "name": "myproject",
 "projectId": "our-project-123"
}

You can also add and edit labels for your Compute Engine Instances using the gcloud commands


text:
Q: Ubuntu misindentifies external monitor - how do create a new monitor definition with a correctly sized viewport? I'm connecting an RCA 22" class LED full HDTV, model number DETG215R via HDMI. Ubuntu Display identifies it as an Avolites Ltd 23". It wouldn't bother me except that Ubuntu thinks the monitor is bigger than it is, so the controls for a maximized window are just slightly out of reach.
Any ideas how to troubleshoot this? Or how to create a new monitor definition with a correctly sized viewport? Thanks!

A: You can either set it in some GUI app but I'm not sure about the level of customization or using a command-line tool xrandr:
http://manpages.ubuntu.com/manpages/wily/man1/xrandr.1.html
https://wiki.ubuntu.com/X/Config/Resolution


text:
Q: findOrCreate with include - sequelize.js I want to create a Tournament (if not exists), and a Match (if not exists) associated to the Tournament.
let [match, created] = await Match.findOrCreate( {
  where: {scoreHome: 97, Tournament: {name: "USA South Men's Basketball"}},
  include: [Tournament]
})

If the tournament 'USA South Men's Basketball' is already in the db (let's say with id 1), then the match should be created with TournamentId: 1. If there is already a match in the db with {scoreHome: 97 and TournamentId: 1}, then no match should be created.
  let Match = sequelize.define('Match', {
    scoreHome: DataTypes.INTEGER,
    //...
  })

  Match.associate = models => {
    Match.belongsTo(models.Tournament)
  }

EDIT
Here is the error:

[Error: Invalid value [object Object]]

This works fine
let match = await Match.create({
    scoreHome: 97, Tournament: {name: "USA South Men's Basketball"}
  },{include: [Tournament]}
})

A: I am not sure sequelize will allow this "deep findOrCreate".
But you can achieve the wanted effect using two queries, and the sequelize transaction to make sure the two are linked together:
const t = await sequelize.transaction();

try {
  const [tournament] = await Tournament.findOrCreate({
    where: {name: "USA South Men's Basketball"},
    { transaction: t }
  })
  const [match] = await Match.findOrCreate({
    where: {scoreHome: 97, tournamentId: tournament.id},
    { transaction: t }
  })
  t.commit()
} catch(err) {
  t.rollback()
}

It is a bit more verbose, but with this you are sure of what you do, and it is also (personal opinion) more readable for another dev reading that after you.


text:
Q: Stuck wtih file input and validation error I`m having troubles using carrierwave but it is not strictly related to it.
I have Attachment model:
class Attachment < ActiveRecord::Base
  attr_accessible :event_id, :file, :file_cache
  belongs_to :event
  mount_uploader :file, AttachmentUploader
end

which belongs to Event model
class Event < ActiveRecord::Base

 ATTACHMENTS_LIMIT=3
 attr_accessible ...
              :attachments_attributes
 ...
 has_many :attachments, :dependent => :destroy
 accepts_nested_attributes_for :attachments
end

and a nested form like this:
<%= f.fields_for :attachments do |builder| %>
<fieldset class="attachment">
  <%= builder.file_field :file %>
  <%= builder.hidden_field :file_cache %>
  <%= link_to_remove_fields t("actions.delete"), builder %>
</fieldset>
<% end %>

and it seems ok, unless once you get a validation error - then all file_fields are being reset with blank values. But there is a file_cache pointing to my carrierwave upload path(*uploads/tmp/20121003-1959-2388-3822/Getting_Started.pdf*).
How can i preserve files from being lost when validation error occurs??? Any tip would be greatly appreciated! I`ve smoked up those how-tos from official carrierwave wiki and related posts, but still no luck.

A: Edit: After some investigation, I realize that my "image_path" field and before_validation method weren't necessary. All I had to do was this: https://github.com/jnicklas/carrierwave#making-uploads-work-across-form-redisplays. I'm not sure what the issue with the OP's code is... looks like it should work to me.

Just ran into this same problem. The fact that carrierwave keeps the file stored in a /tmp folder is very helpful. Here's what I did, in a nutshell:
Model:
class Image < AR:B
  mount_uploader :image, ImageUploader
  attr_writer :image_path

  before_validation :set_image

  def set_image
    self.image = File.open(@image_path) if @image_path && !image.present?
    true
  end
end

View (using slim):
- if f.object.image.present?
  = f.hidden_field :image_path, value: f.object.image.current_path

** Note: this exposes, in the raw html, the full path to the file on the production server. If that's a security concern for you, you could encrypt / decrypt the path, or set the value to be the raw image data or something.


text:
Q: I get an inconsistency in the conversion NSDecimalNumber to doubleValue Example:
import UIKit

let amountDecimal:NSDecimalNumber = 22.99

let amount = amountDecimal.doubleValue

Expected: 22.99
Return:   22.990000000000002


text:
Q: Evaluate deep rooted key without nil pointer I have a fairly complex values file, which is complex by design really. A single place to store common config for a number of deployments.
As a result, I need to use a lot of nested values like.
app1:
  environment:
    staging:
      replicas: 3

Which I select with:
{{ index .Values (.Values.app) "environment" (.Values.env) "replicas" }}

This works fine when the values exist.. but I'm looking to put a default in incase it does not and thus I need to be able to evaluate this at every iteration of the tree..
I've tried the obvious combinations, but of course it doesn't work with the likes of;
{{ if index .Values (.Values.app) "environment" (.Values.env) "replicas" }}
replicas: {{ index .Values (.Values.app) "environment" (.Values.env) "replicas" }}
{{ else }}
replicas: 1
{{ end }}

I saw another post on here which talks about the double parenthesis inherited from text/template, but I can't get that to work at all.
For bonus points, can anyone tell me how I can get the built in default function to work with index? I can't seem to get that to work either. I also wonder if theres a better way to handle the multiple (.Values.app) and (.Values.env)?
EDIT:
I've been experimenting with using default to add an empty dict to each step... but still no closer.. this is what I've currently been trying:
{{- $app := index .Values (.Values.appName) -}}
{{- $env := index $app "environment" | default dict -}}
{{- $replicas := index $env (.Values.env) | default dict -}}
{{- if $replicas "replicas" -}}
replicas: {{ index .Values (.Values.appName) "environment" (.Values.env) "replicas" }}
{{- else -}}
replicas: 1
{{- end -}}

EDIT AGAIN:
I'm slowly realising that it's just not possible to do what I'm trying to do in the way I'm trying to do it.. whichever way I think about it, it's going to be a bit messy.
Currently experimenting with this idea (although not yet working)..
{{- if hasKey index .Values (.Values.appName) "environment" -}}
{{- if hasKey index .Values (.Values.appName) "environment" (.Values.env) -}}
replicas: {{ index .Values (.Values.appName) "environment" (.Values.env) "replicas" }}
{{- end -}}
{{- else -}}
replicas: 1
{{- end -}}

My thinking is to evaluate each step with hasKey and proceed only if the previous key exists. But hasKey does not like index because it only wants 2 arguments passed to it. I've tried with a various selection of () to no avail.
EDIT AGAIN, AGAIN:
Feels like I'm nearly there.. not getting nil pointer error now.. but also, not getting replicas at all in the rendered manifest :(
{{ $app := index .Values (.Values.appName) }}
{{ if hasKey $app "environment" }}
{{ $env := index $app "environment" (.Values.env) }}
{{ if hasKey $env "replicas" and not empty $env "replicas" }}
{{ $replicas := index .Values (.Values.appName) "environment" (.Values.env) "replicas" }}
replicas: {{ default "1" $replicas  }}
{{ end }}
{{ end }}

EDIT AGAIN, AGAIN, AGAIN:
I see it!! We're not matching {{ if hasKey $env "replicas" and not empty $env "replicas" }} and thus replicas doesn't make it into the manifest at all. The behaviour I'm seeing makes sense, which means it should be easier to debug..

A: Perhaps a bit long winded, and not the nicest of solutions.. but this one puzzled me for quite a while! This is working as intended.. I'd still like to assemble a more elegant solution, but posting as an answer in case it helps other people.
{{ $app := index .Values (.Values.appName) }}
{{ if hasKey $app "environment" }}
{{ $env := index $app "environment" (.Values.env) }}
{{ if hasKey $env "replicas" and not empty $env "replicas" }}
{{ $replicas := index .Values (.Values.appName) "environment" (.Values.env) "replicas" }}
replicas: {{ $replicas  }}
{{ end }}
{{ else }}
replicas: 1
{{ end }}


text:
Q: drain() vs flush() in ObjectOutputStream Class in Java When I saw descriptions about these two methods as below, I felt a bit confused about them.

protected void drain(): Similar to flush but does not propagate the flush to the underlying stream.
void flush(): Writes any buffered output bytes and flush through to the underlying stream.

For example:
FileOutputStream out = new FileOutputStream("test.txt");

ObjectOutputStream oout = new ObjectOutputStream(out);

Question 1:
If I call oout.flush(), it will force the output data in the ObjectOutputStream to be written to the underlying FileOutputStream, but it doesn't guarantee that these data will be subsequently written from FileOutputStream to the file "test.txt" in the disk since I don't call out.flush(), is this correct?
Question 2:
What if I call oout.drain()?

*

*What executions will be done?

A: Flush will write the data to the test.txt. However, drain is similar to flush but does not propagate the flush to the underlying stream.

A:
Question 1:
If I call oout.flush(), it will force the output data in the ObjectOutputStream to be written to the underlying FileOutputStream, but it doesn't guarantee that these data will be subsequently written from FileOutputStream to the file "test.txt" in the disk since I don't call out.flush(), am I right?

No, you are wrong. It does flush the FileOutputStream. However, as FileOutputStream doesn't buffer or flush, in fact there is no difference between drain() and flush() in this circumstance. If there had been a BufferedOutputStream around the FileOutputStream, there would have been a difference.

Question 2:
What if I call oout.drain()? What executions will be done?

It will flush the ObjectOutputStream but not the underlying stream, exactly as it says in the Javadoc.
You have somehow managed to get this completely back to front. I can't understand how: the Javadoc is quite clear. Also, as drain() is protected it is none of your business anyway.


text:
Q: How to correctly add the rows from a table that were linked by an id to another table on MySQL? Suppose that the following query:
SELECT author, is_public, content
FROM dapp.messages WHERE is_public = '0'

gets the following table:
| author| is_public      | content            |
-----------------------------------------------
|  3240 |0               |Hello, I'm Bertha   |
|  4039 |0               |Hello, I'm Kristina |
|  4810 |0               |Hello, I'm April    |

Now, in this case, the numbers in the column author are linked to a row in another table called credentials, which means that:
3240 is linked to this row in credentials table:
|   id  | first_name   | member_type   |
----------------------------------------
|  3240 |Bertha        | regular       |

4039 is linked to this row in credentials table:
|   id  | first_name   | member_type   |
----------------------------------------
|  4039 |Kristina      | regular       |

4810 is linked to this row in credentials table:
|   id  | first_name   | member_type   |
----------------------------------------
|  4039 |April         | regular       |

So, I would like to know a correct way of adding the first name column from credentials table to the table obtained by the first query in this post, ending up with an output like this:
| author| is_public      | content            | first_name   |
--------------------------------------------------------------
|  3240 |0               |Hello, I'm Bertha   |Bertha        |
|  4039 |0               |Hello, I'm Kristina |Kristina      |
|  4810 |0               |Hello, I'm April    |April         |

I thought that by trying the following query, I would get the desired output from above:
SELECT t1.*, t2.*
FROM (SELECT author, is_public, content
    FROM dapp.messages
    WHERE is_public = '0') t1
CROSS JOIN (SELECT first_name
    FROM dapp.credentials
    WHERE id IN (SELECT author FROM dapp.messages)) t2

But I ended up creating a monstrosity that threw this output:
| author| is_public      | content            | first_name   |
--------------------------------------------------------------
|  3240 |0               |Hello, I'm Bertha   |Bertha        |
|  3240 |0               |Hello, I'm Bertha   |Kristina      |
|  3240 |0               |Hello, I'm Bertha   |April         |
|  4039 |0               |Hello, I'm Kristina |Bertha        |
|  4039 |0               |Hello, I'm Kristina |Kristina      |
|  4039 |0               |Hello, I'm Kristina |April         |
|  4810 |0               |Hello, I'm April    |Bertha        |
|  4810 |0               |Hello, I'm April    |Kristina      |
|  4810 |0               |Hello, I'm April    |April         |

Which I didn't get at all, so I'm stuck.

A: I'm not sure why you think you need a cross join here, it appears you need a simple inner join:
select m.author, m.is_public, m.content, c.first_name
from dapp.messages m
join dapp.credentials c on c.id = m.author
where m.is_public = '0';

As you want a single column a correlated subquery is also a viable option:
  select m.author, m.is_public, m.content,
    (select first_name from dapp.credentials c where c.id = m.author) as first_name
  from dapp.messages m
  where m.is_public = '0';


text:
Q: How to use XmlHolder.removeDomNodes() with namespaces in SOAP-UI I have a namespace-aware xml structure and want to remove one node in XmlHolder. Whenever I specify the name space (by un-commenting one of the two lines below) I receive the following exception at the line of removeDomNodes:

java.lang.RuntimeException: net.sf.saxon.trans.XPathException: XPath
  syntax error at char 1 on line 2 in {\ndeclare namespace ns}:
  Unexpected token "declare namespace" in path expression error

Example:
def soapmessage = '''<ns:basket xmlns:ns="http://example.com">
                    |   <ns:fruit>
                    |      <ns:name>banana</ns:name>
                    |      <ns:color>yellow</ns:color>
                    |     </ns:fruit>
                    |   <ns:fruit>
                    |      <ns:name>apple</ns:name>
                    |      <ns:color>green</ns:color>
                    |     </ns:fruit>
                    |   <ns:fruit>
                    |      <ns:name>strawberry</ns:name>
                    |      <ns:color>red</ns:color>
                    |     </ns:fruit>
                    |</ns:basket>'''.stripMargin()

def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context )

def holder = new com.eviware.soapui.support.XmlHolder( soapmessage )
  //holder.namespaces["ns"] = "http://example.com"
  //holder.declareNamespace("ns", "http://example.com")

assert holder.getNodeValue("//ns:fruit[2]/ns:color[1]") == "green"

holder.removeDomNodes("//ns:fruit[2]")

assert holder.getNodeValue("//ns:fruit[2]/ns:color[1]") == "red"

Question:
It would work if I just let the namespace-declaration commented. But I need them for other methods to work. Is there a workaround for this problem?

A: For removing your node, there is no value in specifying the namespace:
holder.removeDomNodes('//*:fruit[2]')

Alternatively, you could try something like:
holder.getDomNode('//*:basket').removeChild('/*:fruit[2]')


text:
Q: iphone: ubercab aka (uber) map coordinate Can anyone describe how to get the map coordinate of a MKMapView by its position on center of screen?  Check out Uber app (its free).  They have a pin statically located in the middle of the screen and you drag the map but the pin stays there.  The middle of the screen is they find your location (very very quickly) showing you the address you are close to.

A: Heyo! I'm the mobile Engineer at Uber (you asked for some Uber help I assume :)) The trick is to place the pin, which is actually a UIImage, at the center of the map. The pin is on top of the map and is not an annotation. Then, whenever you get the regionDidChangeAnimated callback, you get the coordinate of the center of the map using this:
CLLocationCoordinate2D center = m_mapView.centerCoordinate;
CLLocation *location = [[[CLLocation alloc] initWithLatitude:center.latitude longitude:center.longitude] autorelease];

Ideally, you want the bottom part of the pin to point exactly at the center of the map view.
Hope this helps,
Jordan


text:
Q: MVC: store input value as variable in controller or query view when I need the value? I am building a graphic python application with some sort of MVC (as far as I can tell) pattern implemented.
I have a slider which represents a value. Now, I have two options how to access this value.

*

*I could have a variable in my controller which holds the value of the slider. Whenever the slider is updated in the view, the view transmits the value to the controller through an event.

*I could have a function in the controller which, whenever called for, asks the slider in the view what its current value is.

The second option seems more dynamic, but if I'm making plenty of calls it seems more efficient to have the value stored.
Is the question basically of how often and in what way I expect the value to change, or is there some generally accepted best practice in this situation?


text:
Q: Blackberry specific Mobile Redirect plugin? Is there a Wordpress plugin out there, that redirects only Blackberry visitors to a very simple basic something of the site?
Currently I have a responsive website, a long vertical one with smoothscroll.js (Similar to the Nike one). It responds in iOS, Android, and iPad - and while it displays alright in BB (curve 2009), its very hard to read text. I have to support curve 2009 + BB.
Any suggestions?

A: There isn't one that I know off, however if you wanted to write a script to solve your problem then:
In Javascript:
<script type="text/javascript">
   var userBrowser = navigator.userAgent;
   var url = "http://forblackberryusers.yoursite.com/";
   if (userBrowser.indexOf("BlackBerry") >= 0)
   {
      if (userBrowser.indexOf("WebKit") >= 0)
      {
         window.location = url;
      }
   }
</script>

or alternatively you could be smart and try and create a plugin. In php, I'd imagine it would have something along the lines of:
<?php
   $userBrowser = strtolower($_SERVER['HTTP_USER_AGENT']);
   $blackberry = strrpos($userBrowser, "blackberry");
   $webkit = strrpos($userBrowser, "webkit");
   $url = "http://forblackberryusers.yoursite.com/";

   if (!($pos_blackberry === false))
   {
      if (!($pos_webkit === false))
      {
         header("Location: " . $url);
      }
   }
?>

Hope that helps


text:
Q: Is there a way to get current count of requests on OkHttp client? Is there a way to get current count of running/ waiting requests on OkHTTP library?
I found something like this but it's returns total count of requests.
Log.d(TAG, String.format("Hit count=%d.", getOkHttpClient().getCache().getHitCount()));
Log.d(TAG, String.format("Network count=%d.", getOkHttpClient().getCache().getNetworkCount()));
Log.d(TAG, String.format("EoRequestSpec count=%d.", getOkHttpClient().getCache().getRequestCount()));

I have idea to use Interceptor but would like to know a better way.
EDIT:
I have added log output of my test app. You can see that there is 1 active connection but getConnectionCount() and getHttpConnectionCount() both returns 0.
03-23 15:28:12.559: I/LoggingInterceptor(23131): [com.myapp.android.networking.interceptor.LoggingInterceptor.intercept:29] Sending request http://xyz.xyz.xyz.xyz/my_first_script.php on null
03-23 15:28:13.037: D/MainActivity(23131): [com.myapp.android.MainActivity$1$1.run:78] Connection count=0.
03-23 15:28:13.038: D/MainActivity(23131): [com.myapp.android.MainActivity$1$1.run:82] HTTP connection count=0.
03-23 15:28:13.537: D/MainActivity(23131): [com.myapp.android.MainActivity$1$1.run:78] Connection count=0.
03-23 15:28:13.540: D/MainActivity(23131): [com.myapp.android.MainActivity$1$1.run:82] HTTP connection count=0.
03-23 15:28:13.728: I/LoggingInterceptor(23131): [com.myapp.android.networking.interceptor.LoggingInterceptor.intercept:44] Received response for http://xyz.xyz.xyz.xyz/my_first_script.php in 1176,8ms
03-23 15:28:13.728: I/LoggingInterceptor(23131): X-Powered-By: PHP
03-23 15:28:13.728: I/LoggingInterceptor(23131): Content-type: text/html
03-23 15:28:13.728: I/LoggingInterceptor(23131): Transfer-Encoding: chunked
03-23 15:28:13.728: I/LoggingInterceptor(23131): Date: Mon, 23 Mar 2015 14:28:13 GMT
03-23 15:28:13.728: I/LoggingInterceptor(23131): Server: my_server
03-23 15:28:13.728: I/LoggingInterceptor(23131): OkHttp-Selected-Protocol: http/1.1
03-23 15:28:13.728: I/LoggingInterceptor(23131): OkHttp-Sent-Millis: 1427120892821
03-23 15:28:13.728: I/LoggingInterceptor(23131): OkHttp-Received-Millis: 1427120893720
03-23 15:28:13.735: D/MainActivity(23131): [com.myapp.android.MainActivity$6.onResponse:281]

03-23 15:28:13.737: I/LoggingInterceptor(23131): [com.myapp.android.networking.interceptor.LoggingInterceptor.intercept:29] Sending request http://xyz.xyz.xyz.xyz/my_second_script.php
03-23 15:28:14.056: D/MainActivity(23131): [com.myapp.android.MainActivity$1$1.run:78] Connection count=0.
03-23 15:28:14.058: D/MainActivity(23131): [com.myapp.android.MainActivity$1$1.run:82] HTTP connection count=0.
03-23 15:28:14.536: D/MainActivity(23131): [com.myapp.android.MainActivity$1$1.run:78] Connection count=0.
03-23 15:28:14.538: D/MainActivity(23131): [com.myapp.android.MainActivity$1$1.run:82] HTTP connection count=0.
03-23 15:28:15.036: D/MainActivity(23131): [com.myapp.android.MainActivity$1$1.run:78] Connection count=0.
03-23 15:28:15.038: D/MainActivity(23131): [com.myapp.android.MainActivity$1$1.run:82] HTTP connection count=0.
03-23 15:28:15.536: D/MainActivity(23131): [com.myapp.android.MainActivity$1$1.run:78] Connection count=0.
03-23 15:28:15.538: D/MainActivity(23131): [com.myapp.android.MainActivity$1$1.run:82] HTTP connection count=0.
03-23 15:28:15.873: I/LoggingInterceptor(23131): [com.myapp.android.networking.interceptor.LoggingInterceptor.intercept:44] Received response for http://xyz.xyz.xyz.xyz/my_second_script.php
03-23 15:28:15.873: I/LoggingInterceptor(23131): X-Powered-By: PHP
03-23 15:28:15.873: I/LoggingInterceptor(23131): Content-type: application/json; charset=UTF-8;
03-23 15:28:15.873: I/LoggingInterceptor(23131): Content-Length: 276
03-23 15:28:15.873: I/LoggingInterceptor(23131): Date: Mon, 23 Mar 2015 14:28:15 GMT
03-23 15:28:15.873: I/LoggingInterceptor(23131): Server: my_server
03-23 15:28:15.873: I/LoggingInterceptor(23131): OkHttp-Selected-Protocol: http/1.1
03-23 15:28:15.873: I/LoggingInterceptor(23131): OkHttp-Sent-Millis: 1427120893743
03-23 15:28:15.873: I/LoggingInterceptor(23131): OkHttp-Received-Millis: 1427120895870
03-23 15:28:15.876: D/MainActivity(23131): [com.myapp.android.MainActivity$5.onResponse:251]

03-23 15:28:15.905: I/LoggingInterceptor(23131): [com.myapp.android.networking.interceptor.LoggingInterceptor.intercept:29] Sending request http://xyz.xyz.xyz.xyz/my_second_script.php
03-23 15:28:16.036: D/MainActivity(23131): [com.myapp.android.MainActivity$1$1.run:78] Connection count=0.
03-23 15:28:16.039: D/MainActivity(23131): [com.myapp.android.MainActivity$1$1.run:82] HTTP connection count=0.

...

03-23 15:28:27.536: D/MainActivity(23131): [com.myapp.android.MainActivity$1$1.run:78] Connection count=0.
03-23 15:28:27.538: D/MainActivity(23131): [com.myapp.android.MainActivity$1$1.run:82] HTTP connection count=0.
03-23 15:28:27.706: D/MainActivity(23131): [com.myapp.android.MainActivity$9.run:364] Canceling a call.
03-23 15:28:27.711: I/LoggingInterceptor(23131): [com.myapp.android.networking.interceptor.LoggingInterceptor.intercept:44] Received response for  in 11804,4ms
03-23 15:28:27.714: W/MainActivity(23131): [com.myapp.android.MainActivity$8.onFailure:337] (sendWaitForNewDeviceRequestOverOkHttp)
03-23 15:28:27.714: W/MainActivity(23131): java.io.IOException: Canceled
03-23 15:28:27.714: W/MainActivity(23131):  at com.squareup.okhttp.Call$AsyncCall.execute(Call.java:159)
03-23 15:28:27.714: W/MainActivity(23131):  at com.squareup.okhttp.internal.NamedRunnable.run(NamedRunnable.java:33)
03-23 15:28:27.714: W/MainActivity(23131):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
03-23 15:28:27.714: W/MainActivity(23131):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
03-23 15:28:27.714: W/MainActivity(23131):  at java.lang.Thread.run(Thread.java:856)

03-23 15:28:27.717: I/LoggingInterceptor(23131): [com.myapp.android.networking.interceptor.LoggingInterceptor.intercept:29] Sending request http://xyz.xyz.xyz.xyz/my_second_script.php
03-23 15:28:28.036: D/MainActivity(23131): [com.myapp.android.MainActivity$1$1.run:78] Connection count=0.
03-23 15:28:28.037: D/MainActivity(23131): [com.myapp.android.MainActivity$1$1.run:82] HTTP connection count=0.

...

03-23 15:28:31.036: D/MainActivity(23131): [com.myapp.android.MainActivity$1$1.run:78] Connection count=0.
03-23 15:28:31.037: D/MainActivity(23131): [com.myapp.android.MainActivity$1$1.run:82] HTTP connection count=0.
03-23 15:28:31.231: I/LoggingInterceptor(23131): [com.myapp.android.networking.interceptor.LoggingInterceptor.intercept:44] Received response for http://xyz.xyz.xyz.xyz/my_second_script.php
03-23 15:28:31.231: I/LoggingInterceptor(23131): X-Powered-By: PHP
03-23 15:28:31.231: I/LoggingInterceptor(23131): Content-type: application/json; charset=UTF-8;
03-23 15:28:31.231: I/LoggingInterceptor(23131): Content-Length: 276
03-23 15:28:31.231: I/LoggingInterceptor(23131): Date: Mon, 23 Mar 2015 14:28:30 GMT
03-23 15:28:31.231: I/LoggingInterceptor(23131): Server: my_server
03-23 15:28:31.231: I/LoggingInterceptor(23131): OkHttp-Selected-Protocol: http/1.1
03-23 15:28:31.231: I/LoggingInterceptor(23131): OkHttp-Sent-Millis: 1427120907727
03-23 15:28:31.231: I/LoggingInterceptor(23131): OkHttp-Received-Millis: 1427120911228
03-23 15:28:31.234: D/MainActivity(23131): [com.myapp.android.MainActivity$5.onResponse:251]

03-23 15:28:31.243: I/LoggingInterceptor(23131): [com.myapp.android.networking.interceptor.LoggingInterceptor.intercept:29] Sending request http://xyz.xyz.xyz.xyz/my_second_script.php
03-23 15:28:31.536: D/MainActivity(23131): [com.myapp.android.MainActivity$1$1.run:78] Connection count=0.
03-23 15:28:31.537: D/MainActivity(23131): [com.myapp.android.MainActivity$1$1.run:82] HTTP connection count=0.

...

03-23 15:28:35.536: D/MainActivity(23131): [com.myapp.android.MainActivity$1$1.run:78] Connection count=0.
03-23 15:28:35.538: D/MainActivity(23131): [com.myapp.android.MainActivity$1$1.run:82] HTTP connection count=0.
03-23 15:28:35.842: I/LoggingInterceptor(23131): [com.myapp.android.networking.interceptor.LoggingInterceptor.intercept:44] Received response for http://xyz.xyz.xyz.xyz/my_second_script.php
03-23 15:28:35.842: I/LoggingInterceptor(23131): X-Powered-By: PHP
03-23 15:28:35.842: I/LoggingInterceptor(23131): Content-type: application/json; charset=UTF-8;
03-23 15:28:35.842: I/LoggingInterceptor(23131): Content-Length: 1149
03-23 15:28:35.842: I/LoggingInterceptor(23131): Date: Mon, 23 Mar 2015 14:28:35 GMT
03-23 15:28:35.842: I/LoggingInterceptor(23131): Server: my_server
03-23 15:28:35.842: I/LoggingInterceptor(23131): OkHttp-Selected-Protocol: http/1.1
03-23 15:28:35.842: I/LoggingInterceptor(23131): OkHttp-Sent-Millis: 1427120911246
03-23 15:28:35.842: I/LoggingInterceptor(23131): OkHttp-Received-Millis: 1427120915840
03-23 15:28:35.845: D/MainActivity(23131): [com.myapp.android.MainActivity$3.onResponse:170]
03-23 15:28:36.036: D/MainActivity(23131): [com.myapp.android.MainActivity$1$1.run:78] Connection count=1.
03-23 15:28:36.038: D/MainActivity(23131): [com.myapp.android.MainActivity$1$1.run:82] HTTP connection count=1.
03-23 15:28:36.536: D/MainActivity(23131): [com.myapp.android.MainActivity$1$1.run:78] Connection count=1.
03-23 15:28:36.537: D/MainActivity(23131): [com.myapp.android.MainActivity$1$1.run:82] HTTP connection count=1.
...

Java doc of ConnectionPool class says:

Manages reuse of HTTP and SPDY connections for reduced network
  latency. HTTP requests that share the same {@link
  com.squareup.okhttp.Address} may share a {@link
  com.squareup.okhttp.Connection}. This class implements the policy of
  which connections to keep open for future use.

A: Since version 3 it possible to use queuedCallsCount and runningCallsCount

A: You need to check the ConnectionPool from the client instance.
int connections = getOkHttpClient().getConnectionPool().getConnectionCount();
int httpConnections = getOkHttpClient().getConnectionPool().getHttpConnectionCount();


text:
Q: Transport float with huge precision from Oracle to SQL Server via .Net and SqlBulkCopy Working with ODP.Net I connect to Oracle database and transfer data to SQL Server using SqlBulkCopy.
As most of us already have noticed - Oracle float can hold values with precision higher than the .Net variables can hold.
.Net can hold precision up to 28 and Oracle can have e.g. 30.
In that case, the ODP.Net crashes with "Specified cast is invalid".
Oracle won't adjust their code and Microsoft won't create a new variable with higher precision, which leaves us to do workarounds.
In my case I couldn't find another way, but to convert the Oracle floats to nvarchar and then save them to SQL Server temp table that has a type nvarchar and then with a stored procedure to convert that nvarchar to SQL Server float.
Like that I can keep the original value and don't loose part of it's precision.
ORACLE:
For SqlBulkCopy I use this sql to get data from Oracle:
SELECT TO_CHAR(the_float) FROM the_table;

bulkCopy.WriteToServer(reader);

Then on the SQL Server I see the value, like this:
-,00000000000000088817841970012

This is the default formatting that Oracle does (the leading 0 is missed).
Convert that using
T-SQL
SELECT Try_convert(float,'-,00000000000000088817841970012') FloatValue

(I had to replace the , with . so my SQL Server would recognize it as float and the convert works!)
Try_convert(float,REPLACE('-,00000000000000088817841970012', ',', '.'))  FloatValue

Is this the way to go around the Oracle Float and .Net variables ( ODP.Net and .Net ) inconsistency that I described?

A: Out of all tags you used, I know a little bit of Oracle. Perhaps you're missing the format mask with the TO_CHAR function. Here's an example:
SQL> create table the_table (the_float number);

Table created.

SQL> insert into the_table values (-0.00000000000000088817841970012);

1 row created.

SQL>
SQL> select to_char(the_float) your_result,
  2         to_char(the_float, '0D9999999999999999999999999999999999') my_result
  3  From the_table;

YOUR_RESULT                              MY_RESULT
---------------------------------------- -------------------------------------
-,00000000000000088817841970012          -0,0000000000000008881784197001200000

SQL>

See if it helps (hopefully, it does).
More about format models here: https://docs.oracle.com/en/database/oracle/oracle-database/12.2/sqlrf/Format-Models.html#GUID-EAB212CF-C525-4ED8-9D3F-C76D08EEBC7A