Posts

Showing posts from June, 2011

crontab - why flock run two process? -

[root@vm_47_86_centos bin]# ps -ef | grep moni root 2078 2075 0 apr04 ? 00:00:00 flock -xn /tmp/svr_lock /data1/svr/bin/monitor.sh root 2082 2078 0 apr04 ? 00:07:35 /bin/bash /data1/svr/bin/monitor.sh root 3438 3303 0 10:30 pts/0 00:00:00 grep --color=auto moni root 14249 14243 0 apr04 ? 00:00:00 flock -xn /tmp/svr_lock /data1/svr/bin/monitor.sh root 14253 14249 0 apr04 ? 00:07:32 /bin/bash /data1/svr/bin/monitor.sh crontab : * * * * * flock -xn /tmp/svr_lock /data1/svr/bin/monitor.sh monitor.sh damon. why use flock or there 2 processes

swift - Difference between before and after in viewDidLoad -

i have tried set searchbar tableheaderview inside of viewdidload : override func viewdidload() { super.viewdidload() // searchcontroller initializiation self.searchcontroller = uisearchcontroller.init(searchresultscontroller: nil) self.searchcontroller.delegate = self self.searchcontroller.searchbar.delegate = self self.searchcontroller.searchbar.sizetofit() self.searchcontroller.searchresultsupdater = self self.searchcontroller.searchbar.bartintcolor = uicolor.white self.searchcontroller.searchbar.keyboardappearance = .default self.searchcontroller.searchbar.backgroundcolor = uicolor.white self.searchcontroller.hidesnavigationbarduringpresentation = true self.searchcontroller.obscuresbackgroundduringpresentation = false self.tableview.tableheaderview = self.searchcontroller.searchbar self.definespresentationcontext = true self.fetch() self.tableview.reloaddata() } and fetch() function: func fetch() {

android - How can a widely used custom button track which class its onclick is called from? -

in application, have custom button used in many different custom views. behavior differs depending on view button clicked in, want have 1 @onclick implementation in custom button class takes care of every case in order avoid having similar code in every custom view class. is there way can determine in @onclick block button clicked from? it looks like public class custombutton extends appcompactimagebutton { //stuff @onclick public void onbuttonclick(){ //handles general behavior //if (clicked customviewa) { //do stuff //} } } and have customviewa has custombutton within it, i'm not sure put in if statement, if that's proper way handle this you can use tag attribute. in xml layouts, add line android:tag="viewname" to xml button (in code can .settag("viewname") . can modify onclick check tag using this.gettag() , use identify click came from.

php - How to get password_verify to work for me -

using password_hash() able hash password , store long string in database. however, when try use password_verify(), having trouble confirming value entered matches hashed value stored in database can log in. $uid = $_post['uid']; $pwd = $_post['pwd']; $sql = "select * user uid='$uid'"; $result = $conn->query($sql); $row = $result->fetch_assoc(); $hash_pwd = $row['pwd']; if (password_verify($pwd, $hash_pwd)) { $sql = "select * user uid='$uid' , pwd='$hash_pwd'"; $result = $conn->query($sql); if (!$row = $result->fetch_assoc()) { echo "your username or password incorrect!"; } else { $_session['id'] = $row['id']; } }

dialog - uwp - How to make ContentDialog size according to contents? -

in contentdialog , have stackpanel 3 controls (vertical orientation). problem contentdialog's height stretches way bottom of window though contents don't occupy half of it. i'm having guess stackpanel 's issue, nevertheless how fix this? i set maxheight , have fill fixed values differ per contentdialog ... update this in mainpage.xaml (default starting page of vs uwp template). xaml shows creation of 1 use-case button, on click event: private async void button_click(object sender, routedeventargs e) { dataentrydialog dialog = new dataentrydialog(); //show dialog await dialog.showasync(); } dataentrydialog.xaml: <contentdialog x:class="app1.dialogs.useraccountdataentrydialog" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

java - Websphere Liberty - How to fetch the keystore password from windows registry? -

i have application running on websphere liberty , trying explore ways fetch keystore password windows registry. for instance - adding keystore service object entry server.xml file. keystore element called defaultkeystore , contains keystore password. <keystore id="samplepkcs12keystore" password="mypassword" location="mykeystorefile.p12" type="pkcs12" /> is there way fetch password windows registry instead of having having in server.xml? can there hook established java code ( application code) server.xml ? thanks i not believe possible store passwords in non-filesystem storage. best option encrypt server.xml passwords , store decryption key in separate directory. note document describes, server needs access actual passwords, fundamentally, can ever obscure rather prevent unauthorized access passwords.

java - from Missed Function Call

i'm sorry if posted elsewhere (i can't find anything, problem rather specific), understand (or least in theory) error is; having trouble on how fix it. code supposed show how merge sort works; code runs, never hits function call "merge" (code below, know bad practice call in in imports, isn't major project, don't care; maybe preview, written import java.util. ; , import java.security. ;). import java.util.*; import java.security.*; public class merge { public static void mergesort(int[] data) { sortarray(data, 0, data.length - 1); } private static void sortarray(int[] data, int low, int high) { if ((high - low) >= 1) { int m1 = low + high; int m2 = m1 + 1; system.out.printf("split: %s\n", subarraystring(data, low, high)); system.out.printf(" %s\n", subarraystring(data, low, m1)); system.out.printf(" %s\n\n", subar

python - Silent printing and scanning windows 7 -

hi there way implement script do silent scan , silent print epson 'mfc-l2700dw'... software used 'cc4', on windows 7 machine tried wiaacmgr , cc4 give me gui... wiaacmgr /? what options available if ? or there python module that? or batch file make ??? else ....i try on gsscript no success... p = subprocess.popen([r"p:\ath\to\gsprint.exe", "test.pdf"], stdout=subprocess.pipe, stderr=subprocess.pipe) stdout, stderr = p.communicate() print stdout print stderr any welcome

java - Decoding File from Disc Cache into Bitmap referencing to same Bitmap Object -

i trying load added bitmap disc cache recyclerview. processed bitmap disc cache returning different image referencing same bitmap object. hence of imageview in recyclerview change processed bitmap. image processing code given below /** * disk cache. * * @param data unique identifier item * @return bitmap if found in cache, null otherwise */ public bitmap getbitmapfromdiskcache(string data) { //begin_include(get_bitmap_from_disk_cache) final string key = hashkeyfordisk(data); bitmap bitmap = null; synchronized (mdiskcachelock) { while (mdiskcachestarting) { try { mdiskcachelock.wait(); } catch (interruptedexception e) { } } if (mdisklrucache != null) { inputstream inputstream = null; try { final disklrucache.snapshot snapshot = mdisklrucache.get(key); if (snapshot != null) { if (buildconfig.debug) {

rest - Add variable to URL in python for Hue lights -

i know can shorten down length of python api call hue using variable cant figure out format or proper term find answer in stackoverflow. learn how hide auth token practice better security , add variable multiple lights may add in future. believe need multiple variables within url. please appreciated. import requests url = "http://192.168.98.233/api/cjk7782cabrguggxutlt8dwwnk516ilhmhzhwflq/lights/{}/state".format(1) url2= "http://192.168.98.233/api/cjk7782cabrguggxutlt8dwwnk516ilhmhzhwflq/lights/{}/state".format(2) url3= "http://192.168.98.233/api/cjk7782cabrguggxutlt8dwwnk516ilhmhzhwflq/lights/{}/state".format(3) payload = " {\"on\":false}" headers = { 'content-type': "application/json", 'cache-control': "no-cache" } r = requests.put(url, data=payload, headers=headers) r2 = requests.put(url2, data=payload, headers=headers) r3 = requests.put(url3, data=payload, headers=headers) pr

php - Magento Admin Grid Field Custom filter issue -

i have created magento admin module grid , field having custom filter. $this->addcolumn('diff', array( 'header' =>'diff.', 'align' =>'left', 'type' => 'number', 'index' =>'diff', 'filter_condition_callback' => array($this, '_difffilter'), )); collection having group below: $collection->getselect()->group(array('main_table.order_id')); custom filter function below: protected function _difffilter($collection, $column) { if (!$value = $column->getfilter()->getvalue()) { return $this; } $_filter_data = $column->getfilter()->getvalue(); if($_filter_data["from"]!=''){ $collection->getselect()->having('round((main_table.base_cost-main_table.base_price)*100/main_table.base_cost) >= ?', $_filter_data["from&

iphone - iOS : Programmatically control the volume of Notification alert and sound theme -

i have requirement like, through app want set notification sound , volume. because of our requirement. there 3 different states - happy, sad , normal. when user gain points send congratulation message, when lost points send message also. promotion related other message too. these state want set different notification sound , volume too. appreciate inputs. ty for local notification func schedulenotifications(inseconds: timeinterval, completion: @escaping (_ success: bool) ->()){ ... notif.sound = unnotificationsound.init(named: "customsound.mp3") ... } for push notification aps data should have sound key in , server need send file name should play, { aps = { alert = "message"; sound = "sound file name.extension"; badge = 1; }; }

python - For Loop and Accumulator Pattern -

an old legend has wise man, when offered reward desired, requested first grandchild receive 1 coin, second grandchild receive twice many first, third receive twice many second, , on. how many coins last grandchild receive? how many coins grandchildren receive in all? function should accept number of grandchildren , return statement addressing both questions. ihave far def grandchild_coins(number_of_grand_children):# not finished coins=1 grand_child in range(number_of_grand_children): coins=coins*2 return ' grand child' + str(grand_child) + ' ' + str(coins) + ' coins' grandchild_coins(10) out[33]: ' grand child9 1024 coins' how list how coins each grand child has ? thanks guys def grandchild_coins(number_of_grand_children): # initalizes coins 1 coins=1 total_coins=[] # grand_child in range entered code ran grand_child in range(number_of_grand_children): # if grand_child number not 0 coins

c# - System.Drawing.FontFamily does not accept Uri-based Font -

is there way define external font new system.drawing.fontfamily ? tried using code: fontfamily robotolight = new fontfamily(new uri("pack://application:,,,/"), "./fonts/#roboto light"); and shows error: cannot convert system.uri string i realized i've been using different reference , 1 accepts uri system.windows.media.fontfamily , not work. i researched , saw define custom fonts use privatefontcollection.addfontfile , it's using absolute path font, answered here . my fonts resides in fonts folder inside project, , built included in .exe file, absolute path no-go me. and need use system.drawing , not system.windows.media because i'm creating customized messagebox system.drawing.fontfamily doesn't understand pack uris. please refer following question example of how use embedded font system.drawing.fontfamily class: how , embed fonts in winforms app in c#

vue.js - vuejs 2 how to watch store values from vuex -

i using vuex , vuejs 2 together. i new vuex , want watch store variable change. i want add watch function in vue component this have far: import vue 'vue'; import { my_state, } './../../mutation-types'; export default { [my_state](state, token) { state.my_state = token; }, }; i want know if there changes in my_state how watch store.my_state in vuejs component? you should not use component's watchers listen state change. recommend use getters functions , map them inside component. import { mapgetters } 'vuex' export default { computed: { ...mapgetters({ mystate: 'getmystate' }) } } in store: const getters = { getmystate: state => state.my_state } you should able listen changes made store using this.mystate in component. https://vuex.vuejs.org/en/getters.html#the-mapgetters-helper

r - Create a column with random decimal values -

just trying create column random decimal points between 0.001 , 0.009 i'm using code: data$newrow <- sample(0.001:0.009,replace=t, nrow(data)) but seems produce column 0.001. summary(data$newrow) min. 1st qu. median mean 3rd qu. max. 0.001 0.001 0.001 0.001 0.001 0.001 any ideas why? thanks!

scala - Not able to run Spark job on YARN cluster -

i have simple hadoop cluster on top of spark runs (that spark uses yarn cluster manager). i using hadoop 2.7; scala 2.112.1; spark 2.1.0 , jdk 8. now, when submit job, fails, message below: 17/04/06 23:57:55 info yarn.client: application report application_1491534363989_0004 (state: accepted) 17/04/06 23:57:56 info yarn.client: application report application_1491534363989_0004 (state: failed) 17/04/06 23:57:56 info yarn.client: client token: n/a diagnostics: application application_1491534363989_0004 failed 2 times due container appattempt_1491534363989_0004_000002 exited exitcode: 15 more detailed output, check application tracking page:http://rm100.hadoop.cluster:8088/cluster/app/application_1491534363989_0004then, click on links logs of each attempt. diagnostics: exception container-launch. container id: container_1491534363989_0004_02_000001 exit code: 15 are there issues jdk 8? update when run same program using jdk 7, working fine. question is: spark, s

javascript - Angular ng-message is not shown up when adding a ng-pattern -

Image
i added ng-pattern="/^[0-9]{1,7}$/" input field (type=number) validate numbers without 'e' letter.i using angular material.it validating , showing red color in input validation message not showing up.it shown kind of similar value '3223233e3' this happens when supply number , single e : this happens when supply many e 's: <input type="number" id="txtand" ng-model="txtand" ng-pattern="/^[0-9]{1,25}$/" name="andocc" required /> <div ng-messages="three.andocc.$error"> <div ng-message="required">please supply value</div> <div ng-message="pattern">please supply valid value</div> </div> in pen @edric, try code <div ng-messages="three.andocc.$error"> <div ng-message="required">please supply value</div> <div ng-message="number">please supp

ios - How to add different image for different cell with different text in UICollectionView programmatically? -

i want add different image different cell different textlabel in uicollectionview programmatically. tried many way show error. here code: import foundation import uikit class homecvc: uicollectionviewcontroller, uicollectionviewdelegateflowlayout { let homecellid = "homeid" override func viewdidload() { super.viewdidload() // homeobjects = homeobject.sampleobjectheadline() navigationitem.title = "home" collectionview?.backgroundcolor = .green collectionview?.register(homecell.self, forcellwithreuseidentifier: homecellid) } override func collectionview(_ collectionview: uicollectionview, numberofitemsinsection section: int) -> int { return 7 } override func collectionview(_ collectionview: uicollectionview, cellforitemat indexpath: indexpath) -> uicollectionviewcell { let cell = collectionview.dequeuereusablecell(withreuseidentifier: homecellid, for: indexpath) as

ios - Regular expression for password validation - Objective C -

i need regular expression can validate following cases, be 8 20 characters use @ least 1 upper case letter, 1 lower case letter, , 1 number not repeat same number or letter more 3 times in row not contain spaces, , may use these characters @ # * ( ) + = { } / ? ~ ; , . - _ the closest solution can find ^(?=.*[a-z])(?=.*[a-z])(?=.*\d)(?=.*[^\da-za-z])(?=.*[@(#*){+=}/?~;,._]).{8,20}$ but contains following issue, accepting space can't add - character repeating same number or letter more 3 times in row. edit: fixed repeating character issues , have final expression like, ^(?!.*?(.)\1{3})(?!.* )(?=.*[a-z])(?=.*[a-z])(?=.*\d)(?!.*[:£€&"!'[\]%^\|<>$]).{8,20}$ but working on online tester [regexr][1] tried following code generates runtime - (bool)string:(nsstring *)text matches:(nsstring *)pattern{ nserror *error; nsregularexpression *regex = [nsregularexpression regularexpressionwithpattern:pattern options:0 error:&error]; nsarr

linux - Error (Klocwork): '_M_dataplus._M_p' might be used uninitialized in this function -

'klocwork' profiller generate error ['it.second.name_._m_dataplus._m_p' might used uninitialized in function.] in following code section. class test { public: test() { } test(std::string str) { name = str; cout <<"test::test object: " <<name <<endl; } ~test() { cout <<"test::~test object: " <<name <<endl; } string getname() { return name; } private: string name; }; class maphandler { private: map<int, test> mymap; public: void mapfiller(); void mapdisplay(); }; void maphandler::mapfiller() {

java - Getting ArrayIndexOutOfBoundsException on Sorting list taken from SharedInstance in Android -

i have list stored in sharedinstance, want sort based upon time parameter. code sorting collections.sort(sharedinstance.getinstance().getmasterlistfavfeeds().getposts(), new datecomparator()); public class datecomparator implements comparator { dateformat dateformat = new simpledateformat("yyyy-mm-dd't'hh:mm:ss"); @override public int compare(object date1, object date2) { try { return dateformat.parse(date2.tostring()).compareto(dateformat.parse(date1.tostring())); } catch (parseexception e) { throw new illegalargumentexception(e); } } } crash log java.lang.arrayindexoutofboundsexception: length=1459; index=1459 @ java.util.collections.sort(collections.java:1888) @ com.fnshealth_android.utils.updatecomments.updatecommentcounttosharedinstancelist(updatecomments.java:34) @ com.fnshealth_android.utils.notificationmanager.processnewcommentfeed(notificationmanager.java:135) @ com.fnshealth_android.utils.not

android - Tabs, Material Design and Support Library -

goal: implement tabs. conditions: use only api21+ (lolipop+) components. use material design. noticed @ current state android has: tabhost , tabwidget (going deprecated). actiobar.addtab (going deprecated). tablayout (belongs design support library , requires appcompat theme ) so how developers supposed implement tabs on android 5.0+ (api21+, lolipop+) applications? using deprecated stuff rejected. using tablayout leads appcompat usage. android material usage docs: https://developer.android.com/training/material/index.html i haven't found single document describing how tabs should implemented, except appcompatactivity or android.support.design.widget.tablayout . i mean, looks nonsense: android releases material design. developers cannot use material design directly, because there no components (e.g. tabs) in api21+, , forced use theme.appcompat stuff instead. appcompat created ease need of having maintain different components /

Red updating text in VID using reactive method -

red [needs: 'view] num: ["1^/"] k: num/1 view [ size 600x600 txt: text 30x50 k ar: area 300x400 "" focus on-change[ txt/size: ar/size len: length? split face/text newline either (len - face/data) > 0 [ append num append form (len + 1) newline face/data: len ][ remove tail num face/data: face/data - 1 ] txt/text: form num ] [ar/data: 0] ] this red program contains "text face" , "area face". text face contains vertical list of serial numbers. when newline added in area face, serial number increase per number of lines. , when line removed in area face, serial number decrease well. this using non-reactive method. there reactive approach it? i believe we're looking react function. reactive framework introduced in this blog post , there similar example of converting example using o

ubuntu 16.04 - mails are not forwarded to external email accounts -

i'm new using postfix. tried installing postfix mta ubuntu server. main.cf looks below: smtpd_banner = $myhostname esmtp $mail_name (ubuntu) biff = no append_dot_mydomain = no readme_directory = no smtpd_tls_cert_file = /etc/ssl/certs/smtpd.crt smtpd_tls_key_file = /etc/ssl/private/smtpd.key smtpd_use_tls=yes smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination myhostname = ubuntu alias_maps = hash:/etc/aliases alias_database = hash:/etc/aliases mydestination = $myhostname, ubuntu, localhost.localdomain, , localhost relayhost = mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 mailbox_size_limit = 0 recipient_delimiter = + inet_interfaces = inet_protocols = myorigin = home_mailbox = maildir/ mailbox_command = smtpd_sasl_local_domain = smtpd_sasl_auth_enable = yes smtpd_sasl_security_

ngrx - Angular 2 Set Default Form Control Value Presentation Component -

i bit lost here. have angular 2 app built store architecture (ngrx) , using smart , presentation components. everything working in relation store , retrieving data, stuck when comes setting default form control value in presentation component. keeps failing compile because property not exist, timing issue property not there when first tries load form. so how set default value or initial value in form control after @input() customer value available. presentation component import { component, oninit, input, output, eventemitter, changedetectionstrategy} '@angular/core'; import { formbuilder, formgroup, formarray, validators, formcontrol } "@angular/forms"; // mojito models import { customermodel } '../../models/customer-model'; @component({ selector: 'mj-customer-detail', templateurl: './customer-detail.component.html', styleurls: ['./customer-detail.component.scss'], changedetection: changedetectionstrategy.on

android - How to show tabs on whole application on bottom of screen -

hy, working on android application.i have more hundred activities.i using custom tab bars , showing single activity on each tab. but want show 4 basic tabs below activities , tabs should visible whole application. how it. me please use <include include layout file containing this. <include layout="@layout/your_custom_bottom_layout" /> your_custom_bottom_layout file contains android.support.design.widget.bottomnavigationview put java related code in kind of baseactivity , extend activity of activity. so, contain common code across whole app.

Is it necessary to re-analyze an elasticsearch copy_to if the original content has been analyzed? -

we have elasticsearch mapping using copy_to (custom _all). used queries , not stored. analyze original file_content_de using "analyzer": "german". need analyze copy_to, es documentation not clear this? es documentation: https://www.elastic.co/guide/en/elasticsearch/guide/2.x/custom-all.html "attachment_contents_de": { "type": "string" }, ... "file_content_de": { "type": "string", "analyzer": "german", "copy_to": "attachment_contents_de", "include_in_all": false, "store":true }, ... yes have analyze copied field seperately official documentations mentions. and doesn't mean re-analyze, copy_to copies string values field, field in should have own definition along analyzers defined mappings of first_name , last_name fields have no bearing on how full_nam

Insert value from textbox into 2 different table ms-access -

i have 2 types of table in database. project , services table. both table have projectno , address field. have created 3 form, 1 project department (view only), 1 services department (view only) , form combination of first form , second form , use data entry form sale department. so, in data entry form there 2 projectno , address textbox in form because 1 project table , 1 services table. there suggestion on how can fill both table field single textbox value? table structure. project - projectno; order; engineer; address; services-projectno; warranty; warrantyend; address; short answer yes. can use vba code update field in second table after updating textbox in 1 of forms. key question why have address field in both tables if going same time. what relationship between project , services? services going have same address projects? services going shared multiple projects? the solution may delete address 1 of tables or make service form subform of project form

ruby on rails - Rspec + Capybara + Rack::Test — disable cookies -

how turn off cookies in feature test rack::test ? there no built-in way disable cookies when using rack::test. can clear them during test with page.driver.browser.clear_cookies which may provide functionality need. if not, can install middleware during test runs , enable/disable stripping of cookies on every request. can see example of @ https://makandracards.com/makandra/15187-how-to-disable-cookies-in-cucumber-tests . example cucumber should easy enough convert plain rspec.

ios - How to make viewcontroller to show as bottom page in ios10 swift3? -

Image
i have 1 view controller button, if click on button should display bottom view controller (like bottom page in android): i have these 2 demo view controllers, if click on button second view controller should display details view , should popup bottom of first view controller. thank you. for achieving should add second view controller child view controller , animate bottom. adding child: let secondviewcontrollerinstance = secondviewcontroller() // or storyboard instantiate method self.addchildviewcontroller(secondviewcontrollerinstance) let initialrect = cgrect(x: 0, y: screen_height-200, width: screen_width, height: 200) secondviewcontrollerinstance.view.frame = rect secondviewcontrollerinstance.view.center.y += 100 self.view.addsubview(secondviewcontrollerinstance.view) secondviewcontrollerinstance.didmove(toparentviewcontroller: self) //animate center y uiview.animate(withduration: 0.3) {

unit testing - Use the same log4j.properties for tests in a multi module Maven project -

i have multi-module, lot of modules, maven project. each module has it's own set of unit-tests. want use same log4j.properties file tests. have copy , paste same file in each module's /src/test/resources or there smartest way? i'm looking smartest way no luck now. i think there couple of possible ways: add directory log4j.properties classpath used when running unit tests add directory log4j.properties additional resources directory, files directory copied target/classes directory every module

How can i use hover effect on after element with css? -

this question has answer here: how write :hover condition a:before , a:after? 6 answers this code, want show hover effect on after element. #car:after:hover{background:red:} but not working. check out demo below. think missing content property. the red div created using :after , changes color on hover. the selector:after:hover won't work. .car { position: relative; width: 100px; height: 100px; background: yellow; } .car:hover { background: skyblue; } .car:after { content: ''; width: 50px; height: 50px; position: absolute; right: 0; bottom: 0; background: green; } .car:hover:after { background: red; } <div class="car"></div>

javascript - how to attach on to the `onclick` event of the link? (autocomplete) -

do autocomple. need in dropdown prompts make links. i use plugin . $(function () { $('input[name="oem"]').autocomplete({ minchars: 4, source: function (term, response) { term = term.tolowercase(); $.getjson('/search.json?oem=' + term, function (data) { var matches = []; (i = 0; < data.length; i++) if (~data[i].tolowercase().indexof(term)) matches.push(data[i]); response(matches.slice(0, 11)); }); }, renderitem: function (item, search) { search = search.replace(/[-\/\\^$*+?.()|[\]{}]/g); var re = new regexp("(" + search.split(' ').join('|') + ")"); return '<div class="autocomplete-suggestion" data-val="' + item + '"><a href="#" onclick="javascript:document.locatio

ios - Synchronization of multiple tasks on single thread -

how can prevent block of code repeatedly accessed same thread? suppose, have next code: func sendanalytics() { // synchronous work asynctask() { _ in completion() } } i want prevent any thread accessing "// synchronous work", before completion called. objc_sync_enter(self) objc_sync_exit(self) seem prevent accessing code multiple threads , don't save me accessing code single thread. there way correctly, without using custom solutions? my repeatedly accessing, mean calling sendanalytics 1 thread multiple times. suppose, have for, this: for in 0...10 { sendanalytics() } every next call won't waiting completion inside sendanalytics called (obvious). there way make next calls wait, before completion fires? or whole way of thinking wrong , have solve problem higher, @ body? you can use dispatchsemaphore ensure 1 call completes before next can start let semaphore = dispatchsemaphore(value:1) func sendanalytics() {

merge 2 array into new array after matching their content javascript -

i have 2 arrays, , want new array based upon condition content of these 2 arrays matched arr1 = [{ package_id: 'aabbccdd', level: 2 }, { package_id: 'xycd21', level: 3 } ] arr2 = [{ package_id: 'aabbccdd', level: 1 }, { package_id: 'zcb21', level: 5 }] mergedarray = [{ package_id: 'aabbccdd', arr1level: 2, arr2level: 1 }, { package_id: 'xycd21', arr1level: 3, arr2level: 0 }, { package_id: 'zcb21', arr1level: 0, arr2level: 5 }] so if package_id checked in both arrays. , if found in either array, new array pushed 1 element level both array mentioned against package_id. i not figure out logic that. if can done lodash kindly tell me. you can solve using loops did here: var arr1 = [{ package_id: 'aabbccdd', level: 2 }, { package_id: 'xycd21', level: 3 } ]; var arr2 = [{

Spring 4 Ehcache 3 Hibernate 5 cache default template setup -

my project on spring 4.3.4, hibernate 5.2.4 , ehcache 3.3 i looking solution singular jsr-107 (jcache) cachemanager whole application provide: spring caching - number of explicitly named caches; hibernate l2 caching - ability implicitly generate number of regions (which in fact caches too) the main concern here hibernate. in fact, question of setting default template regions. after review of lot of topics have not discovered suitable solution. so, if exists, i'm kindly ask experts point it. programmatic way of configuring highly appreciated (ehcache.xml unwanted). added: (in answer @anthony dahanne): have seen solution in project pointing before posted topic. more, project starting point of investigation week ago. but solution involving explicit declaration of several named cache regions not spring, hibernate, can find in cacheconfiguration#createcacheconfigurations method. this inconvinient in real project wich contains 100500 different entities, natural

java - Google Url shortner giving error for url with Ip -

i using google url shorten api. shorten url " http://demos.companyname.com:1339/ " but when replace url " http://demos.companyname.com:1339/ " " http://36.186.69.8:1339/ " returns error. how solve problem? my url shorten code is: public jsonobject getjsonfromurl(string address,string longurl) { // making http request try { // defaulthttpclient defaulthttpclient httpclient = new defaulthttpclient(); httppost httppost = new httppost(address); httppost.setentity(new stringentity("{\"longurl\":\""+ longurl+"\"}")); httppost.setheader("content-type", "application/json"); httpresponse httpresponse = httpclient.execute(httppost); httpentity httpentity = httpresponse.getentity(); = httpentity.getcontent(); } catch (ioexception e) { e.printstacktrace(); } try { bufferedreader reader = new b

javascript - How do I manipulate with Google Forms on Form View, client side -

this code works fine if run when form editor opened: var ui = formapp.getui(); var response = ui.prompt('getting know you', 'may know name?', ui.buttonset.yes_no); // process user's response. if (response.getselectedbutton() == ui.button.yes) { logger.log('the user\'s name %s.', response.getresponsetext()); } else if (response.getselectedbutton() == ui.button.no) { logger.log('the user didn\'t want provide name.'); } else { logger.log('the user clicked close button in dialog\'s title bar.'); } but not work on form view, when filling it, dont understand why google made work way, benefit of me seeing dialog box , not 1 filling it... also, possible can response before form being submited can validate field using javascript function? alternatively how can achieve such things on google forms apps script? google apps script runs on google form editor, not on

node.js - how run express js project on secure shell? -

1.please explain how create secure shell in express project? var express = require('express'); var app = express(); var pg = require('pg'); app.listen(7207); var bodyparser = require('body-parser'); app.set('view engine', 'ejs'); app.use('/asset/css', express.static('asset/css')); var urlencodedparser = bodyparser.urlencoded({ extended:false }); app.get('/', function (req, res) { res.render('home'); }); console.log("server running on 7207 port........(192.168.1.29:7207)"); you can't create secure shell via node application. can run application in secure shell (ssh) following steps. 1) take terminal emulator , ssh machine command ssh user@ip_address 2) run application node_env="myenv" node myapp.js you may create screen before running application application running if disconnect ssh session. screen -s myscreen create new screen.

Uber API returns 404 no_partner_for_user with valid token -

i have valid oauth token retrieved uber api driver account. when hit endpoint: curl -i -h "authorization: bearer xxxxx" https://api.uber.com/v1/partners/me i'm returned with: {"meta":{},"errors":[{"status":404,"code":"no_partner_for_user","title":"the user not have partner account."}]} my colleague can hit same endpoint valid token same driver , receives account data. edit just confirming account we've authed absolutely definitively driver account. the user not have partner account, looks rider authed , token using.

scala - "Immortal" Spark Streaming Job? -

all right, i've asked similar question related how spark handles exceptions internally, example had wasn't clear or complete. answer there pointed me in direction can't explain things. i've setup dummy spark streaming app , in transform stage have russian-roulette expression, might or not throw exception. if exception thrown, stop spark streaming context. that's it, no other logic, no rdd transformation. object immortalstreamingjob extends app { val conf = new sparkconf().setappname("fun-spark").setmaster("local[*]") val ssc = new streamingcontext(conf, seconds(1)) val elems = (1 1000).grouped(10) .map(seq => ssc.sparkcontext.parallelize(seq)) .toseq val stream = ssc.queuestream(mutable.queue[rdd[int]](elems: _*)) val transformed = stream.transform { rdd => try { if (random.nextint(6) == 5) throw new runtimeexception("boom") else println("lucky bastard") rdd } catc

openCV module version with python 2.66 -

i'm trying use cv2 module on centos 6.8 system running python 2.6.6 repository installed module gives me "cv" does know if cv2 module available on python 2.66? i'd rather not have upgrade python 2.7, since risks sorts of os problems if wrong!

excel - vba select/remove all sheets except first -

i had problem removing unnecessary sheets. looked @ different forums , mashed different solutions. macro removes sheets (except first sheet). sub wrong() dim sht object application.displayalerts = false each sht in activeworkbook.sheets if sht.index <> 1 sht.delete end if next end sub is solution ok or can improved? tried actions directly on objects (workbooks, worksheets), failed each time your code work (but have discovered yourself!) you avoid if-then-end if looping through sheets index directly last 1 2nd one, follows option explicit sub wrong() dim long application.displayalerts = false sheets '<--| reference active workbook 'sheets' collection = .count 2 step -1 '<--| loop through referenced sheets index last 2nd .item(i).delete '<--| delete current index sheet next end application.displayalerts = true end sub

java - Implementing Virtual Keyboard Android to PC -

i'm attempting use android phone keyboard pc. done on local wifi connection using sockets create client/server connection. i'm using textwatcher pick change in characters in edittext , sending on server uses robot class write onto pc. using softkeyboard on android phone. issue when writing in edittext 1 character gets sent. , picked server. e.g. type on android phone "a" , respective keypress simulated on server. if type character not read character if delete "a" , type character send character. below client side of code, android application. public class mainactivity extends appcompatactivity implements view.onkeylistener { private final static int portnumber = ****; private final static string hostname = "192.168.0.8"; private final static string ctest = "connection test"; socket socket = null; private static string tag = "test"; @override protected void oncreate(bundle savedinstancestate) { super.oncre

optimization - Truth table with 5 inputs and 3 outputs -

i have make truth table 5 inputs , 3 outputs, this: a b c d e red green blue 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 1 0 0 0 1 . . . . 1 1 0 1 0 0 1 1 . . . 1 1 1 1 1 1 0 1 etc. (in total 32 rows, numbers in rgb table represents number of 1's in each row in binary i.e in row 1 1 0 1 0 there 3 1's, 3 in binary 0 1 1). i present result of in atanua ( http://sol.gfxile.net/atanua/index.html ) tool (so fore example when press button e, blue light shine, when pressing b d green , blue light shine , on). there requirement can use and, or, not operands, , each operand can have 2 inputs. although i'm using karnaugh map minimize it, still many records results each output long (especially last one). i tried simplify more adding of 3 output boolean functions one, , minimization process ended pretty well: a + b + c + d it seems work fine (but there 1 output light, works in red green blue column separately). concern fact

python - How to view shell on pi after auto startup -

i new linux, python , pi. however, have managed write python program reads temperature sensor , displays it, updating every 10 minuites. if run program python editor (hitting f5 run), opens python shell , can see output program. however, program run when pi boots , still display temperture in shell. i put .py file in launcher.sh in /home/pi program run when pi boots (i can tell program flashes led show running) not shell , cannot see temperture being displayed. can tell me, please, how can start program when pi boots make open shell can see output. many thanks, peter

python - Why does using "and" between two lists give me the second list (as opposed to an error)? -

this question has answer here: python , operator on 2 boolean lists - how? 6 answers i encountered bug in code. (incorrect) line similar to: [x x in range(3, 6) , range(0, 10)] print x [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] (the correct way of writing statement not part of question) wondering somelist , someotherlist does, experimented. seems ever set result last parameter passed: x = range(0,3) # [0, 1, 2] y = range(3, 10) # [3, 4, 5, 6, 7, 8, 9] z = range(4, 8) # [4, 5, 6, 7] print x , y # [3, 4, 5, 6, 7, 8, 9] print y , x # [0, 1, 2] print z , y , x # [0, 1, 2] i assume unintentional consequence of being able write is useful, i'm not seeing how semantics of "and" operator being applied here. from experience, python won't apply operators things don't support operators (i.e. spits out typeerror), i'd expect error an

javascript - how to repeat the left menubar in each html page -

var navigation = new array(); // navigation. // ==================== navigation ==================== // navigation[0] = '<div id="menu">'; navigation[1] = '<ul>'; navigation[2] = '<li><a href="../about_us.htm">aboutus</a></li>'; navigation[3] = '</ul>'; navigation[4] = '</div><!-- close tab navigation -->'; function show(i) { (x in i) { document.write(i[x] + '\n') } } i have created above function in javascript menubar need call menubar in html file. i recommend use document.createelement instead of using document write, , array of string. secondly recommend initialize arrays using [] literal instead of using array construct. this: var arr = [1,2,3]; //like var arr2 = new array(1,2,3,4); // not recommended the code below should work want do. var navigation = document.createelement('div'); navigation.id = 'm

javascript - How to clear dataTable body after button click -

i have datatable data coming backend. data coming based on fromdate todate , in table can sort data.but when there no data between fromdate todate displaying "no data found in table" when click on sorting icon on head of table because table not refreshing itself. var inittable = function() { var finance = $('#financetbl'); var ofinance = finance.datatable({ // internationalisation. more info refer http://datatables.net/manual/i18n "language": { "aria": { "sortascending": ": activate sort column ascending", "sortdescending": ": activate sort column descending" }, "emptytable": "no data available in table", "zerorecords": "no matching records found" },