text:
Q: JS function breaks upon entering no argument Here is a simple function, that counts the price of engraving, based on the entered phrase length.
function engravePrice(phraseToEngrave) {

  var pricePerWord = 11;
  var wordsToEngrave = phraseToEngrave.split(' ');

  if (phraseToEngrave.length === 0){
    return 0;
  } else if (phraseToEngrave.length > 0){
    return wordsToEngrave.length * pricePerWord;
  }
}

console.log(`Gift wrap and engraving price is: ${engravePrice('')} Q`);

It actually works pretty well:
engravePrice('Two words') //will return 22, as expected
engravePrice('') //will return 0, as expected

except for one specific situation:
engravePrice() //when it breaks, saying "cannot read property 'split' of undefined"

Is there a solution for that?
Thanks.

A: You need to check phraseToEngrave.for undefined, e.g.
function engravePrice(phraseToEngrave) {
if (!phraseToEngrave) return 0;
...
}

or in ES6, give it a default:
   function engravePrice(phraseToEngrave = '') {
     ...
    }

A: I would do it like this:
function engravePrice(phraseToEngrave) {
  var phraseToEngrave = phraseToEngrave || '';
  var pricePerWord = 11;
  var wordsToEngrave = phraseToEngrave.split(' ');

  if (phraseToEngrave.length === 0){
    return 0;
  } else if (phraseToEngrave.length > 0){
    return wordsToEngrave.length * pricePerWord;
  }
}

Which just converts it to an empty string if nothing is passed.


text:
Q: Generic tree with UNIQUE generic nodes Problem description
I have a generic tree with generic nodes. You can think about it like it is a extended router config with multi-level children elements.
The catch is, that each node can have other generic type that its parent (more details - Typescript Playground).
So when node has children, the problem is lying in typing its nodes generics.
Code
type ReactNode = string

type languageTag = 'en' | 'ru'/* | 'de' | 'cs' | 'fr' | 'cn' | 'pl' */

// the type below may be the problem
type translations<T extends unknown = unknown> = {
  [key in languageTag]: T
}

interface pageData<T extends unknown = unknown> {
  path: string,
  contentTranslations: translations<T>
  element: ReactNode,
  children?: Array<pageData<T>>
}

const informationPageData: pageData<{ hobbies: string/* , fullName: string, birthDate: string, sex: string, ... */ }> = {
  path: 'information',
  contentTranslations: {
    en: { hobbies: 'hobbies' },
    ru: { hobbies: 'хобби' }
  },
  element: 'profile information'
}

const profilePageData: pageData<{ recentPosts: string }> = {
  path: ':profileId',
  contentTranslations: {
    en: { recentPosts: 'recent posts' },
    ru: { recentPosts: 'недавние посты' }
  },
  element: 'profile component',
  children: [ informationPageData ] // Error
}

const profilesPageData: pageData<{ youMayKnow: string }> = {
  path: '/profiles',
  contentTranslations: {
    en: { youMayKnow: 'you may know' },
    ru: { youMayKnow: 'возможно вы знакомы' }
  },
  element: 'profiles list',
  children: [ profilePageData ] // Error
}

Questions
Where should I get those types from?
The goal is to make it as much DRY as it could be. Maybe with type inferring?
Typescript Playground
Can I have your help please?

A: Your problem with pageData interface is the parent T is the same type required by the children. What you want is to open up the generic type to accommodate any record therefor allowing the children to define their own properties.
interface pageData<T extends Record<string, string>> {
  path: string,
  contentTranslations: translations<T>
  element: ReactNode,
  children?: Array<pageData<Record<string, string>>>
}

You will still get the strongly typed nature of the component props, but without the inherited restrictions

redpajama_set_name: RedPajamaStackExchange


text:
Q: In virtual table click function is not working click function is not working. I don,t know the reason
$("img[id^='down']").click(function(){
        alert("hi");
});

after collect some data, a table is display in browser with down image. i need click function for that image but its not working

please help me where iam wrong

A: Because your target element doesn't exist on page load and it loaded using ajax, the
$("img[id^='down']").click(...

doesn't work. You should use event delegation. So your code should changed to
$(document).on('click', "img[id^='down']", function(){
    alert("hi");
})


text:
Q: How to get AEM 6.3 to Livereload clientlibs I am using the gulp-aemsync plugin to sync my css and js changes to a clientlib on an AEM instance. A have a gulp task watching the js and css that runs gulp-aemsync fine (changes are on the site when i refresh), but being a bit lazy as i am it would be nice to get live reload working so that i never have to manually refresh the page while working.
I have tried to follow both these 2 online guides:
https://adobe-consulting-services.github.io/acs-aem-tools/features/live-reload/index.html
https://www.cognifide.com/our-blogs/cq/up-and-running-with-livereload-in-adobe-aem6
Followed the steps of:

*

*installing Netty package on AEM instance

*installing ACS AEM tools package on the AEM instance

*installing the RemoteLiveReload chrome extension (the AEM instance is hosted on AWS)

That didn't work, so i got one of our DevOps engineers to open port 35729 (which is the default for Livereload) on the AEM instance. That still doesn't work, and when i click the chrome browser extension to sync it i get the following message:
Could not connect to LiveReload server. Please make sure that LiveReload 2.3 (or later) or another compatible server is running.
Can anyone help me figure this out as i'd really like to get it working to streamline my workflow.
Thanks

A:
DISCLAIMER: This answer is based on a setup I had working at some point, and by no means is a complete/working answer. But it should give you an alternative to the other tools that exist and get you half way there.

I have not used the tools you are mentioning, but since you are using gulp and aemsync, you could do the following:
In your gulp setup, create a websocket server and basically make that server publish messages everytime aemsync is triggered to push content to AEM.
// start a websocket server
const WebSocket = require('ws'); // requires "npm install ws"
const wss = new WebSocket.Server({ port: 8081 });
const connections = [];
wss.on('connection', function connection(ws) {
  connections.push(ws); // keep track of all clients

  // send any new messages that come to this server, to all connected clients
  ws.on('message', (d) => connections.forEach(connection => connection.send(d)));
});

// create a new websocket to send messages to the websocket server above
const ws = new WebSocket('ws://localhost:8081');

// send a regex to the server every second
// NOTE: CHANGE this to run when aemsync is triggered in your build
setInterval( () => ws.send('reload'), 1000 );

Then in your JS code (on AEM) or really in a <script> tag that you make sure will NOT go beyond your local (or dev/prod) you can setup a websocket listener to refresh the page:
socket = new WebSocket('ws://localhost:8081');
socket.onopen  = // add function for when ws is open
socket.onclose  = // add function for when ws is closed
socket.onerror = // add function for when ws errors
// listen to messages and reload!
socket.addEventListener('message', function (event) {
  location.reload();
});

Alternatively, you could use the chrome plugin I've developed:
https://github.com/ahmed-musallam/websocket-refresh-chrome-ext
It's not perfect by any means. However, for a basic setup, it should work great! an you don't need to touch your AEM JS.


text:
Q: Contraction mapping and linear continous operator I'm working on contraction mapping theorem with parameter, and this leads me to Appendix D of G. Da Prato, Introduction to stochastic analysis and Malliavin calculus.
In the book, it says

whereas I have literally no idea why $G$ defined above is a contraction. Please help me with it

A: Assuming the problem is that you don't see why the final inequality holds, note that if you set $\mu =0$ in D.3, and take norms you get $$|F_x(\lambda, x)y| = \lim_{h\to 0} \frac 1{|h|} |F(\lambda, x+hy) - F(\lambda, x)|$$
By D.1, this becomes
$$|F_x(\lambda, x)y| \le \lim_{h\to 0} \frac 1{|h|} k|hy| = k|y|$$
This holds for any $\lambda, x, y$, so we can rewrite it as
$$|F_x(\alpha, u)y| \le k|y|$$
Now, letting $\alpha= \lambda + \xi h\mu,\ u = x(\lambda) + \xi\big(x(\lambda + h\mu) - x(\lambda)\big),\ y = z$, we have
$$|Gz| \le \int_0^1\left|F_x\bigg(\lambda + \xi h\mu,\ x(\lambda) + \xi\big(x(\lambda + h\mu) - x(\lambda)\big)\bigg)z\right|\,d\xi\le\int_0^1 k|z|\,d\xi = k|z|$$


text:
Q: Search-Mailbox cmdlet availability with app-only authentication in Exchange Online I'm connecting to Exchange Online using PowerShell and the following command:
Connect-ExchangeOnline -AppId APP_ID -CertificateFilePath CERTIFICATE_PATH -Organization ORG_NAME

And would like to use the "Search-Mailbox" cmdlet.
The docs say:

By default, Search-Mailbox is available only in the Mailbox Search or Mailbox Import Export roles, and these roles aren't assigned to any role groups.

The app has the Exchange administrator role assigned in Azure.
In Exchange admin center, I added Exchange administrators to the Discovery Management role group that has the Mailbox Search role enabled.
After reconnecting, Search-Mailbox is still not available:

Search-Mailbox: The term 'Search-Mailbox' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

Could someone please explain why it doesn't work and how to make it work?

A: It worked after I assigned "Mailbox Search" role to the "Organization Management" role group (Exchange administrators role groups inherits from it).

A: When the CmdLet is not available it needs to be imported, installed or run on the correct server. It seems like Search-Mailbox is part of the module ExchangePowerShell.
I believe you either need to import the module in your PowerShell session:
Import-Module -Name 'ExchangePowerShell'

Or run the CmdLet on the Exchange server directly or use Connect-ExchangeOnline.


text:
Q: How to add an item to discogs inventory using python I´m currently trying to automate my shop. That´s why I wanted to add items to my store via discogs api. I tried the official discogs client for python at first but it looks like there is no way to add new items. I only was able to make requests, delete or edit existing items. Then I tried to make my own post request with the following code but I always get a Response 422:
import requests
from requests_oauthlib import OAuth1

auth = OAuth1('YOUR_APP_KEY', 'YOUR_APP_SECRET',
              'USER_OAUTH_TOKEN', 'USER_OAUTH_TOKEN_SECRET')
mydata = {'release_id': 9093239,
          'condition': 'Mint',
          'sleeve_condition' : 'Mint',
          'price' : 5.68,
          'status' : 'For Sale'}
result = requests.post("https://api.discogs.com/marketplace/listings", json=mydata, auth=auth)
print(result)

or a Response 400:
result = requests.post("https://api.discogs.com/marketplace/listings", data=mydata, auth=auth)

I would be very thanksful if someone could pointed out what I do wrong. Thanks to everyone for reading.
All the best
cpow


text:
Q: How to run the multiple instance in parallel for time efficiency in shell scripting I am using shell scripting, where it reads the input file of 16000 lines. It takes more than 8 hours to run the script. I need to reduce that so I divided that to 8 instance and read the data, where I used for loop iterate the 8 files and inside it while loop to read the record from the files. But it is not working.
how can i run 8 instance parallel in background
I need help to run it more efficiency like using a functions or forking process.
Here is the code
for file in "$MY_WORK/CCN_split_files"/*
do
    echo "$file"
    echo "begin read loop"
    ### removing the header record from the file ###
    if [ "$file" == "$MY_WORK/CCN_split_files/ccn.email.list.file00" ]
    then
        mv $MY_WORK/CCN_split_files/ccn.email.list.file00 $MY_WORK/raw_file
        sed -e '/ Regular  /d; / Duplicate  /d' $MY_WORK/raw_file > $MY_WORK/CCN_split_files/ccn.email.list.file00
    fi
    ### end of removing header record  ###

    while read -r record
    do
      reccount=$(( reccount + 1 ))

        ### parse input record

          contact_email=`echo "$record" | cut -f5 -d ''`
              echo "contact email is $contact_email"
          credit_card_id=`echo "$record" | cut -f6 -d ''`
              echo "credit card id is $credit_card_id"
          ref_nr=`echo "$record" | cut -f7 -d ''`
              echo "reference nr is $ref_nr"
          cny_cd=`echo "$record" | cut -f8 -d ''`
              echo "country code is $cny_cd"
          lang=`echo "$record" | cut -f9 -d ''`
              echo "language is $lang"
          pmt_ir=`echo "$record" | cut -f13 -d ''`
              echo "payment ir is $pmt_ir"

        ### set paypal or credit card

          if [ "$pmt_ir" = "3" ]
            then
              pmt_typ="PP"
              echo "payment type is $pmt_typ"
          else
              pmt_typ="CC"
              echo "payment type is $pmt_typ"
          fi

        ### retrieve doc from application

          echo "retrieve from CMOD for $ref_nr"
          GetExit01Cntr=0
          GetExit01='F'
          until [[ $GetExit01 = 'T' ]]
           do
            GetExit01Cntr=`expr $GetExit01Cntr + 1`

            /opt/ondemand/bin/arsdoc get -ac -d $MY_WORK -h $host -u $user -p $pwd -v -i  "WHERE ReferenceNumber='$ref_nr' AND CreditCardId='$credit_card_id'" -f "$folder" -L1 -o "$notify_afp" -v 2> $MY_WORK/$arsdoc_out
            if grep "Retrieving 1 document(s)." $MY_WORK/$arsdoc_out > /dev/null
            then
               GetExit01='T'
               echo "CCN AFP retrieval successful"
            else
               echo "CCN AFP retrieval failed - Performing retry (${GetExit01Cntr})"
               sleep 30
               GetExit01='F'
               if [[ $GetExit01Cntr -ge 3 ]]
               then
                  echo "Max Retry Failure: (GetExit01) - Failed to successfully perform arsdoc get"
                  echo "CCN AFP retrieval failed"
                  echo "CCN AFP retrieval failed" >> $MY_WORK/$logfile
                  exit 12
               fi
            fi
           done

        ### convert to PDF

          echo "afp2pdf conversion begins"

          /a585/app/AFP2PDF_PLUS/afp2pdf.sh -i /a585/app/AFP2PDF_PLUS/a2pxopts2.cfg -n /a585/app/AFP2PDF_PLUS/font -o $MY_WORK/$notify_pdf $MY_WORK/$notify_afp > $MY_WORK/$afp2pdf_out 2>&1

          ReturnCode=`echo $?`
          if [ "$ReturnCode" != "0" ]
            then
             echo "afp2pdf failed"
             echo "afp2pdf failed" >> $MY_WORK/$logfile
             exit 12
          fi

        ### assign message text, subject, and reply address variables

          echo "assign message text, subject, reply"
          if [ $cny_cd = "US" ] && [ $lang = "EN" ] && [ $pmt_typ = "CC" ]
            then
               email_text=$MSG_PATH/ccnotifyusen.new
               email_reply="abx@xx.com"
               email_subject=" Credit Card Billing Adjustment. Ref# $ref_nr"

             elif [ $cny_cd = "CA" ] && [ $lang = "EN" ] && [ $pmt_typ = "CC" ]
               then
                 email_text=$MSG_PATH/ccnotifycaen.new
                 email_reply="abx@xx.com"
                 email_subject="Credit Card Billing Adjustment. Ref# $ref_nr"

             elif [ $cny_cd = "CA" ] && [ $lang = "FR" ] && [ $pmt_typ = "CC" ]
               then
                 email_text=$MSG_PATH/ccnotifycafr.new
                 email_reply="abx@xx.com"
                 email_subject=" Rajustement des frais. Ref. $ref_nr"

             elif [ $cny_cd = "US" ] && [ $lang = "EN" ] && [ $pmt_typ = "PP" ]
               then
                 email_text=$MSG_PATH/ppnotifyusen.new
                 email_reply="abx@xx.com"
                 email_subject=" Billing Adjustment. Ref# $ref_nr"

             elif [ $cny_cd = "CA" ] && [ $lang = "EN" ] && [ $pmt_typ = "PP" ]
               then
                 email_text=$MSG_PATH/ppnotifycaen.new
                 email_reply="abx@xx.com"
                 email_subject=" Billing Adjustment. Ref# $ref_nr"

             elif [ $cny_cd = "CA" ] && [ $lang = "FR" ] && [ $pmt_typ = "PP" ]
               then
                 email_text=$MSG_PATH/ppnotifycafr.new
                 email_reply="ssunkara@ups.com"
                 email_subject_text=`cat $MSG_PATH/ppsubjectcafr`
                 email_subject="$email_subject_text $ref_nr"

             else
               echo "invalid country, language, payment type combination: $cny_cd, $lang, $pmt_typ"
               echo "invalid country, language, payment type combination: $cny_cd, $lang, $pmt_typ" >> $MY_WORK/$logfile
               exit 12
          fi

        ### overlay reply address in .muttrc initialization file

          cd /a585/app/script/
          echo "email via NSGalinaMail"

          /usr/bin/java -jar NSGalinaMail.jar "$email_text"  "$email_subject" "$contact_email" "abc@xx.com" $lang  $cny_cd $MY_WORK/$notify_pdf
          if [ $? -eq 0 ]; then
              emailCountSuccess[$reccount-1]="Success: Email to $contact_email for $ref_nr"
           else
              emailCountFailure[$reccount-1]="Failure: Email to $contact_email for $ref_nr"
           fi

    done < $file
done

A: If you want lots of stuff done in parallel, consider using GNU Parallel. There is a great PDF here explaining how to use it. Specifically, I was using "Section 9 - Pipe Mode" to answer your question.
I am not re-writing all your code for you, just showing you some ideas.
Let's generate a sample file of 16,000 lines to match yours:
seq 16000 > YourFile

And now let's generate a dummy script, called YourScript to process your data, like this:
#!/bin/bash
lines=$(wc -l < /dev/stdin)
echo "Called to process $lines lines"
sleep 2

As you can see, it just count the lines it receives on its stdin and tells you how many there are and sleeps for 2s so you can see what is happening. Make it executable with:
chmod +x YourScript

Now, you can use GNU Parallel. First, let GNU Parallel split your file into chunks of 4,000 lines and pass one chunk to each of 4 jobs:
parallel --pipe -N4000 ./YourScript  < YourFile

Called to process     4000 lines
Called to process     4000 lines
Called to process     4000 lines
Called to process     4000 lines

If you have 4 or more CPU cores, that will have taken 2s because, by default, GNU Parallel starts one job per CPU core.
Now try passing 2,000 lines to each job, and running 4 jobs at a time:
parallel --pipe -j 4 -N2000 ./YourScript  < YourFile

Called to process     2000 lines
Called to process     2000 lines
Called to process     2000 lines
Called to process     2000 lines
Called to process     2000 lines
Called to process     2000 lines
Called to process     2000 lines
Called to process     2000 lines

That will run the first 4 lots of 2,000 lines in 2s, then the second 4 lots of 2,000 lines in a further 2s.
Hopefully you can now see how to parallelise your script. Remember to read from stdin, not from a file!!! If you want your script to run using the filename of your 16,000 line file as a parameter, or the filename of a chunk of that file as chunked up GNU Parallel, you could use:
parallel --pipe -N 2000 --cat YourScript {}

then it will write a temporary file with 2,000 lines call your script and delete the temporary file afterwards.
Useful switches to GNU Parallel are:

*

*parallel --dry-run ... which tells you what it would do without actually doing anything

*parallel --bar ... which gives you a progress bar

*parallel --eta ... which gives you an ETA

Note also that GNU Parallel can distribute work across other machines in your network, and it has fail and retry handling, output tagging and so on...
Also, you run cut 6 times for each line of your 16,000 line file - that means you have to fork nearly 100,000 processes! You can use IFS and read instead of those 6 processes:
IFS='|' read -r f1 f2 f3 <<< "a|b|c"

A:  May be you could declare the tasks ("### parse input record / ### set paypal or credit card / ... and so on ) whithin a function:
proceed_tasks (){
  ### parse input record
  ### set paypal or credit card
 }

then run the loop :
while read -r record
  do
    (proceed_tasks) &
    if (( $i % 50 == 0 ));then wait; fi # Limit to 50 concurrent subshells.
 done

As subshell advise. That should create as many as subprocesses needed, (in the limit of 50)


text:
Q: Magento customer save memory leak I'm trying to edit customer data in bulk (a couple of thousand records) and Magento keeps running out of available memory to run the script.
After some testing with memory_get_usage() the culprit seems to be the $customer->save() method which seems to take 5M of memory for each save but doesn't release it when done.
As a result, when looping through a couple of thousand records it is running of memory.
Here is what I've tried so far:
$customer->clearInstance()
unset($customer)
This doesn't seem to help though.
Below is my code:
public function createCustomerAddress($customerAddressData, $email){
     $customer = Mage::getModel('customer/customer');

     $customer->setWebsiteId(Mage::app()->getWebsite()->getId());
     $customer->loadByEmail($email);

     $address   = Mage::getModel('customer/address');

     $address->addData($customerAddressData);
     $customer->addAddress($address);
     unset($address);
     try{
         $customer->save();
     }catch (Exception $e){
         var_dump($customerAddressData);
         var_dump($e->getMessage());
     }
    echo "\n" . "Before unsetting \n" . memory_get_usage() . "\n";
    $customer->clearInstance();
    unset($customer);
    echo "\n" . "After  \n" . memory_get_usage() . "\n";  // no difference than before
}

Any help would be greatly appreciated.
p.s. I'm not sure if the clearInstance() function (in the Mage_Core_Model_Abstract) does anything, if someone has some insight into this it would be greatly appreciated if its shared :)

A: Memory is only released once there are no references to that variable/object. I suspect -- and will edit my answer once confirmed, that the event system in Magento passes an instance of the model to the observer, and therefore there is a reference to it in memory.
But this is a well documented issue. (one which I commented on in 2011 http://www.magentocommerce.com/boards/viewthread/26561/).

A: I believe this is a known issue across all platforms and versions of Magento. unset() or clearInstance() will not have any effect. Mage::getModel() leaked memory in all instances I've come across (customer, products, orders, etc.). The only way around that I have found is to use a collection instead, if possible (may not be applicable for you), when dealing with a large number of object creations. When your process is complete, the memory will be released.
Are you running out of memory? This is usually not an issue unless you are. If you are running out of memory, perhaps, you can try to break up the bulk process into separate runs in your extension. If this is in a shell script, then it would be easy to break it up. Just create two or more files and run them one after another with predefined ranges of customer entity_ids.

A: I think that this is related to a core PHP issue, which is not easily resolved without extensive modifications to core Magento files.
The only way to get this done is using a workaround:
I propose:
a. If this is being called from the browser, I would do a separate ajax call, as @Julien Lacal recommended in his answer.
b. If this is all being done server side, I would break this down to two scripts, with 1. one that iterates over the existing customer list, and 2. one which calls the createCustomerAddress function, using post params. The second script should then be called using CURL from the first script, so that each instance of the second script runs in isolation, and is not affected by the memory leak.

A: A good workaround would be to build your own admin module for bulk customer import, and have it use Ajax calls to a controller to import data in smaller sets. This way you won't run out of memory because it'll launch a new process each time you make that Ajax call instead of constantly allocating memory because of the Mage::getModel('customer/address')

A: Seems I found a major memory leak when calling Model::save()
After the item has been saved to the database there is the following code in the mentioned method:
$this->_getResource()->addCommitCallback(array($this, 'afterCommitCallback'))

This way the model gets added to the static parameter $_commitCallbacks. The method will be removed if the transaction level is set to zero only.
To solve this either add the following code to your own resource model:
public function addCommitCallback($callback)
{
    return $this;
    //return parent::addCommitCallback($callback);
}

This works only for one type of resource model, you need to do this to all resource models which are updated frequently in your loop. A drawback is that the method afterCommitCallback() of your model is never called.
Another (better) possibility is to overwrite the commit() and rollback() methods and remove the model from the variable in every case.


text:
Q: how to notify user in ios, while app is closed/ inbackground i want to notify the user when a "time" is reached.
for example:
i have an tableview with many rows. this rows are something like reminders where the user can set the date and time of remind.
So in a row the reminder is set to 24 April 12:15.
At this time the App is closed.
So how can i notify the user that this time is reached?
Is there a way to do that without apple push notification service?
Edit 1:
Thanks for answering, here is an example for local notifications:
//This example adds 20 seconds to current time, use it for testing
    UILocalNotification *localNotification = [[UILocalNotification alloc] init];

    NSDate *currentDate = [NSDate date];
    NSDate *currentDatePlus = [currentDate dateByAddingTimeInterval:20];

    localNotification.fireDate = currentDatePlus;
    localNotification.alertBody = @"Hallo ayFon User";
    localNotification.soundName = UILocalNotificationDefaultSoundName;

    [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
    [localNotification release];

EDIT 2:
//Add this for iOS 5 Notifications
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
 UIRemoteNotificationTypeAlert |
 UIRemoteNotificationTypeSound];

A: You have to use the Local Notifications of iOS. They are done in this exact purpose.
You can find documentation here: Local and Push Notification Programming Guide.

A: You don't have to use Push Notifications - you could use Local Notifications instead. They are similar to Push notifications except that they are generated on the device instead so you don't need a network connection.
This is a fairly common pattern for alarm type apps.


text:
Q: How to edit file json with Swift? Can I read a attribute from JSON, change, and push back to the JSON.
Exp: I read json file
let jsonData:NSData = LocalFile.ReadFile(fileName)
let json = try NSJSONSerialization.JSONObjectWithData(jsonData, options: .AllowFragments)
if let m_array = json as? [[String: AnyObject]]{...}

*

*I change value of m_array

*I want to save the json file with a part new content of m_array ?
How can do that?


text: Q: How can we give username/Designation wise access to app features? I'm developing an CRM based android app but i want to add Username or salesperson wise app features like Complaint Management System(CMS) should be visible to only CMS-SALES person,All features like attendence and all should be visible to only admin.How can we do that?


text:
Q: Can't get a simple RewriteRule in .htaccess to work in local WAMP I've enabled mod_rewrite, restarted all services, still not taking affect. Here's what I have in .htaccess:
RewriteEngine on
RewriteRule .* localhost/phpinfo.php
Please advise.

A: First of all rewrite rules in general do not affect the host part of the URL (unless you specify predefined names like REQUEST_URI etc.) just the path part (an excellent article explaining the bits and bytes of URL rewriting.) That said your rules should at least look something like this.
RewriteEngine On
RewriteRule (.+) /phpinfo.php [L]

Furthermore is your AllowOverride directive for that particular vhost (or folder) configured to allow .htaccess files at all? If not .htaccess files will be completely ignored. In order for mod_rewrite to work it needs to be set at least to FileInfo Options.
AllowOverride FileInfo Options


text:
Q: How to derive SurveyMonkey's sample size formula? SurveyMonkey stated their sample size formula on this page as following:
$$ Sample\space Size = \frac{\frac{z^2 \times p(1-p)}{e^2}}{1+(\frac{z^2\times(p(1-p)}{e^2N})} $$
How did they derive such formula?


text:
Q: How do you reset the master key in sql server 2005? Our old DB admin is gone, any ideas?
It looks it was set up many years ago.

A: Assuming that you are trying to reset the database master key you just need to use the ALTER MASTER KEY statement adding in the keyword FORCE.
ALTER MASTER KEY
FORCE REGENERATE WITH ENCRYPTION BY PASSWORD = 'YourNewPassword!';


text:
Q: How to download Rhandsontable output into .xlsx and .pdf? I would like to download rhandsontable output object from an R Shiny app into .xlsx and .pdf format. Does anyone have any idea how to do this? For example, I want to download the tables in the results tab in the app below (the codes are copied from my other question earlier):
library(shiny)
library(rhandsontable)

ui <- navbarPage("App",

                 tabPanel("Input",
                          numericInput('num_of_table', "Number of sub tabs: ", value = 1, min = 1, max = 10),
                          uiOutput("input")),

                 tabPanel("Results",
                          uiOutput("results"))

)

server <- function(input, output,session) {

  ### Input ###
  input_table <- reactive({
    list_of_input_table = list()

    for (i in c(1:input$num_of_table)){
      mat <- matrix(c(1:25) * i, ncol = 5, nrow = 5)
      list_of_input_table[[i]] = as.data.frame(mat)
    }

    index = c(1:i)
    list_of_input_table[index]
  })

  observeEvent(input$num_of_table, {
    lapply(seq_len(input$num_of_table), function(i) {
      output[[paste0('input_table_', i)]] <- renderRHandsontable({
        rhandsontable(input_table()[[i]])
      })
    })
  })

  output$input <- renderUI({

    nTabs = input$num_of_table

    myTabs1 = lapply(seq_len(nTabs), function(x){
      tabPanel(paste("Tab", x),
               column(12,
                      rHandsontableOutput(paste0("input_table_", x))))
    })
    do.call(tabsetPanel, myTabs1)

  })

  ### Results ###
  results_table <- reactive({

    list_of_results_table = list()
    for (i in c(1:input$num_of_table)){
      req(input[[paste0("input_table_", i)]])
      list_of_results_table[[i]] <- hot_to_r(input[[paste0("input_table_", i)]])[2:5]/hot_to_r(input[[paste0("input_table_", i)]])[1:4]
      }
    return(list_of_results_table)
  })

  observeEvent(input$num_of_table, {
    lapply(seq_len(input$num_of_table), function(i) {
      output[[paste0('results_table_', i)]] <- renderRHandsontable({

        rhandsontable(results_table()[[i]])
      })
    })
  })

  output$results <- renderUI({

    nTabs = input$num_of_table

    myTabs2 = lapply(seq_len(nTabs), function(x){
      tabPanel(paste("Tab", x),
               column(12,
                      rHandsontableOutput(paste0("results_table_", x))))
    })
    do.call(tabsetPanel, myTabs2)

  })
}

shinyApp(ui,server)

Appreciate any help! Thanks!

A: This will download the results but you will need to first click all the tabs in the results to essentially have the results rhandsontables active and then hit the downloadButton which you can also change to a downloadLink().
library(shiny)
library(rhandsontable)
library(writexl)

ui <- navbarPage("App",

                 tabPanel("Input",
                          numericInput('num_of_table', "Number of sub tabs: ", value = 1, min = 1, max = 10),
                          uiOutput("input")
                          ),

                 tabPanel("Results",
                          downloadButton("dwnld", "Download Results"),
                          uiOutput("results"))

)

server <- function(input, output,session) {

  ### Input ###
  input_table <- reactive({
    list_of_input_table = list()

    for (i in c(1:input$num_of_table)){
      mat <- matrix(c(1:25) * i, ncol = 5, nrow = 5)
      list_of_input_table[[i]] = as.data.frame(mat)
    }

    index = c(1:i)
    list_of_input_table[index]
  })

  observeEvent(input$num_of_table, {
    lapply(seq_len(input$num_of_table), function(i) {
      output[[paste0('input_table_', i)]] <- renderRHandsontable({
        rhandsontable(input_table()[[i]])
      })
    })
  })

  output$input <- renderUI({

    nTabs = input$num_of_table

    myTabs1 = lapply(seq_len(nTabs), function(x){
      tabPanel(paste("Tab", x),
               column(12,
                      rHandsontableOutput(paste0("input_table_", x))))
    })
    do.call(tabsetPanel, myTabs1)

  })

  ### Results ###
  results_table <- reactive({

    list_of_results_table = list()
    for (i in c(1:input$num_of_table)){
      req(input[[paste0("input_table_", i)]])
      list_of_results_table[[i]] <- hot_to_r(input[[paste0("input_table_", i)]])[2:5]/hot_to_r(input[[paste0("input_table_", i)]])[1:4]
    }
    return(list_of_results_table)
  })

  observeEvent(input$num_of_table, {
    lapply(seq_len(input$num_of_table), function(i) {
      output[[paste0('results_table_', i)]] <- renderRHandsontable({

        rhandsontable(results_table()[[i]])
      })
    })
  })

  output$results <- renderUI({

    nTabs = input$num_of_table

    myTabs2 = lapply(seq_len(nTabs), function(x){
      tabPanel(paste("Tab", x),
               column(12,
                      rHandsontableOutput(paste0("results_table_", x))))
    })
    do.call(tabsetPanel, myTabs2)

  })

  output$dwnld <- downloadHandler(
    filename = function(){ paste0("results.xlsx")},
    content = function(file){
      resultslist <- lapply(1:input$num_of_table, function(x) hot_to_r(input[[paste0("results_table_",x)]]))
      write_xlsx(resultslist, path = file)
    }
  )

}

shinyApp(ui,server)


text:
Q: networkx graph with csv input and plotly output Some background...
I am a beginner to python and networkx...
I have a csv file with multiple columns.
I have extracted the columns that contained the sender and receiver addresses and put them into lists like so:
with open('file.csv,'r') as csv_file:
    lines = csv_file.readlines()

sip = []
dip = []

for line in lines:
    data = line.split(',')
    sip.append(data[9])
    dip.append(data[10])
nodes=list(set().union(sip,dip))
edges=list(set().union(list(zip(sip,dip))))

A quick print of my G.nodes() and G.edges()
gives me the following output:
edges = [('AddressA','AddressB'),('AddressA','AddressC')]
nodes = ['AddressA','AddressB','AddressC']

where edges = [('senderaddress','receiveraddress')]
My goal
I wish to use networkx to plot out connections between senders and receivers.
I am using this page as reference.
This is my current code:
import plotly.graph_objs as go
import networkx as nx
from plotly.subplots import make_subplots

#######CREATE NODES/EDGES#############
G=nx.Graph()
nodes=list(set().union(sip,dip))
edges=list(set().union(list(zip(sip,dip))))
G.add_nodes_from(nodes)
G.add_edges_from(edges)
pos = nx.get_node_attributes(G,'pos')

edge_trace = go.Scatter(
    x=[],
    y=[],
    line=dict(width=0.5,color='#888'),
    hoverinfo='none',
    mode='lines')

for edge in G.edges():
    x0, y0 = G.nodes[edge[0]]['pos']
    x1, y1 = G.nodes[edge[1]]['pos']
    edge_trace['x'] += tuple([x0, x1, None])
    edge_trace['y'] += tuple([y0, y1, None])

node_trace = go.Scatter(
    x=[],
    y=[],
    text=[],
    mode='markers',
    hoverinfo='text',
    marker=dict(
        showscale=True,
        colorscale='YlGnBu',
        reversescale=True,
        color=[],
        size=10,
        colorbar=dict(
            thickness=15,
            title='Node Connections',
            xanchor='left',
            titleside='right'
        ),
        line=dict(width=2)))

for node in G.nodes():
    x, y = G.nodes[node]['pos']
    node_trace['x'] += tuple([x])
    node_trace['y'] += tuple([y])

# ########COLOR NODES#########
for node, adjacencies in enumerate(G.adjacency()):
    node_trace['marker']['color']+=tuple([len(adjacencies[1])])
    node_info = '# of connections: '+str(len(adjacencies[1]))
    node_trace['text']+=tuple([node_info])

# ########CREATE GRAPH#########
fig = go.Figure(data=[edge_trace, node_trace],
             layout=go.Layout(
                title='
Network graph made with Python',
                titlefont=dict(size=16),
                showlegend=False,
                hovermode='closest',
                margin=dict(b=20,l=5,r=5,t=40),
                annotations=[ dict(
                    text="Python code:  https://plot.ly/ipython-notebooks/network-graphs/",
                    showarrow=False,
                    xref="paper", yref="paper",
                    x=0.005, y=-0.002 ) ],
                xaxis=dict(showgrid=False, zeroline=False, showticklabels=False),
                yaxis=dict(showgrid=False, zeroline=False, showticklabels=False)))

fig.show()

However, I end up with this error:
  x0, y0 = G.nodes[edge[0]]['pos']
KeyError: 'pos'

A print(pos) showed that it was empty:
{}

I'm not sure where the error lies. I believe it may have started since I populated the graph with nodes and edges. I am not sure how to rectify it though...

A: I modified some part of the posted code.
With nodes and edges given directly, from the output shown in question.
import plotly.graph_objs as go
import networkx as nx
from plotly.subplots import make_subplots

x = []
y = []
G=nx.Graph()

#from question
edges = [('AddressA','AddressB'),('AddressA','AddressC')]
nodes = ['AddressA','AddressB','AddressC']

print ("nodes =", nodes)
print ("edges =", edges)

G.add_nodes_from(nodes, word1 = 'word2')

pos = nx.get_node_attributes(G,'word1')
G.add_edges_from(edges)
print("pos = ", pos)

This will print pos
Note1:
If I G.add_edges_from before pos = nx.get_node_attributes(G,'word1') ;
then pos = []
If I assign pos = nx.get_node_attributes(G,'word1') before G.add_edges_from  then pos will print correctly
I get output as follows:
nodes = ['AddressA', 'AddressB', 'AddressC']
edges = [('AddressA', 'AddressB'), ('AddressA', 'AddressC')]
pos =  {'AddressA': 'word2', 'AddressB': 'word2', 'AddressC': 'word2'}


text:
Q: Error Showing While Running Pentaho Data Integrator Community Edition on OSX While running spoon.sh from my Mac OS I found following error:

After a long time spoon open but there is no option in Design or Transformation.
I am using OSX 10.13.5

A: This is errors which Pentaho considers as normal and nice in the log. The error is coming from else were.
Are the PENTAHO_JAVA and PENTAHO_JAVA_HOME variables defined? To check run the command set-pentaho-env.sh after having uncommented the two last lines.
${PENTAHO_JAVA_HOME}/java.exe -version and ${PENTAHO_JAVA} -version should give you a java with a version at least 1.8.


text:
Q: Backload thumbnails generation I use Backload as backend for plupload. Is there any way to disable automatic thumbnails generation in backload? I didn't find a notice about that.

A: I found the solution in official documentation. Maybe it would be useful to someone.
Set the path attribute of the thumbnails configuration element to an empty string: <thumbnails path="" ... />

A: Setting path to empty string is not sufficient for backload version 2.2.2. Instead <thumbnails  ... > has a store attribute. So you need to put this into configuration:
<thumbnails store="false" />


text:
Q: Co relation between eCPM and impressions I have heard and seen that the eCPM drops with a higher number of ad impressions. Right now in my game, I show an interstitial ad everytime the user fails in the game (every few seconds). Will this help me get more revenue than it would if I show less ads (cause the eCPM would be higher with less ads)? Should I change my high frequency of ads? Will it make around the same as now?

A: You're eCPM will remain the same no matter how often you show your ads if your CTR (Clickthrough Rate) remains the same. Read this article here for a nice explanation of how eCPM is calculated. A good rule of thumb is, more impressions, better chance for more clicks, more clicks equal more revenue. eCPM is not the end all metric here. Your main concern should be user retention. If users are leaving your application due to the mass amount of ads then lowering your applications ad frequency may pay off in the long run.


text:
Q: Java making confirming exit I have an application. I need to make this, when user click the close button, a confirmation will come ( just like javascript confirm dialog ) , 'Are you sure'? I'm using Swing visual editor in Netbeans and I'm using a listener on window closing. But I can't make it. Any help?

A: Try this code:
jj4.addActionListener(new ActionListener()  // jj4-button's reference to implement exit
    {
        public void actionPerformed(ActionEvent ae)
        {
            if(!jtextarea.getText().equals("") && !jtextarea.getText().equals(fileContent))
            {
                if(fileName == null)
                {
                    //this method have 3 options (1 = YES, 2 = NO, 3 = Cancel)
                    option = JOptionPane.showConfirmDialog(null,"Do you want to save the changes ??");
                    if(option == 0)
                    {
                        //to save the text into file
                        saveAs();
                        System.exit(0);
                    }
                    if(option == 1)
                    {
                        //to exit the program without saving
                        System.exit(0);
                    }
                }
                else
                {
                    option = JOptionPane.showConfirmDialog(null,"Do you want to save the changes ??");
                    if(option == 0)
                    {
                        save();
                        System.exit(0);
                    }
                    if(option == 1)
                    {
                        System.exit(0);
                    }
                }
            }
            else
            {
                System.exit(0);
            }
        }
    });


text:
Q: Error on Command Prompt while pip install -e. (OpenAI Universe) According to OpenAI official website, OpenAI Universe can be installed by:
git clone https://github.com/openai/universe.git
cd universe
pip install -e .

I manage to do the first 2 but the third line didn't work. I get an error which I couldn't troubleshoot after surfing the net for quite a while.

I am running windows. Could it be the reason why it isn't able to install? Sorry if this is a dumb question, I've barely started python.


text:
Q: phpMailer: Send emails to multiple recipients I am trying to send emails to multiple recipients.
So far, I was able to retrieve the email addresses in an array. But the mail function somehow does not accept the email addresses. Instead, it gives an error that it needs at least one email address to send an email, and it displays the emails inside the array.
Have a look at my code below.
$email = "select email from student";

if ($p_address=mysql_query($email))
{
$address = array();

while($row = mysql_fetch_array($p_address))
{
$address[] = $row;
}

for ($i = 0; $i < count($address); $i++) {
$all_address[] = implode(';', $address[$i]);
}

foreach ($all_address as $aa) {

$mail->AddAddress($aa);
}

Hope that you could help. Thanks.

A: Not sure what all that other code is for but something like this should be fine:
if ($p_address=mysql_query($email))
{
  while($row = mysql_fetch_array($p_address))
  {
    $mail->AddAddress($row[0]);
  }
}

A: it seems you have one redundant array - not sure why you need to implode addresses ...
$email = "select email from student";

if ($p_address=mysql_query($email))
{
$address = array();

while($row = mysql_fetch_array($p_address))
{
$address[] = $row;
}

foreach ($address as $aa) {

$mail->AddAddress($aa);
}


text:
Q: Dotnet-core convert raw bytes of http-request to HttpRequest class Let's imagine I have a custom protocol to transport data now I want to wrap an HTTP request in it and pass it to the server on the server I receive a raw byte array of my HTTP request now I want to parse it to HttpRequest class.
Is there any way to parse the raw byte array to HttpRequest in .net-core? Something like this:
Stream mystream = myCustomProtocol.BodyStream; //the body-stream is a complete http request
HttpRequest request = HttpRequestHelper.ReadFrom(mystream);


text:
Q: CORS issue on ajax call in scriptlab I'm testing the scriptlab addin in excel
I try to execute a rest call to an external endpoint, like this
$.ajax({
            url: "https://jsonplaceholder.typicode.com/posts/1",
            dataType: 'JSON',
            headers: {
              'Authorization': 'Basic blablabla',
            })....

Above is working fine. But on a end point where CORS is enabled, I got a xhr.readyState 0 back.
How can I avoid CORS issues? (I'm not the owner of the end point)

A: First off, thanks for trying out Script Lab!
I would begin with answering the following question:  is the issue specific to Office Add-ins and/or Script Lab.  The easiest way might be to try a different JS playground, such as JSFiddle or CodePen.  Can you make the call work there?  This will isolate the question of both CORS and of App Domains (what Slava mentioned). Though
In terms of general guidance, I think you have several options

*

*The service you are calling may allow exceptions for particular URLs (i.e., it may ask you for a URL that you'll be calling from, and whitelist that URL).  If so, give it the URL of https://script-lab-runner.azureedge.net (the URL itself doesn't resolve as it expects to be POST-ed to; but your compiled running snippet will ultimately be running off of it).

*You could create your own server (or perhaps a very small unit of computation, like an Azure Function) to do the call on your behalf server-side (where CORS is a non-issue). And you can have the Azure Function itself accept CORS.  That way you're essentially proxying the request via your own server where you can enable CORS.

Hope this helps!

A: You should modify your manifest file and add into AppDomains tag your domain to be trusted by the app. By default, your add-in can load any page that is in the same domain as the location specified in the SourceLocation element. To load pages that are not in the same domain as the add-in, specify the domains by using the AppDomains and AppDomain elements.


text:
Q: Remove all rows in a CSV file without corresponding/matching timestamp in another CSV file I have 2 CSV files which look like follows:
file1.csv
col1,col2,col3,col4,date,time,col7
1,2,3,4,2019-07-20,12:40:00,0
1,2,3,4,2019-07-20,12:43:00,0
1,2,3,4,2019-07-20,12:44:00,0
1,2,3,4,2019-07-20,12:45:00,0
1,2,3,4,2019-07-20,12:46:00,0
1,2,3,4,2019-07-20,12:47:00,0

file2.csv
date,time,col3
2019-07-20,12:40:00,1
2019-07-20,12:41:00,2
2019-07-20,12:42:00,3
2019-07-20,12:43:00,4
2019-07-20,12:44:00,5
2019-07-20,12:45:00,6
2019-07-20,12:46:00,7
2019-07-20,12:47:00,8

As one can see in file2.csv, for for rows 2 and 3 with timestamps 2019-07-20,12:41:00 and 2019-07-20,12:42:00 respectively, no corresponding rows exist with the same timestamp in file1.csv. I would like to output file2.csv with those specific rows removed so that only rows with matching timestamps in file1.csv will remain.
Is it possible to perform this with a simple command in command line? I have a hunch it might involve regex matching but I am not sure about the most efficient way to perform this operation.
Thank you!

A: Here's one way:
$ awk -F, 'NR==FNR {a[$5 FS $6]; next} ($1 FS $2) in a' file1 file2
date,time,col3
2019-07-20,12:40:00,1
2019-07-20,12:43:00,4
2019-07-20,12:44:00,5
2019-07-20,12:45:00,6
2019-07-20,12:46:00,7
2019-07-20,12:47:00,8

A: csv-sqlite -i file1.csv -i file2.csv \
  'select * from input2 where date || time in (select date || time from input1) |
  csv-header --remove-types'

csv-sqlite is from csv-nix-tools.


text:
Q: Does a "typical" reproducing kernel on a manifold generate an infinite-dimensional RKHS? Let $M$ be a finite dimensional manifold and $k:M\times M\rightarrow\mathbb{R}$ a smooth reproducing kernel. Is the set of all such $k$ with the property that the reproducing kernel Hilbert space generated by $k$ is infinite dimensional an open subset of the collection of all smooth reproducing kernels?
More generally, are there any references that investigate how the set of reproducing kernels on a manifold is organized according to RKHS dimension?


text:
Q: How to configure storage for MsSql Export Purpose in Azure I want to Export Mssql file from azure to local system according to this link
But when I go to Export and click on the storage configuration:

and then it opens configuration form but nothing happen there  and storage option is also closed

Any solution for it ?

A: As a workaround, you can use SqlPackage to export an Azure SQL Database to a local folder in your computer as a bacpac.
SqlPackage /Action:Export /SourceServerName:SampleSQLServer.sample.net,1433 /SourceDatabaseName:SampleDatabase /TargetFile:"F:\Temp\SampleDatabase.bacpac"

A: This is likely a UI bug in the Azure Portal.
Please create an Storage Account prior to exporting the Azure SQL Database and it will be available as follows:


text:
Q: How to set compiler in waf I'm trying to compile 3rd party software which uses waf as the build tool.  I run into problems immediately.
> python waf configure --prefix=install
Checking for program 'g++, c++'          : CC
Could not determine the compiler version ['CC', '-dM', '-E', '-']

The config.log file says (with some extra crap deleted):
Checking for program 'g++, c++'
CC
['CC', '-dM', '-E', '-']
out: No supported cpu target is set, CRAY_CPU_TARGET=x86-64 will be used.
Load a valid targeting module or set CRAY_CPU_TARGET

err: CC-2130 crayc++: WARNING in command line
  The "-d" commandline option is unsupported.
CC-2289 crayc++: ERROR in command line
  Invalid characters after option '-d' in command line item '-dM'.
CC-2107 crayc++: ERROR in command line
  No valid filenames are specified on the command line.

I don't know how to debug waf scripts. Does anyone have any suggestions?  I guess that I have to tell waf to use gcc (or c++) as the compiler, but I can't even figure out how to tell waf to do that.  waf has an argument --check-cxx-compiler, but that doesn't appear to work.


text:
Q: Android\Eclipse the for-each loop This is my code Android extract of java class and complete XML Android file:
            for (int i = 0; i < tokens.length; i++) {
                Log.i("myApp0", tokens[0].toString());
                Log.i("myApp1", tokens[1].toString());
                Log.i("myApp2", tokens[2].toString());

                profileImage.setImageUrl(tokens[0].toString());
                textData.setText(tokens[1].toString());
                textTitle.setText(Html.fromHtml(tokens[2].toString()));
                textTitle.setMovementMethod(LinkMovementMethod.getInstance());
            }

Layout XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <com.loopj.android.image.SmartImageView
        android:id="@+id/profileImage"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_margin="5dp"
        android:background="#444"
        android:padding="3dp"
        android:scaleType="fitCenter" />

    <TextView
        android:id="@+id/textData"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/textTitle"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dip"
        android:linksClickable="true"
        android:text="@string/hello"
        android:textSize="18sp"
        android:textStyle="bold"
        android:maxLines="1"
        android:textColor="@android:color/black" />

</LinearLayout>

I think that the output for each row have the date and title of each photo albums but instead I've the same photo album for each row and in the layout android I've only first date and photo album... why?
04-09 18:38:11.088: I/myApp0(28558): https://Link1
04-09 18:38:11.088: I/myApp1(28558): 09/04/2013
04-09 18:38:11.088: I/myApp2(28558): Pics1
04-09 18:38:11.178: I/myApp0(28558): https://Link1
04-09 18:38:11.178: I/myApp1(28558): 09/04/2013
04-09 18:38:11.178: I/myApp2(28558): Pics1
04-09 18:38:11.188: I/myApp0(28558): https://Link1
04-09 18:38:11.188: I/myApp1(28558): 09/04/2013
04-09 18:38:11.188: I/myApp2(28558): Pics1
04-09 18:38:11.188: I/myApp0(28558): https://Link1
04-09 18:38:11.198: I/myApp1(28558): 09/04/2013
04-09 18:38:11.198: I/myApp2(28558): Pics1
04-09 18:38:11.198: I/myApp0(28558): https://Link1
04-09 18:38:11.208: I/myApp1(28558): 09/04/2013
04-09 18:38:11.208: I/myApp2(28558): Pics1
04-09 18:38:11.208: I/myApp0(28558): https://Link1
04-09 18:38:11.208: I/myApp1(28558): 09/04/2013
04-09 18:38:11.208: I/myApp2(28558): Pics1
04-09 18:38:11.218: I/myApp0(28558): https://Link1
04-09 18:38:11.218: I/myApp1(28558): 09/04/2013
04-09 18:38:11.218: I/myApp2(28558): Pics1
04-09 18:38:11.228: I/myApp0(28558): https://Link1
04-09 18:38:11.228: I/myApp1(28558): 09/04/2013
04-09 18:38:11.228: I/myApp2(28558): Pics1
04-09 18:38:11.228: I/myApp0(28558): https://Link1
04-09 18:38:11.228: I/myApp1(28558): 09/04/2013
04-09 18:38:11.228: I/myApp2(28558): Pics1
04-09 18:38:11.238: I/myApp0(28558): https://Link1
04-09 18:38:11.238: I/myApp1(28558): 09/04/2013
04-09 18:38:11.238: I/myApp2(28558): Pics1
04-09 18:38:11.248: I/myApp0(28558): https://Link1
04-09 18:38:11.248: I/myApp1(28558): 09/04/2013
04-09 18:38:11.248: I/myApp2(28558): Pics1
04-09 18:38:11.248: I/myApp0(28558): https://Link1
04-09 18:38:11.248: I/myApp1(28558): 09/04/2013
04-09 18:38:11.248: I/myApp2(28558): Pics1
04-09 18:38:11.258: I/myApp0(28558): https://Link1
04-09 18:38:11.258: I/myApp1(28558): 09/04/2013
04-09 18:38:11.258: I/myApp2(28558): Pics1
04-09 18:38:11.268: I/myApp0(28558): https://Link1
04-09 18:38:11.268: I/myApp1(28558): 09/04/2013
04-09 18:38:11.268: I/myApp2(28558): Pics1
04-09 18:38:11.288: I/myApp0(28558): https://Link1
04-09 18:38:11.288: I/myApp1(28558): 09/04/2013
04-09 18:38:11.288: I/myApp2(28558): Pics1
04-09 18:38:11.298: I/myApp0(28558): https://Link1
04-09 18:38:11.298: I/myApp1(28558): 09/04/2013
04-09 18:38:11.298: I/myApp2(28558): Pics1
04-09 18:38:11.298: I/myApp0(28558): https://Link1
04-09 18:38:11.298: I/myApp1(28558): 09/04/2013
04-09 18:38:11.298: I/myApp2(28558): Pics1
04-09 18:38:11.308: I/myApp0(28558): https://Link1
04-09 18:38:11.308: I/myApp1(28558): 09/04/2013
04-09 18:38:11.308: I/myApp2(28558): Pics1
04-09 18:38:11.318: I/myApp0(28558): https://Link1
04-09 18:38:11.318: I/myApp1(28558): 09/04/2013
04-09 18:38:11.318: I/myApp2(28558): Pics1

A: I think it's because you have this:
         Log.i("myApp0", tokens[0].toString());
            Log.i("myApp1", tokens[1].toString());
            Log.i("myApp2", tokens[2].toString());

You aren't using the iterator of i.. you're using the constant of 0,1,2 so it's always going to be outputting the same value all those times.

A: You are not using the i variable.
Lets see your code:
 for (int i = 0; i < tokens.length; i++) {
            Log.i("myApp0", tokens[0].toString()); // is going to print always the same thing no matter how many rows this has
            Log.i("myApp1", tokens[1].toString());
            Log.i("myApp2", tokens[2].toString());

            profileImage.setImageUrl(tokens[0].toString()); //is always going to set the same image url
            textData.setText(tokens[1].toString());
            textTitle.setText(Html.fromHtml(tokens[2].toString()));
            textTitle.setMovementMethod(LinkMovementMethod.getInstance());
        }

Are you sure you should use an array of strings?
The best approach is to use an Object that has this elements:
public class Your_Obj {
    String date, profile_img, title;

//here you implement your object and generate the getters and setters
}

and use a List of objects like this:
instead of your tokens array you should use:
List<Your_obj> listYourObjects= getMyObj();

for(Your_Obj obj in listYourObjects){

                profileImage.setImageUrl(obj.getProfile_img);
                textData.setText(obj.getDate);
                textTitle.setText(obj.getTitle));
                textTitle.setMovementMethod(LinkMovementMethod.getInstance());

}

A: Try this
for (int i = 0; i < tokens.length/3; i++) {
            Log.i("myApp0", tokens[i*3 + 0].toString());
            Log.i("myApp1", tokens[i*3 + 1].toString());
            Log.i("myApp2", tokens[i*3 + 2].toString());

            profileImage.setImageUrl(tokens[i*3 + 0].toString());
            textData.setText(tokens[i*3 + 1].toString());
            textTitle.setText(Html.fromHtml(tokens[i*3 + 2].toString()));
            textTitle.setMovementMethod(LinkMovementMethod.getInstance());
        }

Tokens should be Array of Object instead of this. But you can achieve your desired output using this technique.
To show every record with its own View, you have to create ListView as illustrated in this tutorial
public class ImageListAdapter extends BaseAdapter {

       private LayoutInflater mLayoutInflater;
       private ArrayList<String> yourData = new ArrayList<Entry>();

       public ImageListAdapter(Context context) {
          mLayoutInflater = (LayoutInflater) context
                   .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
       }

       @Override
       public int getCount() {
          return yourData.size()/3; // Specifically for your data -- Not recommended
       }

       @Override
       public Object getItem(int position) {
          return yourData.get(position);
       }

       @Override
       public long getItemId(int position) {
          return position;
       }

       @Override
       public View getView(int position, View convertView,
             ViewGroup parent) {
          RelativeLayout itemView;
          if (convertView == null) {
             itemView = (RelativeLayout) mLayoutInflater.inflate(
                      R.layout.list_item, parent, false);

          } else {
             itemView = (RelativeLayout) convertView;
          }

          ImageView profileImage = (ImageView) itemView.findViewById(R.id.listImage);
          TextView textTitle = (TextView) itemView.findViewById(R.id.listTitle);
          TextView textData = (TextView) itemView.findViewById(R.id.listDescription);

            profileImage.setImageUrl(tokens[i*3 + 0].toString());
            textData.setText(tokens[i*3 + 1].toString());
            textTitle.setText(Html.fromHtml(tokens[i*3 + 2].toString()));
            textTitle.setMovementMethod(LinkMovementMethod.getInstance());

          return itemView;
       }

       public void upDateEntries(ArrayList<String> entries) {
          yourData = entries;
          notifyDataSetChanged();
       }
}

Set this Adapter to your ListView by using ListView.setAdapter(/* ImageListAdapter instance */);
Inspired from this


text:
Q: Is fwrite non-blocking? Before calling fflush can I consider fwrite to be = a non-blocking write?
If not, why not and what are my alternatives?

A: fwrite() may block. It uses (usually) an internal buffer with a maximum length. It will send the data (all or part of its internal buffer) when the buffer becomes full.
The setbuf() and setvbuf() functions let you alter the buffer maximum length, and actually provide the block for the buffer, but the details are implementation dependent, so you will have to read the documentation for your specific C library.
Conceptually, if you want guaranteed non-blocking writes under all conditions, then you need potentially infinite buffers, which can be somewhat expensive. You could make your own functions for buffering data (within a block of RAM, using realloc() to make it grow when necessary) and write out (with fwrite() and possible fflush()) only at the end. Alternatively, you could try to use non-blocking I/O in which write functions never block but may respond that they refuse to accept your data due to internal congestion. Non-blocking I/O is not part of the C standard itself (there is no f*() function for that) but can be found under various names on some systems (e.g. with fcntl() and write() on Unix systems).

A: Technically fwrite() is a blocking call in that it does not return until the procedure has completed. However the definition of completion for fwrite() is that the data you supply has been written to an internal file buffer. As a side effect some of that buffer may also be written to the disk as part of the fwrite() call but you cannot rely on that behavior. If you absolutely require the data to be on the disk you need to call fflush().

A: fwrite() is blocking. fwrite() may call fflush() internally at any time.
If all you need it to buffer, then buffer in your own array. fwrite's buffer is typically a few K.


text:
Q: oracle - catsearch string containing dash (-) I have a table which has data like -
Table
abc-123
abc-124
abc-125

when I am doing below catsearch it is running fine -
select * from table
where  CATSEARCH (columna,'abc-*',NULL)>0

but when I add 1 before the *, it is giving me error
select * from table
where  CATSEARCH (columna,'abc-1*',NULL)>0

ORA-29902: error in executing ODCIIndexStart() routine ORA-20000:
  Oracle Text error: DRG-51030: wildcard query expansion resulted in too
  many terms

What I am doing wrong, please help to understand the issue

A: In Oracle Text you can define some preferences while creating the index. In your case you should consider to define your own LEXER and printjoins.
BEGIN
   ctx_ddl.create_preference('INV_DEV_LEXER','BASIC_LEXER');
   ctx_ddl.set_attribute('INV_DEV_LEXER', 'printjoins','.-_%:;/,()?!*+@');
END;

CREATE TABLE inv_dev (name VARCHAR2(255));

INSERT INTO inv_dev VALUES ('abc-123');

INSERT INTO inv_dev VALUES ('abc-124');

INSERT INTO inv_dev VALUES ('abc-125');

CREATE INDEX inv_dev_idx ON inv_dev(name)
        INDEXTYPE IS CTXSYS.CTXCAT
        PARAMETERS (
            'LEXER INV_DEV_LEXER STOPLIST CTXSYS.EMPTY_STOPLIST'
        );

SELECT *
    FROM inv_dev
WHERE CATSEARCH (name,'abc-1*',NULL)>0;

If - sign is not defined in printjoins and defined in skipjoins, the phrase 'abc-123' is indexed as 'abc123'.
Also just escaping the - with \, so:
SELECT *
    FROM inv_dev
WHERE CATSEARCH (name,'abc\-1*',NULL)>0;


text:
Q: how to reset datepicker I am developing a taskmanager on Android 2.1.
I want to reset date and time on clicking the reset button to current date and time.
Help me with the code..
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final EditText next = (EditText) findViewById(R.id.editText1);
final Button sub = (Button) findViewById(R.id.button1);
final Button res = (Button) findViewById(R.id.button2);
final DatePicker dp= (DatePicker) findViewById(R.id.datePicker1);
final TimePicker tp = (TimePicker) findViewById(R.id.timePicker1);

res.setOnClickListener(new View.OnClickListener() {
 public void onClick(final View view) {
     next.setText("");
     dp.refreshDrawableState();
        }
    });
}}

A: //get current time
Time now = new Time();
now.setToNow();

//update the TimePicker
tp.setHour(now.hour);
tp.setMinute(now.minute);

//update the DatePicker
dp.updateDate(now.year, now.month, now.monthDay);

A: Time is now deprecated. Use Calendar instead:
Calendar calendar = Calendar.getInstance();

tp.setHour(calendar.get(Calendar.HOUR_OF_DAY));
tp.setMinute(calendar.get(Calendar.MINUTE));

dp.updateDate(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));


text:
Q: Help debugging my bash script I wrote a script (my first one) that aims to replace an IP address in a bind configfile whenever it detects that the IP that appears in the file is not the same as the current external IP. I have my own domain but no static IP address, so this script kind of solves things.
The script:
#!/bin/bash

###
### Obtains the current external IP, compares it against the defined
### IPs in the bind config file and, if they do not match,
### it modifies them
###

##
## Variables
##

# File to be modified
currfile=/etc/bind/zones/db.nahue.com.ar
# Current external IP
currextip=$(wget http://ipinfo.io/ip -qO -)
# Current bind config file IP
currbindip=$(cut -f6 $currfile | head -15 | tail -1)
# Current serial number
currbindser=$(cut -f 4 $currfile | head -6 | tail -1)
# Current serial number substring
currbindsersub=$(expr substr $currbindser 1 8)
# Same date serial plus one
newserial1=$(expr $currbindser + 1)
# Current date YYYYMMDD
currdate=$(date +%Y%m%d)
# Current date serial format YYYYMMDDXX
newserial=$(date +%Y%m%d)01

if [ "$currextip" != "$currbindip" ]
then
    sed -i -e "s:$currbindip:$currextip:g" "$currfile"
    if [ "$currbindsersub" = "$currdate" ]
    then
        sed -i -e "s:$currbindser:$newserial1:g" "$currfile"
    else
        sed -i -e "s:$currbindser:$newserial:g" "$currfile"
    fi
    service bind9 restart
    exit
else
    exit
fi

Apparently, at some point it misbehaves and leave the bind config file with no IP addresses at all.
Here the config file I'm trying to modify:
;
; bind file for nahue.com.ar
;
$TTL    900
nahue.com.ar.      IN      SOA     ns1.nahue.com.ar.    hostmaster.nahue.com.ar. (
                        2016010403      ;Serial
                        300             ; Refresh
                        60              ; Retry
                        2419200         ; Expire
                        900 )           ; Negative Cache TTL

; Name servers
@               IN      NS              dns1-npastorale.no-ip.org.
@               IN      NS              dns2-npastorale.no-ip.org.
@               IN      A               190.245.154.174 ; Script control line
a               IN      A               190.245.154.174
b               IN      A               190.245.154.174
c               IN      A               190.245.154.174
@               IN      MX      10      a.nahue.com.ar.

I'm hoping you can help me to figure this out, and I hope I have explained the issue correctly.
Thanks in advance!

A: It is possible http://ipinfo.io/ip sometime fails and returns nothing.
Anyway, you should at least do a minimum check on $currextip value before passing it to sed.
Adding something like this should be enough:
if [ -z $currextip ]; then
    echo "Something went wrong with ipinfo.io!"
    exit
fi

I don't know if this is really the cause of your problem, but you should always check for failure cases.
As a side note, you should not use the ":" separator with sed in this context, because if you get an IPv6 at some point things could get really wrong.


text:
Q: Create a new JSON file for every GET request Background story: I'm retrieving details using a GET method. I managed to get the program to parse the output given by the server into a JSON file titled "output.json".
Problem: Every time I make different requests, the output will overwrite any previous content in the output.json file. Is it possible to make a new JSON file for every request?
I am rather new to GoLang and any help will be very useful :)
Note: I am only showing the method that is being used to call the API, if need to, I will show the rest of my code.
Here is my method used:
func render(endpoint string, w http.ResponseWriter, r *http.Request) {
    // check if request has cookie set
    if cookie, err := r.Cookie(COOKIE_NAME); err != nil {
        // else redirect to OAuth Authorization EP
        redirectToOAuth(w, r, endpoint)
    } else {
        session := cookie.Value
        accessToken := sessions[session]

        // pipe api endpoint
        ep := fmt.Sprintf("%s/%s", fidorConfig.FidorApiUrl, endpoint)
        if api_req, err := http.NewRequest("GET", ep, nil); err != nil {
            w.WriteHeader(500)
            w.Write([]byte(err.Error()))
        } else {
            api_req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", accessToken))
            api_req.Header.Set("Accept", "application/vnd.fidor.de; version=1,text/json")

            client := &http.Client{}
            if api_resp, err := client.Do(api_req); err != nil {
                w.WriteHeader(500)
                w.Write([]byte(err.Error()))
            } else {
                if api_resp.StatusCode == 401 { // token probably expired
                    handleLogout(w, r, endpoint)
                    return
                }

                w.Header().Set("Content-Type", "application/json")
                w.WriteHeader(api_resp.StatusCode)

                defer api_resp.Body.Close()
                out, err := os.Create("output.json")
                if err != nil {
                    // panic?
                }
                defer out.Close()
                io.Copy(out, api_resp.Body)

            }
        }
    }
}

A: If you want to append time in your filename (like @Florian suggested), you can do something like this when you are creating file:
out, err := os.Create(fmt.Sprintf("output-%d.json", time.Now().Unix()))
// filename => output-1257894000.json

Here time.Now().Unix() returns  the number of seconds elapsed since January 1, 1970 UTC (aka Unix time). So each time it will create different json file.
More info about time: https://golang.org/pkg/time/#Time.Unix

A: If you don't want your file to be overwritten you can either give the file a different name (for example by appending the current time using time.Now()) or you can append the output to the file, so the output.json contains all json files.


text:
Q: Spring session concurrency tutorial I've started a Spring application in SpringSource Tool Suite and I want to add a session management feature in my web app, that is I want to prevent a user to login using the same account.
I've searched the net for tutorials and guides but failed to find an intuitive one for my knowledge in Spring. Could someone point me to a "tutorial for beginner" article.

A: Spring Security provides this as described here.
The typical Maven dependencies to use are:
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
        <version>3.1.3</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-taglibs</artifactId>
        <version>3.1.3</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
        <version>3.1.3</version>
    </dependency>

In the XML configuration, the declaration is typically something like:
<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:sec="http://www.springframework.org/schema/security"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">

Then you can prefix the security elements with sec: such as
<sec:custom-filter position="CONCURRENT_SESSION_FILTER" ref="concurrencyFilter" />

Or if you go off of the examples from the Spring Security documenation that I linked to, it prefixs the beans namesspace and leaves security as the default. Either way should serve the same purpose.


text:
Q: Don't have an idea how to read this json format I never had troubles to read a json from a url or anything that's builded like this:
{ success: true,
  name: 'Dekirai',
  clan: null,
  level: 7,
  exp: 3193,
  playtime: 0,
  tdrate: 0,
  kdrate: 0,
  matches_played: 0,
  matches_won: 0,
  matches_lost: 0,
  last_online: '2018-03-02T23:00:00.000Z',
  views: 1,
  favorites: 0,
  fame: 0,
  hate: 0 }
but the json I now have uses square brackets inside like this one here:
[ { id: 23,
    name: 'AeriaGames Login',
    player_limit: -1,
    player_online: -1,
    state: 2,
    last_update: '2018-02-14T16:22:28.000Z' },
  { id: 1,
    name: 'Auth',
    player_limit: -1,
    player_online: -1,
    state: 2,
    last_update: '2018-03-03T14:17:22.000Z' },
  { id: 10,
    name: 'English 1 (Europe)',
    player_limit: 4000,
    player_online: 871,
    state: 2,
    last_update: '2018-03-03T14:17:22.000Z' },
  { id: 11,
    name: 'English 2 (Europe)',
    player_limit: 4000,
    player_online: 48,
    state: 2,
    last_update: '2018-03-03T14:17:22.000Z' },
  { id: 12,
    name: 'English 3 (North America)',
    player_limit: 4000,
    player_online: 54,
    state: 2,
    last_update: '2018-03-03T14:17:22.000Z' } ]
My question now is:
How do I read the "player_online" value from "id: 10"?

A: let player_online = yourObject.find(el => el.id === 10).player_online

A: You can use filter method. This will return an array of matched property. Then use dot operator to get the property value

var x = [{
    id: 23,
    name: 'AeriaGames Login',
    player_limit: -1,
    player_online: -1,
    state: 2,
    last_update: '2018-02-14T16:22:28.000Z'
  },
  {
    id: 1,
    name: 'Auth',
    player_limit: -1,
    player_online: -1,
    state: 2,
    last_update: '2018-03-03T14:17:22.000Z'
  },
  {
    id: 10,
    name: 'English 1 (Europe)',
    player_limit: 4000,
    player_online: 871,
    state: 2,
    last_update: '2018-03-03T14:17:22.000Z'
  },
  {
    id: 11,
    name: 'English 2 (Europe)',
    player_limit: 4000,
    player_online: 48,
    state: 2,
    last_update: '2018-03-03T14:17:22.000Z'
  },
  {
    id: 12,
    name: 'English 3 (North America)',
    player_limit: 4000,
    player_online: 54,
    state: 2,
    last_update: '2018-03-03T14:17:22.000Z'
  }
]

var getPlayerOnline = x.filter(function(item) {
  return item.id === 10 // will return object where id is 10

})[0].player_online;

console.log(getPlayerOnline)

A: You can use find for finding the value of player_online.

var data = [{
    id: 23,
    name: 'AeriaGames Login',
    player_limit: -1,
    player_online: -1,
    state: 2,
    last_update: '2018-02-14T16:22:28.000Z'
  },
  {
    id: 1,
    name: 'Auth',
    player_limit: -1,
    player_online: -1,
    state: 2,
    last_update: '2018-03-03T14:17:22.000Z'
  },
  {
    id: 10,
    name: 'English 1 (Europe)',
    player_limit: 4000,
    player_online: 871,
    state: 2,
    last_update: '2018-03-03T14:17:22.000Z'
  },
  {
    id: 11,
    name: 'English 2 (Europe)',
    player_limit: 4000,
    player_online: 48,
    state: 2,
    last_update: '2018-03-03T14:17:22.000Z'
  },
  {
    id: 12,
    name: 'English 3 (North America)',
    player_limit: 4000,
    player_online: 54,
    state: 2,
    last_update: '2018-03-03T14:17:22.000Z'
  }
]

var getPlayerOnline = data.find(obj => obj.id === 12).player_online

console.log(getPlayerOnline)


text:
Q: Поиск по 2 полям из одной таблицы на Yii2 без Gridview Хочу организовать поиск без использования Gridview и вывести результаты поиска в массиве
Есть таблица с такими полями как id... from , to и другие.
Нужно организовать поиск по 2 полям, так что если введенные данные с обеих полей( from и to) одной таблицы есть в базе вывести их в массиве.
Поиск пока не работает. После нажатия на поиск страница обновляется и остается на site/index(без вывода какого либо результата) не знаю почему помогите пожалуйста кто может. Очень хочется чтобы поиск заработал
код из siteController.php
public function actionSearch()
{
    $driver = new Driver();

    if ($driver->load(Yii::$app->request->post())) {

        $driver = Driver::find()
            ->where(['from' => $driver->from])
            ->andWhere(['to' => $driver->to])
            ->one();

        return $this->render('search', ['driver' => $driver]);
    }
    else {
        throw new NotFoundHttpException('Input data not found' );
    }
}

код из models/Driver.php
<?php

namespace app\models;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use Yii;
/**
 * This is the model class for table "driver".
 *
 * @property string $id
 * @property string $from
 * @property string $to
 * @property string $data
 * @property string $about
 * @property string $car
 */
class Driver extends \yii\db\ActiveRecord{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'driver';
    }
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
//            [['from', 'to', 'data', 'about', 'car'], 'required'],
            [['about'], 'string'],
            [['from', 'to', 'data', 'car'], 'string', 'max' => 255],
        ];
    }
    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'from' => 'From',
            'to' => 'To',
            'data' => 'Data',
            'about' => 'About',
            'car' => 'Car',
        ];
    }

}

код из site/index.php
<?php
use yii\widgets\ActiveForm;
use yii\helpers\Html;
use app\models\Driver;
/* @var $driver app\models\Driver */
?>
<?php
$driver = new Driver;
?>

              <?php $form = ActiveForm::begin(); ?>

                      <?= $form->field($driver, 'from')->label('От')->textInput(['class' => 'input form-control']) ?>

                      <?= $form->field($driver, 'to')->label('До')->textInput(['class' => 'input form-control']) ?>

                      <input type="image" src="<?= \Yii::getAlias('@web/images/button_search.png')?>" class="icon_button" alt="Поиск" >

              <?php ActiveForm::end(); ?>

код из site/search.php
    <?php
use yii\widgets\LinkPager;

$this->title = "Поиск";

$this->registerMetaTag([
    'name' => 'description',
    'content' => 'driver',
]);
$this->registerMetaTag([
    'name' => 'keywords',
    'content' => 'driver',
])

?>
<?php

?>

    <?php if (!$driver) { ?>

Ничего не найдено

    <?php } else { ?>
        <?php foreach ($driver as $one){
        $from = $one -> from;
        $to = $one -> to;
        $data = $one -> data;
        ?>

<?=$from?>

<?=$to?>

            <?=$data?>

<?php  }?>
<?php } ?>

и site/found_drivers.php
он теперь пустой

A: Вы неверно составляете запросы и некорректно используете ActiveRecord.
Ваш запрос выглядит примерно так:
SELECT * FROM driver WHERE from = "<from>" AND to = "<to>";

Для формирования его в ActiveRecord требуется:
$journey = Driver::find()
    ->where(['from' => $driver->from])
    ->andWhere(['to' => $driver->to])
    ->one();

В итоге ваш метод в SiteController будет выглядеть так:
public function actionDriver()
{
     $driver = new Driver();

     if ($driver->load(Yii::$app->request->post())) {

         $driver = Driver::find()
             ->where(['from' => $driver->from])
             ->andWhere(['to' => $driver->to])
             ->one();

         return $this->render('driver', ['driver' => $driver]);
     }
}

Также советую перечитать документацию по Yii2


text:
Q: FileProvder Security Exception in library I have a library which needs to have a fileprovider and in order to prevent conflict with the implementing app's FileProvider, I used the approach mentioned here. Although the library has no issues building and the library tested in the sample application, It throws the below exception.
Note: Despite the exception, I'm able to share the content out to other apps using share intent. I'm going clueless why the exception occurs while still the files are shared without any crash.
Exception:
E/DatabaseUtils: Writing exception to parcel
java.lang.SecurityException: Permission Denial: reading com.library.package.reporter.FilesProvider uri content://com.library.package.sample.com.library.package.provider.fileprovider/./reports/2020-03-28%2022%3A42%3A50_report.txt from pid=3158, uid=1000 requires the provider be exported, or grantUriPermission()
    at android.content.ContentProvider.enforceReadPermissionInner(ContentProvider.java:729)
    at android.content.ContentProvider$Transport.enforceReadPermission(ContentProvider.java:602)
    at android.content.ContentProvider$Transport.query(ContentProvider.java:231)
    at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:104)
    at android.os.Binder.execTransactInternal(Binder.java:1021)
    at android.os.Binder.execTransact(Binder.java:994)

Manifest:
<provider
        android:name=".reporter.FilesProvider"
        android:authorities="${applicationId}.com.library.package.provider.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/filepaths" />
    </provider>

FileProvider Usage:
Uri uri = FilesProvider.getUriForFile(getApplicationContext(), getPackageName() + ".com.library.package.provider.fileprovider", new File(filePath));
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("*/*");
intent.putExtra(Intent.EXTRA_TEXT, content);
intent.putExtra(Intent.EXTRA_STREAM, uri);
context.startActivity(Intent.createChooser(intent, context.getString(R.string.intent_share_title)));

Should I just ignore the crash and move on or is there something I'm doing wrong?


text:
Q: How Prevent a book from being downloaded by restricting IP? I would like to restrict from being downloaded a digital book by someone who did not buy it. Is there a way to do it?
When the user buys the book, it is sent to him a link from where he can download it, but he is the only person that can read it and can´t share it. Likely, only his IP is allowed to read this book.


text:
Q: MongoDB NULL Pointer Exception while getting JSON as input package com.demo.mongodb;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.util.JSON;

public class Driver {
    private static DBCollection channelDBcollection;

    public static void main(String[] args) throws IOException {
        DB db = (new MongoClient("localhost",27017)).getDB("demo");
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        boolean flag = false;
        while(!flag) flag = autenticate(db, bufferedReader);
    }
    private static boolean autenticate(DB db, BufferedReader bufferedReader) throws IOException{
        boolean flag = true;
        System.out.println("User: ");
        String user = bufferedReader.readLine();

        System.out.println("Password: ");
        String password = bufferedReader.readLine();

        if(db.authenticate(user, password.toCharArray())){
            DBCollection channDbCollection = db.getCollection("Channel");
            String command = null;
            while(true){
                System.out.println("What do you want to do ? ");
                command = bufferedReader.readLine();
                if(command.equals("exit")) break ;
                else if(command.equals("findALL")) findAll(channDbCollection);
                else if(command.equals("insertJSON")) insertJSON(bufferedReader,channDbCollection);
            }
        }
        else{
            System.out.println("invalid user/password");
            flag = false;
        }

        return flag;
    }

    private static void findAll(DBCollection dbCollection){
        DBCursor dbCursor = channelDBcollection.find();
        while(dbCursor.hasNext()) System.out.println(dbCursor.next());
    }

    private static void insertJSON(BufferedReader bufferedReader,DBCollection channDbCollection) throws IOException {

        System.out.println("JSON: ");
        channDbCollection.insert((DBObject) JSON.parse(bufferedReader.readLine()));
    }
}

I make Database in MongoDB like :-

use demo
db.addUser("root","root")

While i executed application then while i enter for JSON , i found null pointer can someone help me to take out of this ?

A: in your
private static void findAll(DBCollection dbCollection){
    DBCursor dbCursor = channelDBcollection.find();
    while(dbCursor.hasNext()) System.out.println(dbCursor.next());
}

function, you use global variable channelDBcollection (which is null at the time of call) instead of parameter dbCollection (which is not used anywhere in the method);
what you think is "not null" is the local variable with confusing name "channDbCollection", but it's not used anywhere;
I suggest you to revise your approach to naming, using global variables and coding style in general.


text:
Q: PowerBI. Проблемы с кодировкой заголовка при импорте из MySQL При импорте данных в PowerBI из базы MySQL заголовки столбцов вместо кириллицы отображаются кракозябрами. При этом сами значения отображаются корректно кириллицей. Как это можно пофиксить?

СHARSETS:


text:
Q: KendoUI Datasource when not bound to any controls I'm using a KendoUI Datasource in several places, some are bound to controls others are not.  The call is to a remote web service and can be quite expensive some I'm trying to just execute it first.
The first time I need the data is for a situation where it is not bound to a control.
I call a function similar to this to create the datasouce:

function BuildDS() {
    var DS = new kendo.data.DataSource({
        transport: {
            read: {
                url: "../WS/GetData",
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                type: "POST"
            }
        }
    });

    return DS;
}

I then have another function which iterates through the DS.
function GetName(DSIn, fieldID) {

    DSIn.read();

    var visname = "";
    $.each(DSIn.data(), function (idx, vis) {
        if (vis.FIELD_ID == fieldID) {
            visname = vis.DISPLAY_LABEL;
            return false;
        }
    });
    return visname;
}

I can see that the remote web service is being invoked and returns the data as expected. However the data() property of the DS always returns no data.
When I bind the same datasource to a Kendo control then the data is populated on the DS.

A: Retrieving the data from the server is an async operation, so when you iterate, this call hasn't completed yet. You should use fetch instead:
dataSource.fetch(function(){
  var data = this.data();
  console.log(data.length);

  // now you can iterate over data
});


text:
Q: pandas dataframe.to_sql throws error when writing to MariaDB When I try and execute the code below, python gives me a mariadb.ProgrammingError: Cursor is closed even though the data was successfully written to the db. I guess there is something wrong with returning the rowcount (see the full traceback below). Is this a possible bug or am I missing something?
code sample
import pandas as pd
from sqlalchemy import create_engine
conn_str = 'mariadb+mariadbconnector://user:password@localhost:3306/database_name'
engine = create_engine(conn_str)
df = pd.DataFrame(data={'col1': [1, 2, 3], 'col2': ['A', 'B', 'C']})
df.to_sql('pandas_test_table', index=False, con=engine, if_exists='replace')

traceback
Traceback (most recent call last):
  File "C:\Program Files\Python310\lib\code.py", line 90, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
  File "C:\Users\user\AppData\Roaming\Python\Python310\site-packages\pandas\core\generic.py", line 2951, in to_sql
    return sql.to_sql(
  File "C:\Users\user\AppData\Roaming\Python\Python310\site-packages\pandas\io\sql.py", line 697, in to_sql
    return pandas_sql.to_sql(
  File "C:\Users\user\AppData\Roaming\Python\Python310\site-packages\pandas\io\sql.py", line 1739, in to_sql
    total_inserted = sql_engine.insert_records(
  File "C:\Users\user\AppData\Roaming\Python\Python310\site-packages\pandas\io\sql.py", line 1322, in insert_records
    return table.insert(chunksize=chunksize, method=method)
  File "C:\Users\user\AppData\Roaming\Python\Python310\site-packages\pandas\io\sql.py", line 950, in insert
    num_inserted = exec_insert(conn, keys, chunk_iter)
  File "C:\Users\user\AppData\Roaming\Python\Python310\site-packages\pandas\io\sql.py", line 858, in _execute_insert
    return result.rowcount
  File "C:\Users\user\AppData\Roaming\Python\Python310\site-packages\sqlalchemy\util\langhelpers.py", line 1113, in __get__
    obj.__dict__[self.__name__] = result = self.fget(obj)
  File "C:\Users\user\AppData\Roaming\Python\Python310\site-packages\sqlalchemy\engine\cursor.py", line 1691, in rowcount
    self.cursor_strategy.handle_exception(self, self.cursor, e)
  File "C:\Users\user\AppData\Roaming\Python\Python310\site-packages\sqlalchemy\engine\cursor.py", line 846, in handle_exception
    raise err
  File "C:\Users\user\AppData\Roaming\Python\Python310\site-packages\sqlalchemy\engine\cursor.py", line 1689, in rowcount
    return self.context.rowcount
  File "C:\Users\user\AppData\Roaming\Python\Python310\site-packages\sqlalchemy\engine\default.py", line 1439, in rowcount
    return self.cursor.rowcount
  File "C:\Users\user\AppData\Roaming\Python\Python310\site-packages\mariadb\cursors.py", line 541, in rowcount
    self.check_closed()
  File "C:\Users\user\AppData\Roaming\Python\Python310\site-packages\mariadb\cursors.py", line 55, in check_closed
    raise mariadb.ProgrammingError("Cursor is closed")
mariadb.ProgrammingError: Cursor is closed

package version
mariadb==1.1.4
pandas==1.4.3
SQLAlchemy==1.4.40

A: I had attempted Georg Richter's recommendation regarding installing MariaDB 1.1.5 from source or rolling back to 1.1.3 and was still receiving the error message.
Eventually, I came across this documentation and had changed the engine DBAPI from
uri = 'mariadb+mariadbconnector://Username:Password@localhost/test'

to
uri = 'mariadb+pymysql://Username:Password@localhost/test'

And it worked.

A: It's a bug in MariaDB Connector/Python.
It's already fixed in 1.1.5 (not released yet). If you don't want to downgrade to 1.1.3 you have to build 1.1.5 from source.

A: Hummm... I'm using mariadb version 1.1.5.post3, but I get the same error. Just the last lines of the data insertion code, which doesn't raise any error in case I use the pymysql connector:
new_employee = {'id': '105', 'first_name': 'Joao',
                'last_name': 'da Silva', 'description': 'Lorem Ipsum', 'active': '1'}
emp = {k: [v] for k, v in new_employee.items()}
df = pd.DataFrame(
    emp, columns=['id', 'first_name', 'last_name', 'description', 'active'])
df.to_sql('employees', con=cnx, index=False, if_exists='append')

The error:
    raise mariadb.ProgrammingError("Cursor is closed")
mariadb.ProgrammingError: Cursor is closed

Just in case, I've tried to downgrade to the version 1.1.5 mentioned above (using pip install, not from the source). Other packages versions:
SQLAlchemy        1.4.46
pandas            1.5.2

P. S. Although we have this error, the data is inserted into the Maria DB table.


text:
Q: C++ Universal Windows app only works when VS2015 project on install drive Steps to rep:

*

*Create a new, blank, UWP, VC++ app project (File --> New -->  Project --> Visual C++ --> Windows --> Universal --> Blank App)

*Store the project on D:\  (Visual Studio is installed on C:)

*Hit F5 to build and run the app (I'm running in Debug, x64)

Error:

4. Now repeat the process but this time store the project on C:.
Everything works just fine.

How do I configure Visual Studio to let me run projects stored on a drive different than the drive on which VS is installed?

Specs:

*

*Microsoft Visual Studio Enterprise 2015

*Version 14.0.24720.00 Update 1

*Microsoft .NET Framework

*Version 4.6.01038

*Windows 10 (fully patched).

A: As per my comment on the question, I have the same issue. I'm not sure this counts as an answer as it's a workaround, but this at least for a C# Universal project...
Go to the project properties for the app and set the Output path to a location on C drive.
e.g. C:\dev\MyTestApp\bin\x86\Debug
(for Debug build. Likewise substitute x64 for x86 for 64bit etc)
It will build and run with the output on C drive but the project remains on the other drive.
Not an ideal solution, but avoids the error.


text:
Q: Why can't I get reproducible results in Keras even though I set the random seeds? I'm training a MobileNet architecture on dummy data with Keras, on Mac OSX. I set both nump.random and tensorflow.set_random_seed, but for some reasons I can't get reproducible results: each time I rerun the code, I get different results. Why? This is not due to the GPU, because I'm running on a MacBook Pro 2017 which has a Radeon graphics card, thus Tensorflow doesn't take advantage of it. The code is run with
python Keras_test.py

so it's not a problem of state (I'm not using Jupyter or IPython: the environment should be reset each time I run the code).
EDIT: I changed my code by moving the setting of all seeds before importing Keras. The results are still not deterministic, however the variance in results is much smaller than it was before. This is very bizarre.
The current model is very small (as far as deep neural network go) without being trivial, it doesn't need a GPU to run and it trains in a few minutes on a modern laptop, so repeating my experiments is within anyone's reach. I invite you to do it: I'd be very interested in learning about the level of variation from a system to another.
import numpy as np
# random seeds must be set before importing keras & tensorflow
my_seed = 512
np.random.seed(my_seed)
import random
random.seed(my_seed)
import tensorflow as tf
tf.set_random_seed(my_seed)

# now we can import keras
import keras.utils
from keras.applications import MobileNet
from keras.callbacks import ModelCheckpoint
from keras.optimizers import Adam
import os

height = 224
width = 224
channels = 3
epochs = 10
num_classes = 10

# Generate dummy data
batch_size = 32
n_train = 256
n_test = 64
x_train = np.random.random((n_train, height, width, channels))
y_train = keras.utils.to_categorical(np.random.randint(num_classes, size=(n_train, 1)), num_classes=num_classes)
x_test = np.random.random((n_test, height, width, channels))
y_test = keras.utils.to_categorical(np.random.randint(num_classes, size=(n_test, 1)), num_classes=num_classes)
# Get input shape
input_shape = x_train.shape[1:]

# Instantiate model
model = MobileNet(weights=None,
                  input_shape=input_shape,
                  classes=num_classes)

model.compile(loss='categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])
# Viewing Model Configuration
model.summary()

# Model file name
filepath = 'model_epoch_{epoch:02d}_loss_{loss:0.2f}_val_{val_loss:.2f}.hdf5'

# Define save_best_only checkpointer
checkpointer = ModelCheckpoint(filepath=filepath,
                             monitor='val_acc',
                             verbose=1,
                             save_best_only=True)

# Let's fit!
model.fit(x_train, y_train,
          batch_size=batch_size,
          epochs=epochs,
          validation_data=(x_test, y_test),
          callbacks=[checkpointer])

As always, here are my Python, Keras & Tensorflow versions:
python -c 'import keras; import tensorflow; import sys; print(sys.version, 'keras.__version__', 'tensorflow.__version__')'
/anaconda2/lib/python2.7/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.
  from ._conv import register_converters as _register_converters
Using TensorFlow backend.
('2.7.15 |Anaconda, Inc.| (default, May  1 2018, 18:37:05) \n[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)]', '2.1.6', '1.8.0')

Here are some results obtained running this code multiple times: as you can see, the code saves the best model (best validation accuracy) out of 10 epochs with a descriptive filename, so comparing filenames across different runs allows to judge the variability in results.
model_epoch_01_loss_2.39_val_3.28.hdf5
model_epoch_01_loss_2.39_val_3.54.hdf5
model_epoch_01_loss_2.40_val_3.47.hdf5
model_epoch_01_loss_2.41_val_3.08.hdf5

A: You can find the answer at Keras docs: https://keras.io/getting-started/faq/#how-can-i-obtain-reproducible-results-using-keras-during-development.
In short, to be absolutely sure that you will get reproducible results with your python script on one computer's/laptop's CPU then you will have to do the following:

*

*Set PYTHONHASHSEED environment variable at a fixed value

*Set python built-in pseudo-random generator at a fixed value

*Set numpy pseudo-random generator at a fixed value

*Set tensorflow pseudo-random generator at a fixed value

*Configure a new global tensorflow session

Following the Keras link at the top, the source code I am using is the following:
# Seed value
# Apparently you may use different seed values at each stage
seed_value= 0

# 1. Set `PYTHONHASHSEED` environment variable at a fixed value
import os
os.environ['PYTHONHASHSEED']=str(seed_value)

# 2. Set `python` built-in pseudo-random generator at a fixed value
import random
random.seed(seed_value)

# 3. Set `numpy` pseudo-random generator at a fixed value
import numpy as np
np.random.seed(seed_value)

# 4. Set the `tensorflow` pseudo-random generator at a fixed value
import tensorflow as tf
tf.random.set_seed(seed_value)
# for later versions:
# tf.compat.v1.set_random_seed(seed_value)

# 5. Configure a new global `tensorflow` session
from keras import backend as K
session_conf = tf.ConfigProto(intra_op_parallelism_threads=1, inter_op_parallelism_threads=1)
sess = tf.Session(graph=tf.get_default_graph(), config=session_conf)
K.set_session(sess)
# for later versions:
# session_conf = tf.compat.v1.ConfigProto(intra_op_parallelism_threads=1, inter_op_parallelism_threads=1)
# sess = tf.compat.v1.Session(graph=tf.compat.v1.get_default_graph(), config=session_conf)
# tf.compat.v1.keras.backend.set_session(sess)

It is needless to say that you do not have to to specify any seed or random_state at the numpy, scikit-learn or tensorflow/keras functions that you are using in your python script exactly because with the source code above we set globally their pseudo-random generators at a fixed value.

A: The key point of making result reproducible is to disable GPU. See my answer at another question (link https://stackoverflow.com/a/57121117/9501391) which has been accepted.