id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_3600
doc_3601
First I put the video.js and video-js.css in client/compatibility folder so it will load first Then in my client side html I write the following simple code,, It is not working <video id="example_video_1" class="video-js vjs-default-skin vjs-big-play-centered" controls width="640" height="264" poster="{{video.thumbs}}" data-setup='{"controls": true, "autoplay": true,"techOrder":["flash", "html5"],preload="auto"}'> <source type='video/flv' src="{{uurl}}" /> </video> There are no issues with the template helpers they are working fine but The problem is with the video.js player , It is not loading. Anyone tried this before? Struck here, Any help appreciated UPDATE: dynamic loading solution working fine for me but when I click on a video it redirects to /video/:_id/:_slug page with subscribing to single video but when I go back to the home page and again click on another video, this time video player is not initializing again Code when onclick on video: 'click .videothumb > a':function(e,t){ Session.set("url",e.currentTarget.getAttribute("data-url")); var url=e.currentTarget.getAttribute("data-url"); var title=e.currentTarget.getAttribute("data-title"); var cid=e.currentTarget.getAttribute("data-id"); Meteor.call("videoData",url,function(er,da){ console.log(cid); Session.set('vurl',da); Router.go("video",{_id:cid,slug:title}); }); } routing this.route("video",{ path:'/video/:_id/:slug', waitOn: function() { // return Meteor.subscribe('singleVideo', this.params._id); }, onBeforeAction: function () { }, data:function(){ Session.set("currentVideoId",this.params._id); var video; video= Videos.findOne({_id: this.params._id}); return { video:video }; } }); rendered function: Template.video.rendered=function(){ var id=Session.get("currentVideoId"); Meteor.call("incViews",id,function(e,d){ console.log("view added"); }); videojs("videoId",{"controls": true, "autoplay": false,"techOrder":["html5","flash"],preload:"auto"},function(){ // Player (this) is initialized and ready. **console.log("videojs initialized");** console.log(this) ; } ); }; that console "videojs initialized" is loging when only first when I route the video page from next routing(when I click video thumbnail on homepage)The log functions is not loggind(means player is not initializing) Any suggestions to make it work better A: In the time videojs script is initialized there is no template rendered, you need to manually initialize videojs player. tpl1.html: <template name="tpl1"> <video id="example_video_1" class="video-js vjs-default-skin vjs-big-play-centered" controls width="640" height="264" poster="{{video.thumbs}}"> <source type='video/flv' src="{{uurl}}" /> </video> </template> tpl1.js: Template.tpl1.rendered = function(){ videojs( "example_video_1", {"controls": true, "autoplay": true,"techOrder":["flash", "html5"],preload="auto"}, function(){ // Player (this) is initialized and ready. } ); }) Please read documentation of Video.js: "Alternative Setup for Dynamically Loaded HTML" A: I implemented it in my project w/o using Blaze but using a lower-level Tracker dependencies. When the Template is rendered, I would dynamically start the player and then have a reactive data-source of the current position that I can control: https://github.com/Slava/talk-player/blob/master/client/player.js A: This worked for me on Meteor 1.6.1.1. template html <template name="tebVideo"> <video class="video-js"> <source src="{{src}}" type="video/mp4"> </video> </template> template js import { Meteor } from 'meteor/meteor'; import { Template } from 'meteor/templating'; import 'video.js/dist/video-js.css'; import videojs from 'video.js'; import './video.html'; // prevent analytics window.HELP_IMPROVE_VIDEOJS = false; // helper for local dev vs product cdn const envUrl = (localPath, fileName) => { if (Meteor.isProduction) { return Meteor.settings.public.host.cdnUrl+'/'+fileName; } else { return localPath+fileName; } }; Template.tebVideo.onRendered(() => { const instance = Template.instance(); const video = videojs(document.querySelector('.video-js'), { controls: true, autoplay: false, preload: 'auto', width: 854, height: 480, aspectRatio: "16:9", poster: envUrl('/images/', instance.data.poster), function() { Log.log(['debug', 'video'], 'Video loaded ok'); } } ); }); Template.tebVideo.helpers({ src() { const instance = Template.instance(); return envUrl('/videos/', instance.data.src); } }); show it {{>tebVideo poster="three_robots.png" src="how-knowledge-automation-works.mp4"}}
doc_3602
A: It depends on whether the content of the iframe is within the same domain as the main page. If they are on the same domain then you could add some JavaScript to the iframe content page to pass the height of the content back to the main page. If they are on different domains then browser security prohibits the two pages from communicating via JavaScript.
doc_3603
Surfaces are exchanged based on the Model state: @Composable private fun AppContent() { val scrollerPosition = ScrollerPosition() Crossfade(State.currentScreen) { screen -> Surface(color = MaterialTheme.colors.background) { when (screen) { is Screen.List -> ListScreen(scrollerPosition) is Screen.Details -> DetailsScreen(screen.transaction) is Screen.New -> NewScreen() } } } } ListScreen used to have a VerticalScroller and I was giving it a ScrollerPosition to retain the position after screen changes. However, this solution does not work with AdapterList. This is how it used to be: @Composable private fun TransactionsList(modifier: Modifier, scrollerPosition: ScrollerPosition) { Box(modifier = modifier.fillMaxSize().wrapContentSize(Alignment.Center)) { VerticalScroller(scrollerPosition = scrollerPosition) { AdapterList(State.transactions, itemCallback = { transaction -> TransactionListRow(transaction) ListDivider() }) } } } How can I make AdapterList retain the scroll position? @Composable private fun TransactionsList(modifier: Modifier, scrollerPosition: ScrollerPosition) { Box(modifier = modifier.fillMaxSize().wrapContentSize(Alignment.Center)) { AdapterList(State.transactions, itemCallback = { transaction -> TransactionListRow(transaction) ListDivider() }) } } A: rememberScrollState()? I think it can be extracted as a value or maybe the lerp() function can be used, by making it a custom Composable instead using Layout() Why not use lazycolumn instead? A: With Jetpack Compose 1.0 scroll position retention has became possible using rememberLazyListState(). To retain the state, initialize the state variable somewhere high enough in the tree, for example, above the navigation. Then pass it to the LazyColumn. Here is an example with a Crossfade which retains the scroll position in the list when switching between list and details: val listState = rememberLazyListState() Crossfade(screen) { scr -> Surface(color = colors.background) { when (scr) { is Screen.List -> LazyColumn(state = listState) { items(items) { item -> // here come the items } } is Screen.Details -> DetailsScreen() } } } The size of items must stay the same in order for this to work.
doc_3604
import numpy as np x = np.random.uniform(low=0, high=10, size=1) attempt = 1 while(x < 8): attempt = attempt + 1 x = np.random.uniform(low=0, high=10, size=1) However, now I want to get the number of attempts before x was greater than 8 for the fourth time. To do this, I placed the for loop just before the while loop which becomes like this: for i in range(0,4): while(x < 8): attempt = attempt + 1 x = np.random.uniform(low=0, high=10, size=1) However, this is not working as I intended it to be. Can someone help me solve this problem? A: You want to get the total number of attempts needed to obtain a random number 8 in 4 consecutive trails. Try this: >>> import numpy as np >>> def fun(): ... x = np.random.uniform(0,10,1) ... attempt = 1 ... while x<8: ... attempt += 1 ... x = np.random.uniform(0,10,1) ... return attempt >>> for i in range(0,4): ... print("Trial" , i , "took" , fun(), "Attempts") Output: Trial 0 took 1 Attempts Trial 1 took 1 Attempts Trial 2 took 8 Attempts Trial 3 took 3 Attempts A: The problem is that you're not resetting your x value. So once the variable is set to a value greater than 8, you code will not enter the while loop again. You need to set x = 0 before the while loop. A: You should modify your code to for i in range(0,4): x = np.random.uniform(low=0, high=10, size=1) while(x < 8): attempt = attempt + 1 x = np.random.uniform(low=0, high=10, size=1) This would reset x before it enters into the while loop. Without this statement, your the control enters into the while loop only once. A: There are many ways of doing this. The below should work... import numpy as np successes = 0 rolls = 0 while (successes < 4): x = np.random.uniform(low=0, high=10, size=1) rolls += 1 if x > 8: successes += 1 print(rolls) A: This is not a for loop case. Try this: while x < 8 and i <= 4: x = np.random.uniform(low=0, high=10, size=1) if x>8: i+=1 x=np.random.uniform(low=0, high=10, size=1) attempt = 1 print(attempt, x) attempt = attempt + 1
doc_3605
cannot instantiate the type objectfactory This compilation error is thrown at the following line: objectFactory = new ObjectFactory();//throws error: "Cannot instantiate the type ObjectFactory" The complete code for the calling class is as follows: package maintest; import java.io.File; import javax.naming.spi.ObjectFactory; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; public class Main { private static JAXBContext context; private static ObjectFactory objectFactory; public static void main(String[] args) { try {setUp();} catch (Exception e) {e.printStackTrace();} unmarshal(); } protected static void setUp() throws Exception { context = JAXBContext.newInstance("generated"); objectFactory = new ObjectFactory();//throws error: "Cannot instantiate the type ObjectFactory" } public static <PurchaseOrderType> void unmarshal(){ Unmarshaller unmarshaller; try { unmarshaller = context.createUnmarshaller(); final Object object = unmarshaller.unmarshal(new File("src/test/samples/po.xml")); } catch (JAXBException e) {e.printStackTrace();} } } How can I resolve this error? A: My guess is that you imported the wrong ObjectFactory. You probably wanted the one generated by xjc (JAXB related) not the one from javax.naming.spi (service provider interface of JNDI). Edit javax.xml.bind.JAXBException: "generated" doesnt contain ObjectFactory.class or jaxb.index Make sure the "generated" package contains either a ObjectFactory (the one with the @XmlRegistry annotation, not a javax.naming.spi.ObjectFactory implementation) or a jaxb.index file. You probably can remove javax.naming.spi.ObjectFactory from your code, unless you're implementing a JNDI implementation yourself. A: Try the following import javax.naming.spi.ObjectFactory; import javax.naming.Context; import javax.naming.Name; import java.util.Hashtable; ObjectFactory objFactory = new ObjectFactory() { @Override public Object getObjectInstance(Object o, Name name, Context cntxt, Hashtable<?, ?> hshtbl) throws Exception { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } };
doc_3606
A: I assume that you are new to programming and you have not yet worked with persistence of any context. In this case, for your simple example, the Java Properties class might be a good entry point into the field of file persistence. In general, there are plenty of ways to persist data: databases, files, web storage, etc... It depends on your application and what you want to do with the data. For an example of the Java Properties file see for example this tutorial: http://www.mkyong.com/java/java-properties-file-examples/ A: Well without seeing any of the code, it is hard to tell you exactly how you should approach this, but in general you will need some method of persistence to save this type of information, ie. a database, flat file, etc. Try looking into sqlite or even XML for storage and retrieval.
doc_3607
In Addition I've got a secound dataframe (df2) like a timeseries but converted to df. I now want to take every measurement of df2 and classify it between two columns of df1. df1 Looks like this basically: km X0.5MNQ MNQ X0.5MQ a X0.75MQ b MQ c X2MQ X3MQ d 1 1 106.64 107.18 107.53 107.79 108.02 108.23 108.44 109.16 109.79 110.87 111.61 2 2 106.64 107.18 107.53 107.79 108.02 108.23 108.44 109.16 109.79 110.87 111.61 3 3 106.63 107.18 107.53 107.78 108.01 108.23 108.43 109.15 109.78 110.86 111.60 4 4 106.63 107.17 107.52 107.77 108.00 108.21 108.41 109.13 109.76 110.83 111.57 5 5 106.63 107.17 107.51 107.76 107.99 108.20 108.41 109.12 109.74 110.81 111.55 df2 Looks like this: Date Pegelstand MKZ Pegel Pegelkm MKZkm 1 1960-01-01 109.696 50491952 Pirna 2 4 2 1960-01-02 109.596 50491952 Pirna 2 4 3 1960-01-03 109.616 50491952 Pirna 2 4 4 1960-01-04 109.596 50491952 Pirna 2 4 5 1960-01-05 109.606 50491952 Pirna 2 4 6 1960-01-06 109.756 50491952 Pirna 2 4 7 1960-01-07 109.846 50491952 Pirna 2 4 I started with some code but I'm missing something so I can not go on with it. workspace`<-... files<-list.files(workspace,"csv", recursive = T) data<-list() for (i in 1:length(files)){ data[[i]]<-read.csv(paste(workspace,files[i],sep="/"), header = T, sep = ",") data[[i]]$Date<-as.Date(data[[i]]$Date) names(data[[i]])<-c("Date", "Pegelstand", "MKZ", "Pegel", "Pegelkm", "MKZkm") } #Zuordnung der Elbekilometer for (i in 1:length(files)){ ganglinie<-length(data[[i]]$Pegelstand) pegelkm<-mean(data[[i]]$Pegelkm) zeile_pegelkm<-which(fix$km==pegelkm) #Zeile in Fixierung mit Pegelwerten for (j in 1:ganglinie) { } } In the first loop i define a list (data[[i]]) with all of my df2 timeseries but converted to dataframe format. Further I search for the row ind df1 which fits to my df2$Pegelkm (df1$km = df2$pegelkm). Thats the reference row on which I want to find my two columns where measurement after measurement from df2 fits in. This shall happen in step 2. therefore I need a secound loop I guess. When I know where my measurement fits in, I have to interpolate it depending on the values of the chosen columns from loop 2 in row df1$km = df2$MKZkm. My main problem is to find the columns where the value fits in. Is there any simple solution? A: I suppose you have no problems in selecting a matching row in df1? Then, you can only fill a simple list or array with all column-values for this row. As next step you can check boundaries (first and last entry in this list) and search for nearest entry. But I'm not sure, how you like to interpolate?! I interpret your values as y-values and miss the corresponding x-values.
doc_3608
I am also creating an XML file with all the URL's in it for particular clientId as shown below. For example: Below will create 12345_abc.xml XML file with all the URL's in them in particular format. func main() { // this "clientId" will be configurable in future clientId := 12345 timeout := time.Duration(1000) * time.Millisecond ctx, _ := context.WithTimeout(context.Background(), timeout) conn, err := grpc.DialContext(ctx, "localhost:50005", grpc.WithInsecure()) if err != nil { log.Fatalf("can not connect with server %v", err) } // create stream client := pb.NewCustomerServiceClient(conn) req := &pb.Request{ClientId: clientId} stream, err := client.FetchResponse(context.Background(), req) if err != nil { log.Fatalf("open stream error %v", err) } // create new object to populate all URL data in memory urlHolder := NewClient() t := time.Unix(0, 0).UTC() done := make(chan bool) go func() { for { resp, err := stream.Recv() if err == io.EOF { done <- true return } if err != nil { log.Fatalf("can not receive %v", err) } log.Printf("Resp received: %s", resp.GetCustomerUrl()) // populate URL object with all the required field in it urlHolder.Add(&URL{ Loc: resp.GetCustomerUrl(), LastMod: &t, ChangeFreq: Daily, Priority: 10.2, }) } }() <-done log.Printf("finished") // create an XML file with all the URL's in it and then save it on disk // for particular clientId. This will create "12345_abc.xml" file, _ := os.Create(fmt.Sprintf("%d_abc.xml", clientId)) urlHolder.WriteTo(file) } Here is my urlholder.go file: type URL struct { Loc string `xml:"loc"` LastMod *time.Time `xml:"lastmod"` ChangeFreq ChangeFreq `xml:"changefreq"` Priority float32 `xml:"priority"` } type UrlMap struct { XMLName xml.Name `xml:"urlset"` Xmlns string `xml:"xmlns,attr"` URLs []*URL `xml:"url"` Minify bool `xml:"-"` } func NewClient() *UrlMap { return &UrlMap{ Xmlns: "http://www.sitemaps.org/schemas/sitemap/0.9", URLs: make([]*URL, 0), } } func (s *UrlMap) Add(u *URL) { s.URLs = append(s.URLs, u) } // WriteTo writes XML encoded urlMap to given io.Writer. func (s *UrlMap) WriteTo(w io.Writer) (n int64, err error) { cw := NewCounterWriter(w) _, err = cw.Write([]byte(xml.Header)) if err != nil { return cw.Count(), err } en := xml.NewEncoder(cw) if !s.Minify { en.Indent("", " ") } err = en.Encode(s) cw.Write([]byte{'\n'}) return cw.Count(), err } Here is my CounterWriter class - // CounterWriter implements io.Writer. Count of bytes written is tracked. type CounterWriter struct { writer io.Writer count int64 } var _ io.Writer = (*CounterWriter)(nil) // NewCounterWriter wraps io.Writer and returns CounterWriter. func NewCounterWriter(w io.Writer) (cw *CounterWriter) { return &CounterWriter{ writer: w, } } // Write calls Write on the wrapped io.Writer and adds the number of bytes // written to the counter. func (cw *CounterWriter) Write(p []byte) (n int, err error) { n, err = cw.writer.Write(p) cw.count = cw.count + int64(n) return n, err } // Count returns the number of bytes written to the Writer. func (cw *CounterWriter) Count() (n int64) { return cw.count } Problem Statement Above code works fine but I need to split an XML file into multiple XML files for same clientId if it matches below requirements: * *A single XML file should not be more than 50MB max. It can be approximate, doesn't have to be accurate. *A single XML file should not have more than 50K URL's max. I know it's weird that 50k URL limit will be reached sooner than 50MB limit but this is what I got the requirement. Now basis on above logic, I need to make multiple XML files for particular clientId. All those multiple files can be like this 12345_abc_1.xml, 12345_abc_2.xml or any other better naming format. I am kinda confuse on how should I proceed to do this. I can add logic for 50K url by using for loop but confuse on the size logic and also I want to make this generic for each clientId so I am having difficulties doing this. A: Inside your WriteTo function, you should be calling something like w.Write(myBytes). The size of myBytes inside that function is the size that you are looking for. You can get it using len(myBytes) or with the first return of w.Write(myBytes). This is important because there is no way of "estimating" the size that a file would have, other than directly counting the information that you will write. You are converting UrlMap into bytes somewhere inside your WriteTo function. That means you can do the same with any URL variable. The way that I would solve this problem is to have a sizeCounter and add the number of bytes that would be stored everytime I create a new URL variable inside the for { loop. In the same place I would also count the number of URLs created. With both counters then the rest is easy. I would add the transformation from URL to bytes inside the .Add function and return it so that everything is easier to understand. You are going to have to move some variables into the go routine. func (s *UrlMap) Add(u *URL) (int) { // Modify this function to count the size and return it s.URLs = append(s.URLs, u) var urlBytes []byte var err error urlBytes, err = xml.Marshal(u) // Transform to bytes using xml.Marshal or xml.MarshalIndent if err != nil { panic(err) // or return the error if you want } return len(urlBytes) } t := time.Unix(0, 0).UTC() done := make(chan bool) go func() { // create new object to populate all URL data in memory urlHolder := NewClient() urlCounter := 0 byteCounter := 0 fileCounter := 0 for { resp, err := stream.Recv() if err == io.EOF { done <- true file, _ := os.Create(fmt.Sprintf("%d_abc_%d.xml", clientId, fileCounter)) urlHolder.WriteTo(file) return } if err != nil { log.Fatalf("can not receive %v", err) } log.Printf("Resp received: %s", resp.GetCustomerUrl()) // I add the bytes of the URL here as a return urlBytes := urlHolder.Add(&URL{ Loc: resp.GetCustomerUrl(), LastMod: &t, ChangeFreq: Daily, Priority: 10.2, }) byteCounter += urlBytes urlCounter += 1 if byteCounter > 49000000 || urlCounter >= 50000 { file, _ := os.Create(fmt.Sprintf("%d_abc_%d.xml", clientId, fileCounter)) urlHolder.WriteTo(file) urlHolder = NewClient() // create a new object for next loop fileCounter += 1 // prepare fileCounter for next loop byteCounter = 0 // restart count variables urlCounter = 0 } } }() <-done log.Printf("finished") // No longer write the files here.
doc_3609
I have very confuse about my problem. switch (state) { case TelephonyManager.CALL_STATE_IDLE: Log.v("idle state", "CALL_STATE_IDLE"); // CALL_STATE_IDLE; if(ring == true && callReceived == true && CheckMissCall.isReject == true) { Intent inter = new Intent(c, callLog.class); inter.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); c.startActivity(inter); } if (ring == true && callReceived == false && CheckMissCall.isRunning== false) { Log.v("missed call", "Missed call from : " + incomingNumber); if(CheckMissCall.isShown) { c.stopService(new Intent(c, Unlock_hud.class)); } flag = true; if (prefs.getBoolean("main_state", true)) { Intent inter = new Intent(c, MissCall.class); inter.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); inter.putExtra("CellNumber", incomingNumber); c.startActivity(inter); } } break; case TelephonyManager.CALL_STATE_OFFHOOK: // CALL_STATE_OFFHOOK; callReceived = true; Log.v("call received", "CALL_STATE_OFFHOOK " + incomingNumber); break; case TelephonyManager.CALL_STATE_RINGING: ring = true; // CALL_STATE_RINGING Log.v("call ringing", "CALL_STATE_RINGING " + incomingNumber); Log.d("flags", "flags: " + flag); if (flag) { //cut = true; //flag = false; CheckMissCall call = new CheckMissCall(c); call.setName(incomingNumber); call.setNumber4Sms(incomingNumber); call.setContactPhoto(); Log.d("main", "state ringing"); //prefs = PreferenceManager.getDefaultSharedPreferences(c); if (!prefs.getBoolean("main_state", false)) { return; } /* if (!isScreenOn && CheckMissCall.isRunning) { return; }*/ if (CheckMissCall.isRunning) { return; } else { Log.d("main", "EEEEEEEEEEEEEEEE: Unlock hud"); Intent in = new Intent(c, Unlock_hud.class); in.setFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP); c.startService(in); // c.stopService(new Intent(c, Unlock_hud.class)); } } break; } A: this is because when any call comes your app goes into background, while for the first time when you receive call your MyPhoneStateListener listens for the call and it ends.. now do one thing.. Run your code in service it will run in background and it will call your dynamic screen in your main activity start service for this i have used toggle button(to enable or disable service) tgl_switch.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { // TODO Auto-generated method stub if(tgl_switch.isChecked()){ startService(new Intent(getApplicationContext(),LogsService.class)); Toast.makeText(getApplicationContext(), "Call Logger Active", Toast.LENGTH_SHORT).show(); }else{ stopService(new Intent(getApplicationContext(),LogsService.class)); Toast.makeText(getApplicationContext(), "Call Logger Deactive", Toast.LENGTH_SHORT).show(); } }}); for example i did this public class LogsService extends Service { String name; String phNumber; String callType; String callDate; Date callDayTime; String callDuration; String dir ; String fileName; boolean wasRinging=false, wasoffHook=false, wasidle=false; private final BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(final Context context, Intent intent) { if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_RINGING)) { // This code will execute when the phone has an incoming call Log.d("ring ", "Detected"); wasRinging = true; // get the phone number // String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER); // Toast.makeText(context, "Call from:" +incomingNumber, Toast.LENGTH_LONG).show(); } else if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals( TelephonyManager.EXTRA_STATE_OFFHOOK)){ wasoffHook=true; // Toast.makeText(context, "hang up", Toast.LENGTH_LONG).show(); } else if(intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals( TelephonyManager.EXTRA_STATE_IDLE)) { // This code will execute when the call is disconnected wasidle=true; // Toast.makeText(context, "IDLE STATE", Toast.LENGTH_LONG).show(); if((wasRinging && wasoffHook && wasidle)){ // this is received call event startActivity(new Intent(getApplicationContext(), Incoming.class)); } else if(wasRinging && wasidle){ // this is missed call event startActivity(new Intent(getApplicationContext(), MissCall.class)); } wasidle = false; wasoffHook = false; wasRinging=false; } } } @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } @Override public void onCreate() { IntentFilter filter = new IntentFilter(); filter.addAction(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED); registerReceiver(receiver, filter); } @Override public void onDestroy() { unregisterReceiver(receiver); } } i used this code to get details of last call you can modify it in your way
doc_3610
I want to Clear "Points" value of all users at a time, For Example There : Points value is "744" so i want to clear this all of my users. A: UPDATE wp_usermeta SET meta_value = 0 WHERE meta_key = 'points'; This should set the meta_value to 0 for all rows where the meta_key is points. Thank Ergest Basha for pointing out the discrepancy in the previous answer.
doc_3611
I was advised to store the images in the document directory and save a path in core-data as to not store the actual images there but simply the address of where I can go and find it. Can someone push me in the right direction? Can't seem to find the appropriate guidance? A: I was able to find the answers to all my questions in this youtube video - https://www.youtube.com/watch?v=6vk4UrJR8WM This is the github with the file that has instructions as to how to complete this - https://github.com/TDAbboud/WeightLogger-Images A: Try Hanake cache: https://github.com/Haneke/Haneke It worked really well for me personally with the same problem. It makes a sometimes painful task pretty easy. A: Save an image in Document directory is easy this code is not optimized is just for give you a hint( you should manage errors, optionals etc). Suppose that you already have a valid UIImage instance called image and a valid image name String called imageName let data = UIImagePNGRepresentation(image) // Unwrapping the data optional if let data = data { let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) let path = (paths.first! as! NSString).stringByAppendingPathComponent(imageName) data.writeToFile(path, options: []) //Save the path into your managed object }
doc_3612
test("test make_params properly url encodes", function() { var o = {"foo":'foo val',"bar":'bar&val'}; var actual = make_params(o); equals('?foo=foo+val&bar=bar%26val', actual, "Expected urlencoded string built to be" + '?foo=foo+val&bar=bar%26val'); }); Results in: 1. Expected urlencoded string built to be?foo=foo+val&bar=bar%26val, expected: "?foo=foo val&bar=bar&val" result: "?foo=foo+val&bar=bar%26val", diff: "?foo=foo val&bar=bar&val" "?foo=foo+val&bar=bar%26val" Is this a bug in qunit or am I overlooking something? A: One minor issue: equals expect the actual value as the first argument, the expected as the second. And equals is now deprecated in favor of equal. Based on that its likely that the test works fine, but the make_params method doesn't actually encode anything.
doc_3613
import torch l = torch.nn.Linear(2,5) v = torch.FloatTensor([1, 2]) print(l(v)) under torch.FloatTensor, pylint in visual studio code claims that 'Module torch has no 'FloatTensor' member pylint(no-member). However, the code works fine. Is this a false positive? How can I disable pylint for this specific instance? A: Yes it is a problem of Pylint If you use Anaconda, you can do: 1. search python.linting.pylintPath in your VSCode setting 2. change it to (You Anaconda Path)\pkgs\pylint-1.8.4-py36_0\Scripts\pylint You Anaconda Path and pylint-1.8.4-py36_0 may vary A: * *Press: CTRL + Shift + P *Click on "Preferences: Open Settings (JSON)" *Add this line into JSON : "python.linting.pylintArgs": ["--generated-members", "from_json,query"] A: What worked for me was noticing what modules were giving those errors, which is torch for you, and then followed these steps: * *hit CTRL + Shift + P *click on "Preferences: Open Settings (JSON)" *add the following to the JSON file you are presented with: "python.linting.pylintArgs": [ "--generated-members", "torch.*" ] for the sake of this answer, say that there were other modules giving problems, then you'd write: "python.linting.pylintArgs": [ "--generated-members", "torch.* other_module.* next_module.*" ] A: A better answer to this question here: Why does it say that module pygame has no init member? The answer above marked as the answer with references to Anaconda doesn't make sense to me, probably a newbie issue. Please follow the link to get the real scoop, but to summarize - Replacing extensionname with your problem module name, such as pygame or RPi or Torch: * *Hit CTRL + Shift + P *Click on "Preferences: Open Settings (JSON)" *Add the following to the JSON file you are presented with (inside the {}, if there are entries already there add leading comma as well): "python.linting.pylintArgs": [ "--extension-pkg-whitelist=extensionname" // comma separated ] A: As Tomari says, it does work on windows.There is a little difference on linux. The path maybe like "(You Anaconda Path)/pkgs/pylint-2.6.0-py38_0/bin/pylint".
doc_3614
$custom = "8-1,1-1,4-1,"; foreach ($custom as $each_item) { $id = $each_item['id']; $quantity = $each_item['quantity']; $sql3 = mysql_query("SELECT * FROM products WHERE id='$id' LIMIT 1"); while ($row = mysql_fetch_array($sql3)) { $product_name = $row["product_name"]; $price = $row["price"]; } } What I have to change in this foreach code? Thanks A: foreach is meant to be used to iterate over array but you are using it with a string. So it is not working for you. A: first line, custom is not a variable (could be copy and paste error) $custom Then you are splitting a string using can array operator, you need to split that string first using: $custompieces = explode(",", $custom); Then, you have declared $custom as $each_item, but you then appear to be trying to access a sub array that doesn't exist. $each_item[id] and $each_item[quantity] are not defined anywhere. I am guessing that you are trying to split the 8-1 into id-quantity, in which case you need to actually define those to be able to use them. $pieces = explode("-", $each_item); $id = $pieces[0]; $quantity = $pieces[1]; So your final code needs to be: $custom = "8-1,1-1,4-1,"; $custompieces = explode(",", $custom); foreach ($custompieces as $each_item) { $pieces = explode("-", $each_item); $id = $pieces[0]; $quantity = $pieces[1]; $sql3 = mysql_query("SELECT * FROM products WHERE id='$id' LIMIT 1"); while ($row = mysql_fetch_array($sql3)) { $product_name = $row["product_name"]; $price = $row["price"]; } }
doc_3615
i am using npm start to run the app import React, { Component} from 'react'; import './App.css'; import { BrowserRouter as Router, Routes, Route } from "react-router-dom"; // import Formed from './form' import Heading from './titlebar'; import Login from './Login'; class App extends Component{ constructor(props){ super(props) this.handleClick = this.handleClick.bind(this) } handleClick() { console.log("hello world") } render(){ return( <div id='App'> {/* <Login /> */} <Router> <Routes> <Route exact path = '/' element= {<Login />} /> <Route exact path = '/home' element = {<Heading />} /> </Routes> </Router> </div> ) } } export default App; import React, {Component} from "react"; import Heading from './titlebar' import Formed from "./form"; class Login extends Component{ render(){ return(<div> <Heading id="title"/> <div id='form_Division'> <Formed id='form'/> </div> </div> ) } } export default Login; import React, {Component} from "react"; import history from './history'; // import ReactHtmlParser, { processNodes, convertNodeToElement, htmlparser2 } from 'react-html-parser'; class Formed extends Component{ constructor(props){ super(props) this.handleSubmit = this.handleSubmit.bind(this) this.handleChange = this.handleChange.bind(this) this.handlePassChange = this.handlePassChange.bind(this) this.state = {value:'',password:'', resp_data:'', isLoggedin:false} } handleSubmit(event){ // console.log(this.state) // alert('a name was submitted :'+this.state.value+' '+this.state.password) var loggedin = false; const cred = {value:this.state.value, password:this.state.password} fetch("http://localhost:8000/api/posts?name="+this.state.value, { method:'POST', body:JSON.stringify(cred), headers:{'Content-type':'application/json'} }).then(response => response.text()).then(data => { this.setState({resp_data: data, isLoggedin:true}) }) if(this.state['isLoggedin']){ history.push('/home') } event.preventDefault() } handleChange(event){ this.setState({value:event.target.value}) // event.PreventDefault() } handlePassChange(event){ this.setState({password:event.target.value}) } render(){ // if (this.state['resp_data'] === ''){ return( <form id={this.props.id}> <label> name: <input type='text' value={this.state.value} onChange={this.handleChange}/> </label> <p> <label> password: <input type='password' ref="password" onChange={this.handlePassChange} value={this.state.password}/> </label> </p> <button onClick={this.handleSubmit} >clickme</button> </form> ) // } // else{ // return this.state['resp_data'] // } } } export default Formed; this is my source code. please help i have tried changing browsers and using hashrouter but the issue persists there as well.I tried running the code on linux it works fine there seems to be an issue with react on windows maybe.
doc_3616
SELECT @query = 'select file-id,file-Name from Files ' SELECT @Clause = 'where' SELECT @colName = 'file-id' SELECT @Filter = '1,2,3,4' SELECT @sql = @query + ' ' + @Clause + ' ' + @ColName + ' IN ' + Convert(bigint,(SELECT csvvalues from [dbo].[SplitString](@Filter,',') as s)) when I execute this via execute sp_executesql it is throwing this error. returnsError#:512|ErrorSubquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression. What I'm doing wrong here.Please Help. A: The IN clause can be used with csv's or tables. As you are calling SP_EXECUTESQL you just need a string to determine the filter, hence the following should work: ` SELECT @query = 'SELECT file-id,file-Name FROM Files ' SELECT @Clause = 'WHERE' SELECT @colName = 'file-id' SELECT @Filter = '1,2,3,4' SELECT @sql = @query + ' ' + @Clause + ' ' + @ColName + ' IN (' + @Filter + ')'
doc_3617
Any way to make it so it sorts of resets the event? $(function () { $(document).on('click', '.box', function () { $('.box').fadeOut( function () { $(this).hide(); }); }); }); Here is the js fiddle: http://jsfiddle.net/sqfyrkpo/ A: If I understand your question right, you want to hide and show the menu. Show on click of the menu input (which you currently do using the :checked pseudo class in CSS) and then hide when clicking the overlay box that appears? If so, why not just uncheck the input using JQuery. This way the overlay will be controlled by the checkbox and the CSS essentially, using the JQuery to do so. Like this (using the basis of your code already): $(function () { $(document).on('click', '.box', function () { $('#toggle-nav').attr('checked', false); }); }); Here is the updated fiddle to show you: http://jsfiddle.net/lee_gladding/sqfyrkpo/7/ Also: I think you were perhaps trying to overcomplicate it, using a checkbox to show using CSS and then using JQuery to hide, which are two different techniques-both separate and unknowing of each other. Ideally the point of using a checkbox (hack) to toggle other CSS is to use the checkbox to toggle both states without the use of JQuery. As you are using JQuery and the way in which you seem to want this to work, you might want to think about just using JQuery to handle all of this instead of part html checkbox (hack) part JQuery, by using a toggling class, say active, on your box (to show/hide the menu). This would give you much more flexibility of markup too and how you can structure your menu. Just an idea! something like: $(function () { $('#menuButton').on('click', function () { $('.box').toggleClass('active'); }); $('.box').on('click', function () { $(this).removeClass('active'); }); }); and update the CSS to use the active class, similar to: #menu .box.active { opacity: 1; z-index: 400; } (There are other updates to the CSS too in the example) Here is an example with altered HTML, CSS and JQuery: http://jsfiddle.net/lee_gladding/sqfyrkpo/18/ However that said, following the JQuery approach either way, then limits your users to have JQuery enabled to use the menu (strictly not fully accessible). So you might also want to think about how a user with no JS enabled could navigate the page.
doc_3618
./centos/6/repo1/x86_64/ ./centos/7/repo1/x86_64/ ./rhel/7/repo2/noarch/ So combinations of distribution name, major release version, repo name and base arch could be arbitrary, and no extra directories would be created. It looks like Ansible file module is suitable for this job, so I create a list of variables with this kind of structure: repos: - name: repo1 os_list: - centos - rhel major_distribution_list: - 6 - 7 - 8 archs: - noarch - x86_64 Now I'm stuck trying to find a right loop control. with_items only allows me to iterate through key-value pairs, not list elements. with_subelements is a bit more handy, but it only lets me use one of the lists/subelements, while I need two and more: - name: Create dirs file: dest: './centos/7/{{ item[0].name }}/{{ item[1] | default("noarch") }}' state: directory loop: '{{ repos | subelements("archs") }}' This is the best I can get of with_subelements. with_nested does combine as many elements as I like, but I can't find a way to feed it with the lists from the variable. The best I can do with it is to create the whole bunch of possible directories regardless of which are actually needed: - name: Create dirs file: dest: '/centos/{{ item[2] }}/{{ item[0].name }}/{{ item[1] | default("noarch") }}' state: directory with_nested: - '{{ repos }}' - [x86_64, noarch] - [6, 7] with_cartesian seems to be pretty much the same. So the question is: is there a way to use a complex variable with multiple lists and combine them all in one task? A: An option would be to loop include_tasks. The play below vars: repos: - name: repo1 os_list: - centos - rhel major_distribution_list: - 6 - 7 - 8 archs: - noarch - x86_64 tasks: - include_tasks: repo-paths.yml loop: "{{ repos }}" loop_control: loop_var: repo ... # cat repo-paths.yml - debug: msg="./{{ item.0 }}/{{ item.1 }}/{{ item.2 }}/{{ item.3 }}" with_nested: - "{{ repo.os_list }}" - "{{ repo.major_distribution_list }}" - "{{ repo.name }}" - "{{ repo.archs }}" gives: "msg": "./centos/6/repo1/noarch" "msg": "./centos/6/repo1/x86_64" "msg": "./centos/7/repo1/noarch" "msg": "./centos/7/repo1/x86_64" "msg": "./centos/8/repo1/noarch" "msg": "./centos/8/repo1/x86_64" "msg": "./rhel/6/repo1/noarch" "msg": "./rhel/6/repo1/x86_64" "msg": "./rhel/7/repo1/noarch" "msg": "./rhel/7/repo1/x86_64" "msg": "./rhel/8/repo1/noarch" "msg": "./rhel/8/repo1/x86_64" A: Instead of mapping you should create nested dict files. For eg. os: centos: - rhel: - This way you can control the loop per os and per distribution. Also my suggestion would be use some values from ansible facts Variables like os name, os major distribution, architecture can be easily taken from ansible facts which will reduce the dict creation and implementing the ansible module would be easy
doc_3619
I am trying to parse a markdown file which has some verbatim code sections in it, separated by the ``` blocks. These blocks neednot be the only characters in a line and \``` this is some code ``` and this is not is a valid line as well. If possible, I'd appreciate if the solution uses pure Fsharp way of doing things and perhaps functional designs patterns like Active Patterns. So far I haven't gone much further than just reading the file. open System open System.IO let readFile path = File.ReadAllText(path) // File.ReadAllLines [<EntryPoint>] let main argv = readFile "src/main.md" |> String.collect (fun ch -> sprintf "%c " ch) |> printfn "%s" 0 EDIT: I do not want to use any libraries. In Python, this would be a one line code; re.search('start;(.*)end', s) A: The best way to parse Markdown is to use a library designed to parse Markdown, such as FSharp.Formatting. It's really not a wheel you'll want to reinvent, especially if you're new to F#. Usage example: open FSharp.Markdown let markdownText = """ # Some document Here is a document with a code block ```fsharp let example = "Foo ``` Here is more text""" let parsed = Markdown.Parse(markdownText) printfn "%A" parsed And since you're interested in an F#-idiomatic solution, take a look at the source for FSharp.Formatting's Markdown parser: plenty of discriminated unions, active patterns, and so on.
doc_3620
Any advice is appreciated. Thanks! A: Branching For each class, run within the repository git checkout --orphan <classname>, and you can get a new parentless branch for that class's content. When getting local copies of your repository, run git clone --single-branch --branch <classname> <url> <localdir>, and it will only clone and later fetch that class's branch. Bitbucket As trauzti said, I would definitely recommend a Bitbucket account. While the UI isn't as pretty as Github's, it has all the same functionality, and they do allow free unlimited private repositories. I use it for my schoolwork. If you really want to use Github though, then the above would work. A: Maybe someone knows a way to use submodules for this: http://git-scm.com/book/en/Git-Tools-Submodules You could use multiple branches, one branch for each class, and check out the different branches in different directories on your computer. But if there are only 5 people or less going to be using these repositories you should check out BitBucket: https://bitbucket.org/ There you can have an infinite number of private repositories for free.
doc_3621
declare namespace ns { interface Test { readonly x: number; } } with: Cannot find name 'readonly'. Property or signature expected. nor does this: declare namespace ns { interface Test { const x: number; } } with: Property or signature expected. A: Your example is compiled without error by TypeScript 2.0: declare namespace ns { interface Test { readonly x: number; } } The current release is 1.8. In order to test with the next version, on a local installation: 1/ install the nightly build of TypeScript with npm install typescript@next, then 2/ execute the compiler: ./node_modules/.bin/tsc your-file.ts. A: You can't assign a value to a property in an interface in TypeScript. So how would you set a readonly variable if you are not allowed to initially set it. You can take a look at the answer to this question here how you could solve this using a module instead: module MyModule { export const myReadOnlyProperty = 1; } MyModule.myReadOnlyProperty= '2'; // Throws an error. Update It seems you have to wait for TypeScript 2.0 for this, which will have readonly properties then: https://github.com/Microsoft/TypeScript/pull/6532
doc_3622
import React, { Component } from 'react'; import { BrowserRouter, Route } from 'react-router-dom'; import PublicLayout from './components/layouts/PublicLayout'; import Main from './components/pages/Main'; import Services from './components/pages/Services'; class App extends Component { render() { return ( <BrowserRouter> <div className="App"> <Route component={ PublicLayout }> <Route exact path='/' component={ Main } /> <Route exact path='/services' component={ Services } /> </Route> </div> </BrowserRouter> ); } } export default App; My PublicLayout is just navigation links. And I see it on the screen. But React doesn't render the Main page content. What I expect to see it just Hello World from Main page component below Navbar. What I'm doing wrong? Please help. UPD: My PublicLayout code: import React, { Component } from 'react'; import Navbar from '../nav/Navbar'; class PublicLayout extends Component { state = { items: [ { id: 1, name: 'Услуги', link: '/services' }, ] } render() { return ( <div> <Navbar items={ this.state.items } /> { this.props.children } </div> ); } } export default PublicLayout; UPD2: In browser console I see an error: Warning: You should not use <Route component> and <Route children> in the same route; <Route children> will be ignored A: Am not sure why are you using PublicLayout, you can't use Route inside Route. Create PublicLayout as child inside BrowserRouter. ` <BrowserRouter> <div className="App"> <Route exact path="/" component={Main} /> <Route exact path="/services" component={Services} /> </div> </BrowserRouter> A: Found an answer here. Since React v4 to wrap components you don't put anymore your Routes inside another Route, you put your Routes directly inside a component. <Router> <MyLayout> <Route path='/abc' component={ABC} /> <Route path='/xyz' component={XYZ} /> </MyLayout> </Router> A: Replace <Route component={ PublicLayout }> with <PublicLayout> <PublicLayout> <Route exact path='/' component={ Main } /> <Route exact path='/services' component={ Services } /> </PublicLayout>
doc_3623
doc_3624
I found this related question but it deals more with enforcing the habit than the question of how to actually type efficiently using the opposite hand to hit modifier keys. A: As the question appears to be targeted towards bash command lines, you can use Control-A Meta-U to capitalize the first word of the line, useful for typing env_var=value some_command ... prior to converting it to ENV_VAR=value some_command ... A: Instead of making CAPS LOCK an additional CTRL, you could simply swap CAPS LOCK and LEFT CTRL.
doc_3625
Is there any way to read multiple files or files name from a folder in Cypress or in JavaScript ? A: You will need to read the file list in cypress.config.js (for Cypress version 10 and above). const { defineConfig } = require('cypress') const fs = require("fs"); module.exports = defineConfig({ e2e: { setupNodeEvents(on, config) { const xmlFolder = `${__dirname}/xml-files/`; const files = fs.readdirSync(xmlFolder) .map(file => `${xmlFolder}/${file}`) // add folder path config.xmlFiles = files // put in config for test return config } } }) In the test, describe('Creating one test for each XML file', () => { Cypress.config('xmlFiles') .forEach(fileName => { it(`Testing ${fileName}`, () => { cy.readFile(fileName) .then(xml => { ... }) }); }); }) For Cypress version 9 and below use plugins.index.js: module.exports = (on, config) => { on('before:run', (spec) => { const xmlFolder = `${__dirname}/xml-files/`; const files = fs.readdirSync(xmlFolder) .map(file => `${xmlFolder}/${file}`) // add folder path config.xmlFiles = files // put in config for test }) return config } A: You can use fs to read the content of a directory, and then we can use Cypress Lodash to iterate through that returned array. import fs from 'fs'; const files = fs.readdirSync('/my/dir/'); describe('My Tests', () => { Cypress._.times(files.length, (index) => { it(`does some test for the file: ${files[index]}, () => { cy.readFile(files[index]).should(...); }); }); });
doc_3626
I would like to get the ids of the relationships like the nodes but I can't find how. In the exemple, we can see that the id of the node is displayed : { "_type":"Movie", "_id":33, "title":"Something's Gotta Give", "acted_in.roles":[ "Julian Mercer" ] } But I would like to have also the id of the relationship : { "_type":"Movie", "_id":33, "title":"Something's Gotta Give", "acted_in.roles":[ "Julian Mercer" ] "acted_in._id": 65 } I've tried to use the map config to get them : CALL apoc.convert.toTree(paths, true, { rels: {acted_in: ['_id']} }) Unfortunately, It doesn't work. Do you have any suggestions ? A: Unfortunately, that APOC function does not return the _id value of the relationship :ACTED_IN. Notice that the variable is a class variable which is preceded by _, so it implicitly added in the result. Try to experiment on the APOC and put a property in the relationship that doesn't exists like 'roleX': CALL apoc.convert.toTree(paths, true, { rels: {acted_in: ['roleX']} }) The result is none of the relationship properties (like roles), will be shown. It is because it cannot find a match on the list of properties in the relationship :ACTED_IN. The property _id is not an explicit property on :ACTED_IN so it does not work. I would suggest a hack so it is up to you if you like it. 1) create another property named: id which is the same value with id(rel) 2) then do your query such as {acted_in: ['id']}. Sample below: MATCH ()-[r:ACTED_IN]->() SET r.id = id(r) then: CALL apoc.convert.toTree(paths, true, { rels: {acted_in: ['id']} }) Result: { "born": 1964, "_type": "Person", "name": "Keanu Reeves", "acted_in": [ { "_type": "Movie", "_id": 154, "acted_in.id": 221, "title": "Something's Gotta Give", "released": 2003 } ], "_id": 1 }
doc_3627
SELECT mc.user_id, mc.id AS movie_comment_id, mc.add_date, mc.movie_id, mc.comment, m.id, m.name FROM movie_comment AS mc INNER JOIN movie AS m ON m.id = mc.movie_id WHERE movie_id = 1500 AND stat = 'onayli' ORDER BY mc.add_date DESC LIMIT 10 What i want is that retriving also usernames from user table.I wrote this sql but does not work SELECT u.id, u.username, mc.user_id, mc.id AS movie_comment_id, mc.add_date, mc.movie_id, mc.comment, m.id, m.name FROM movie_comment AS mc INNER JOIN movie AS m ON m.id = mc.movie_id ON mc.user_id = u.id WHERE movie_id = 1500 AND stat = 'onayli' ORDER BY mc.add_date DESC LIMIT 10 How can i also retrieve usernames ? A: You need to specify INNER JOIN at the start of each inner join. select u.ID ,u.USERNAME,mc.USER_ID,mc.ID as Movie_Comment_ID,mc.ADD_DATE,mc.MOVIE_ID,mc.COMMENT,m.ID,m.NAME from MOVIE_COMMENT as mc INNER Join MOVIE as m ON m.ID=mc.MOVIE_ID INNER JOIN [USER] u ON mc.USER_ID = u.ID WHERE MOVIE_ID = 1500 and STAT='onayli' ORDER BY mc.ADD_DATE DESC LIMIT 10 A: select u.ID ,u.USERNAME,mc.USER_ID,mc.ID as Movie_Comment_ID,mc.ADD_DATE,mc.MOVIE_ID,mc.COMMENT,m.ID,m.NAME from MOVIE_COMMENT as mc INNER Join MOVIE as m ON m.ID=mc.MOVIE_ID INNER JOIN usertable as u ON mc.USER_ID = u.ID WHERE MOVIE_ID = 1500 and STAT='onayli' ORDER BY mc.ADD_DATE DESC LIMIT 10 A: SELECT u.ID, u.USERNAME, mc.USER_ID, mc.ID as Movie_Comment_ID, mc.ADD_DATE, mc.MOVIE_ID, mc.COMMENT, m.ID, m.NAME FROM MOVIE_COMMENT as mc INNER JOIN MOVIE as m ON m.ID = mc.MOVIE_ID INNER JOIN [User] u ON u.ID = mc.USER_ID WHERE MOVIE_ID = 1500 and STAT='onayli' ORDER BY mc.ADD_DATE DESC LIMIT 10
doc_3628
LSB Version: :core-4.1-amd64:core-4.1-noarch:cxx-4.1-amd64:cxx-4.1- noarch:desktop-4.1-amd64:desktop-4.1-noarch:languages-4.1-amd64:languages-4.1-noarch:printing-4.1-amd64:printing-4.1-noarch Distributor ID: RedHatEnterpriseWorkstation Description: Red Hat Enterprise Linux Workstation release 7.3 (Maipo) Release: 7.3 and Distributor ID: Ubuntu Description: Ubuntu 16.10 Release: 16.10 In both of the machines I have installed tensorflow using pip install tensorflow (v0.12) and before doing that I ran a conda update --all to make sure I had all the packages with same versions. Here the fun part starts. Only on the RedHat mahcine the ADAM optimizer converges (I predict the 3d location of neurons and it goes below 10um in around 500 epochs and the final accuracy on validation is around 5um on validation set). Excatly same code and exactly same data (cloned as they are from git) on the Ubuntu machine give much worse results: after 500 iteration the error is still around 48 um (starting 'random' accuracy is 69 um) and the final accuracy is around 56um on the validation set. Now, I checked that the data are exactly the same, they are shuffled with the same random seed and the training and validation set are the same. It only seems that the ADAM optimizer (or others as well) does not converge on the Ubuntu system, while it easily converges on the Redhat one. This are the first iterations: RedHat step 0 , training accuracy 81.1025 step 50 , training accuracy 30.0194 step 100 , training accuracy 25.263 step 150 , training accuracy 19.4822 step 200 , training accuracy 12.0292 step 250 , training accuracy 8.85796 step 300 , training accuracy 7.88442 step 350 , training accuracy 7.20183 step 400 , training accuracy 7.10236 step 450 , training accuracy 6.14335 step 500 , training accuracy 6.20344 Ubuntu step 0 , training accuracy 69.9108 step 50 , training accuracy 57.8822 step 100 , training accuracy 56.905 step 150 , training accuracy 54.9463 step 200 , training accuracy 53.7637 step 250 , training accuracy 53.3795 step 300 , training accuracy 50.9828 step 350 , training accuracy 50.4627 step 400 , training accuracy 48.7606 step 450 , training accuracy 47.8309 step 500 , training accuracy 47.8226 On the Redhat machine the CNN converges also using other optimizers. I tried the same code and the same data also on another machine with the same Redhat version installed and on Ubuntu 16.04 and I got the same weird results: working properly on Redhat, and not converging on Ubuntu. I have no idea how the results I get are so different, since I checked that all the installed packages version are the same.
doc_3629
here is the var: var A1='<table Id="AEid" width="85%" border="3"><tbody> <tr><th><b>AM1</b></th><th><b>AM2</b></th><th><b>Total</b></th> </tr><tr><td rowspan="1">​</td><td rowspan="1">​</td><td rowspan="1">​</td></tr> <tr><td rowspan="1">​</td><td rowspan="1">​</td><td rowspan="1">​</td></tr></tbody></table>'; A: You can just create jquery object from your var without attaching to the DOM and manipulate it to heart's content. var newText ='<table><tbody><tr><td>​1</td><td>​2</td><td>​</td></tr><tr><td>​1</td><td>​2</td><td>​</td></tr></tbody></table>'; $newDiv = $(newText); You can refer to the jsfiddle I made. Not the best answer, but will do what you need http://jsfiddle.net/j5pKx/4/. Hope that helps
doc_3630
A: are you using Spring Boot in your Java app? If so, you can use JMX features with Actuator. Jolokia helps you to do this via JMX over HTTP. Please refer: Spring Boot JMX Management If this is a traditional Java App, you have pushed into PCF, you can use Java build pack features to enable JMX. Please refer: Enable JMX port via Java Build Pack Please try and let us know how it goes. A: For a PCF app, the cloud environment should provide dependencies needed for your app. You can inject these dependencies for runtime in various ways, for instance, provide environment settings. If you need say credentials at runtime, you can look at Spring Cloud Services, and the Config server. If you are looking for other services, you can use Service registry and discovery (based on Netflix Eureka component) within Spring Cloud Services. It all depends on your use case. Can you elaborate more on "change properties at runtime"?
doc_3631
DataInputStream din=new DataInputStream(System.in); double d=din.readDouble(); System.out,println(d); A: Basically, don't use DataInputStream if you're trying to read text. DataInputStream is meant for streams of data written by DataOutputStream or something similar. Read the documentation for readDouble to see exactly what it's doing. Options for you: * *Use Scanner and its nextDouble() method: my experience of questions on Stack Overflow is that Scanner is frankly a pain to use correctly *Create a BufferedReader wrapping an InputStreamReader, and then call readLine() to get a line of text, and Double.parseDouble() to parse that into a double. *A hybrid approach: use Scanner, but only to call nextLine() - just a simpler way to read lines of text from System.in, basically. Additionally, you might want to consider using BigDecimal - the value "15.00" sounds like it might be a financial value (e.g. a price) - and those should be stored in BigDecimal as that can represent exact decimal values.
doc_3632
I tried using setCompoundDrawablesWithIntrinsicBounds, but the image only takes up part of the button, even when I have no text. Notes: I will not have text while I display the image, but the button needs to be a TextButton because there will be text without images at times, and images with text at others. A: Just to answer my own question, after hours of thinking, I realized I could just create ImageButtons and TextButtons, and set the visibility (setvisibility(8)) to the buttons when I do not need them. Setting the visibility to 8 for a view makes it be taken out of the layout, and completely disappear for the time being.
doc_3633
Could you give me the advice? Plan is for product, Date is the day which product sold SELECT * CASE WHEN Plan='1 Class Pass', THEN DATE_ADD(DATE(Date),INTERVAL 3 MONTH) WHEN Plan='10 Class Pass', THEN DATE_ADD(DATE(Date),INTERVAL 3 MONTH) WHEN Plan='20 Class Pass', THEN DATE_ADD(DATE(Date),INTERVAL 3 MONTH) WHEN Plan='40 Class Pass', THEN DATE_ADD(DATE(Date), INTERVAL 3 MONTH) WHEN Plan='1 MONTH UNLIMITED', THEN DATE_ADD(DATE(Date), INTERVAL 1 MONTH) WHEN Plan='3 MONTH UNLIMITED' THEN DATE_ADD(DATE(Date), INTERVAL 3 MONTH) ELSE "null" END AS expire_date FROM `table_Transactions`
doc_3634
I realize this can be accomplished by adding a render ... call to every action and telling it to use the same view file, but is there any way I can hook this into a group of actions and avoid being explicit inside every single one? A: Can you better explain why layouts don't work? I believe this code should solve your problem. Let's say you have UsersController and you want all the actions, except new and create to use the same views. Then you can easily do: def UsersController < ApplicationController layout "shared_layout", except: [:new, :create] layout "new_user_layout", only: [:new, :create] def show # Renders in app/views/layouts/shared_layout.html.erb end def index # Renders in app/views/layouts/shared_layout.html.erb end def new # Renders in app/views/layouts/new_user_layout.html.erb end def create # Renders in app/views/layouts/new_user_layout.html.erb end end Then you can create a layout which say what needs to be render in the shared. In app/views/layouts/shared_layout.html.erb <html> <body> <%= render "shared/shared_partial_1.html.erb" %> <%= render "shared/shared_partial_2.html.erb" %> <%= render "shared/shared_partial_3.html.erb" %> <%= yield %> </body> </html> This will render partials 1, 2, and 3 in the same manner for all the actions of the controller. What is wrong with that? A: You have a couple of solutions: You can create a layout in views/layout specifically for these actions. You would then set the layout in your controller: class LalasController < ApplicationController layout "your_action_layout" end You might be talking about this when you're mentioning render ..., but you can create mini layouts from partials: In views/controller_names/my_layout <div class="my-layout"> <%= yield %> </div> And then, in each of your actions, you would do: <%= render layout: "my_layout" do %> <div></div> <!-- All the code of your view --> <% end %>
doc_3635
A: Create a UserStoryLink Table. This will have the following Columns - > Id/UserId(Foreign to User)/ StoryId(Foreign to UserStoy) On each personalized story send, update UserStoryLink with the UserId and StoryId. You can then, before sending, check that StoryId is never present where UserId of who you're sending it to is present.
doc_3636
My problem is that when I first load the data in the detailed view it works fine however when I try to load data again on a another table item (name) the detailed view loads with the first lot of data and does not change until I restart the simulator. i.e. first selection: table "Name 1" push detailed view "Address 1" works fine. second selection: table "Name 2" push detailed view "Address 1" data does not change. Here is my code; -(void) hydrateDetailViewData { if (isDetailViewHydrated) return; if (detailStmt == nil) { const char *sql = "Select ClubAddress from clubNames Where clubID = ?"; if (sqlite3_prepare_v2(database, sql, -1, &detailStmt, NULL) !=SQLITE_OK) NSAssert1(0, @"Error while creating detail view statment. '%s'", sqlite3_errmsg(database)); } sqlite3_bind_int(detailStmt, 1, clubID); if (SQLITE_DONE != sqlite3_step(detailStmt)) { const char *db_text = sqlite3_column_text(detailStmt, 0); NSString *address = [NSString stringWithUTF8String: db_text]; self.ClubAddress = address; } else NSAssert1(0, @"Error while getting the address of club. '%s'", sqlite3_errmsg(database)); sqlite3_reset(detailStmt); isDetailViewHydrated = YES; } I have tried releasing the variable but I get compiler warnings and the app crashes when I try to push detailed view. Any help would be greatly appreciated. Thanks A: I've got some questions: Are you getting the correct information from your query? Check that out by querying the db directly from the command line. Are you presenting the data in table views? Table views don't refresh instantaneously. you should call [tableView reloadData] to do so. Check Table View Programming guide if you have further doubts with that. Can you post the code snippet where you push the that ViewControllers that crash? If you are getting crashes for releasing object, you'd better take a look at the memory management programming guide on the Developer documentation. A: From your code you are setting isDetailViewHydrated to YES but do you ever set it to no?
doc_3637
Here is what I'm working with: .octicon-class { background-image: url('chrome-extension://__MSG_@@extension_id__/'); -webkit-filter: grayscale(100%); height: 16px; width: 16px; vertical-align: text-top; } I was considering using the !important declaration on some of the attributes in this method, but I've seen that it is bad style. Is there a better way to get the button to appear (as opposed to just text)
doc_3638
<div class="input-group"> <select class="form-control" >Some options here</select> <a class="btn btn-default input-group-addon disabled" title="Legg til" disabled="" href="#" ><i class="glyphicon glyphicon-plus-sign"></i></a> </div> This gives the following result in most browsers (including IE10): However in IE9, the "arrow" for the dropdown is missing: Anyone know a fix for this in IE9? A: I found the issue here. It seems that the arrow button is simply hidden below the button with the plus icon. So the select box is the entire width, and the other buttons end up overlying it. So the fix was to add float:left to the select box, and voila! A: You should use .input-group-btn to avoid this issue : <div class="container"> <form role="form"> <div class="form-group"> <div class="input-group"> <select class="form-control"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> <span class="input-group-btn"> <a class="btn btn-default" href="#"><i class="glyphicon glyphicon-plus-sign"></i></a> </span> </div> </div> <button type="submit" class="btn btn-default">Submit</button> </form> </div> A: You just need to remove padding on the select tag. You'll first need conditional classes for IE9. <!--[if IE 9 ]><html class="ie9"><![endif]--> Then just simply remove the padding on the select tags. .ie9{ select.form-control{ padding: 0 !important; } }
doc_3639
* tags I have a script to grab a page and edit it. The page HTML looks something like this: <p>Title</p>...extra content...<ul><li>Item1</li><li>Item2</li></ul> There are multiple titles and multiple unordered lists but I want to change each list with a regular expression that can find the list with a certain title and use .sub in Ruby to replace it. The regex I currently have looks like this: regex = /<p>Title1?.*<\/ul>/ Now if there are any items below the regex it will match to the last tag and accidentally grab all the lists below it for example if I have this content: content = "<p>Title1</p><ul><li>Item1</li><li>Item2</li></ul><p>Title2</p><ul><li>Item1</li><li>Item2</li><li>Item3</li></ul>" and I want to add another list item to the section for Title 1: content.sub(regex, "<p>Title1</p><ul><li>Item1</li><li>Item2</li><li>NEW_ITEM</li></ul>) It will delete all items below it. How do I rewrite my regex to select only the first /ul tag to substitute? A: "I want to change each list with a regular expression." No you don't. You really do not want to go down this road because it's filled with misery, sorrow, and tears. One day someone will put a list item in your list item. There are libraries like Nokogiri that make manipulating HTML very easy. There's no excuse to not use something like it: require 'nokogiri' html = "<p>Title</p>...extra content...<ul><li>Item1</li><li>Item2</li></ul>" doc = Nokogiri::HTML(html) doc.css('ul').children.first.inner_html = 'Replaced Text' puts doc.to_s That serves as a simple example for "replace text from first list item". It can be easily adapted to do other things, as the css method takes a simple CSS selector, not unlike jQuery. A: Use a non-greedy (lazy) quantifier .*? See this explanation of Ruby Regexp repetition. regex = /<p>Title1?.*?<\/ul>/ A: ...it reformats the html with newlines and changes all <br /> to <br>... That's usually because the wrong method is used when emitting the doc as HTML or XHTML: doc = Nokogiri::HTML::DocumentFragment.parse('<p>foo<br />bar</p>') doc.to_xhtml # => "<p>foo<br />bar</p>" doc.to_html # => "<p>foo<br>bar</p>" doc = Nokogiri::HTML::DocumentFragment.parse('<p>foo<br>bar</p>') doc.to_xhtml # => "<p>foo<br />bar</p>" doc.to_html # => "<p>foo<br>bar</p>" As for spuriously adding line-ends where they weren't before, I haven't seen that. It's possible to tell Nokogiri to do that if you're modifying the DOM, but from what I've seen, on its own Nokogiri is very benign.
doc_3640
HTML part: <!-- our new, semanticized HTML --> <div class="article"> <div class="main-section">...</div> <div class="aside">...</div> </div> Less part: /* its accompanying Less stylesheet */ .article { .makeRow(); // Mixin provided by Bootstrap .main-section { .makeColumn(10); // Mixin provided by Bootstrap } .aside { .makeColumn(2); // Mixin provided by Bootstrap } } But when I take a look at the rendered html page... my article take less space than a span12 I can also put a .makeColumn(10) and .makeColumn(4) and it will stay on the same line. It's like it was a 14 grid column and not a 12 grid column. Am I missing something? A: No. If your required number of columns is n, the .makeColumn mixin and the .span (#grid > .core > .span) mixin both calculate width as follows: (@gridColumnWidth * n) + (@gridGutterWidth * (n-1)) which is the width you'll need to set your element to a width of n columns on the grid. If n = 6, it calculates all column widths and gutter widths from the left edge of your grid to the right-hand edge of column 6. 6 columns and 5 gutters. .span only does width, .makeColumn also adds a float: left, and has an optional @offset argument that which isn't important to your current problem, but which allows you to add columns to the left of the element by adding a margin: left. As @sody says above, wrapping your existing elements in a .container should fix your problem. And I agree with @kleinfreund on using the html elements where you can: <div class="container"> <article> <div class="main-section">Bootstrap rocks <aside> By the way... </aside> </div> </article> </div> I hope that helps.
doc_3641
public class OnAlarmReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { String ns = Context.NOTIFICATION_SERVICE; NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns); int icon = R.drawable.icon; CharSequence tickerText = "Votre vidange approche"; long when = System.currentTimeMillis(); Notification notification = new Notification(icon, tickerText, when); CharSequence contentTitle = "Notification"; CharSequence contentText = "Vérifier votre kilométrage"; Intent notificationIntent = new Intent(this, Acceuil.class); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent); final int HELLO_ID = 1; mNotificationManager.notify(HELLO_ID, notification); } However, i don't know why i have this errors: The method getSystemService(String) is undefined for the type OnAlarmReceiverThe constructor Intent(OnAlarmReceiver, Class<Acceuil>) is undefined The method getActivity(Context, int, Intent, int) in the type PendingIntent is not applicable for the arguments (OnAlarmReceiver, int, Intent, int) In the other activity i guess that i have to do this: public void notifs() { AlarmManager mgr=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE); Intent i=new Intent(context, OnAlarmReceiver.class); PendingIntent pi=PendingIntent.getBroadcast(context, 0, i, 0); mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 1800000, pi); } What's the problem here ? Thank you very much. A: The difference is : NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns); and AlarmManager mgr=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE); The second one works because you call getSystemService on an Application Context, where as in the first you are trying to call it on the this object which at the point is an instance of subclass of BroadcastReceiver which has no method called getSystemService. To fix this do : NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(ns); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); This line gives you problems because you are trying to pass an instance of your custom class as the this object instead of a Context object like it expects. To fix this do : PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
doc_3642
My try (doesn't compile): trait A<T> { type Item = T; fn get(&self) -> Self::Item; } struct B {} impl <T> A<T> for B where T: Send + Sync { type Item = T; fn get(&self) -> Self::Item { // return } } impl <T> A<T> for B { type Item = T; fn get(&self) -> Self::Item { // return } } In this case I want to return something which is Send + Sync when the outside context requires it and all other cases return what is defined in the second trait implementation. It doesn't even have to be an implementation of a struct in my case, I simply thought it was necessary. Is it possible to have the same function signature and have the compiler understand which of the two implementation is needed? A: i have a quite an ugly solution for you: trait A<T1, T2> { type Item1; type Item2; fn get1(&self) -> Self::Item1; fn get2(&self) -> Self::Item2; } struct B {} impl <T1, T2> A<T1, T2> for B where T1: Send + Sync, T2: core::fmt::Debug + core::fmt::Display { type Item1 = ::std::sync::Arc<::std::string::String>; type Item2 = ::std::string::String; fn get1(&self) -> Self::Item1 { // return ::std::sync::Arc::new(String::from("asd")) } fn get2(&self) -> Self::Item2 { String::from("hello world") } } playground i know its not what you want, but if you dont have many implementations that you wanted for T (lets say 4), it does achieve what you want, i hope.
doc_3643
Examples "24kb" = 24.kilobytes = 24576 "32MB" = 32.megabytes = 33554432 "64 GB" = 64.gigabytes = 68719476736 I can go the other way, integer to string, using... >> ActiveSupport::NumberHelper.number_to_human_size(68719476736) => "64 GB" I tried... >> Integer("64GB") => ArgumentError: invalid value for Integer(): "64GB" I can create my own method doing something like... def convert_size_to_integer(size) size.downcase! if(size.end_with? 'kb') size.to_i.kilobytes elsif(size.end_with? 'mb') size.to_i.megabytes elsif(size.end_with? 'gb') size.to_i.gigabytes else size.to_i end end but this is dissatisfying and seems like there is probably something already out there to do this. And, of course, I could simplify this and make it more robust using regex. But I am trying to avoid writing this at all by finding something that already exists. Any suggestions? A: There's filesize It's quite trivial to write your own: But you can write your own: def convert_size_to_bytes md = match(/^(?<num>\d+)\s?(?<unit>\w+)?$/) md[:num].to_i * case md[:unit] when 'KB' 1024 when 'MB' 1024**2 when 'GB' 1024**3 when 'TB' 1024**4 when 'PB' 1024**5 when 'EB' 1024**6 when 'ZB' 1024**7 when 'YB' 1024**8 else 1 end end
doc_3644
A: You can enforce Pull Requests!! . Before your code gets to be merged on the server , it has to go through code review and discussion among some engineers who feel that its as per the standards . Once approved , now this PR can be merged to target branch. Also you should lock your master/ so that no Push will be allowed and engineers don't force push their changes without reviewing. A: There are some possibilities. Git itself propose Integration-Manager Workflow where every developer has own public repo, when code is ready put things to own repo and send message to integration manager to merge his code. If integration manager says that code is good enough merge code from developer public repo to his "blessed repo", where only him can push. Rest of developers should merge changes to theirs code. Other variation of this method is to use different branches for every developer, and only integration manager merge it to master, but this method is without authorization. Other possibility is to use some git server offers control of pull requests, when code is ready for publish, developer send pull request, and after code review someone with credentials can accept this request.
doc_3645
python -v # installing zipimport hook import zipimport # builtin # installed zipimport hook # /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.py import site # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site.pyc # /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py import os # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc import errno # builtin import posix # builtin # /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.py import posixpath # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc # /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/stat.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/stat.py import stat # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/stat.pyc # /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/genericpath.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/genericpath.py import genericpath # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/genericpath.pyc # /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/warnings.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/warnings.py import warnings # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/warnings.pyc # /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/linecache.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/linecache.py import linecache # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/linecache.pyc # /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/types.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/types.py import types # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/types.pyc # /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/UserDict.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/UserDict.py import UserDict # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/UserDict.pyc # /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_abcoll.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_abcoll.py import _abcoll # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_abcoll.pyc # /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/abc.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/abc.py import abc # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/abc.pyc # /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_weakrefset.pyc matches /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_weakrefset.py import _weakrefset # precompiled from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_weakrefset.pyc import _weakref # builtin What did I do? I just don't know waht the error is. Here is another issue: dbconf -a lms -d wu-llm -e prod get lms_core.db_root_pwd Traceback (most recent call last): File "/usr/local/bin/dbconf", line 8, in <module> sys.exit(main()) File "/usr/local/lib/python2.7/site-packages/dbconf/__init__.py", line 418, in main args.func(get_domains(args), args) File "/usr/local/lib/python2.7/site-packages/dbconf/__init__.py", line 66, in get_domains return [get_domain(domain, args.app, env) for env in args.environments for domain in args.domains] File "/usr/local/lib/python2.7/site-packages/dbconf/__init__.py", line 60, in get_domain parser.error("domain does not exist: %s" % name) AttributeError: 'NoneType' object has no attribute 'error'
doc_3646
packages/ -Shreeji/ --Ring/ ---composer.json ---src/ ----Ring.php ----RingModel.php ----RingServiceProvider ----Views/ -----ringslist.blade.php composer.json { "name": "shreeji/ring", "description": "Simple", "license": "MIT", "authors": [ { "name": "author", "email": "email@gmail.com" } ], "autoload": { "psr-4": { "Shreeji\\Ring\\": "src/" } }, "minimum-stability": "dev", "require": { "Illuminate/support": "~5" } } Ring.php namespace Shreeji\Ring; use Illuminate\Http\Response; Class Ring { function __construct() { } public function get_all() { return view("ring::ringlist"); } } RingServiceProvider.php namespace Shreeji\Ring; use Illuminate\Support\ServiceProvider; Class RingServiceProvider extends ServiceProvider { public function register() { $this->app->bind('ring', function($app){ return new Ring; }); } public function boot() { $this->loadViewsFrom(__DIR__ . '/Views', 'ring'); } } ringlist.blade.php <!DOCTYPE html> <html> <body> <h1>Welcome</h1> </body> </html> And in app/Http/Controllers I have created a test file like this: Ringcontroller.php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use Shreeji\Ring\Ring; class RingController extends Controller { public function index() { $ring = New Ring(); $ring->get_all(); } } When I call the controller, browser keeps loading and crashed systematically. I don't know if I can use view outside any controller class like such. Let me know if I did any mistake in calling view from Ring.php file. A: You can use somethin like view composer Docs In your RingServiceProvider register a composer use Illuminate\Contracts\View\Factory as ViewFactory; public function boot(ViewFactory $view) { $view->composer('*', 'App\Http\ViewComposers\SomeComposer'); } And in App\Http\ViewComposers\SomeComposer use Illuminate\Contracts\View\View; public function compose(View $view) { $view->with('count', '1'); } Play around with it, basically I am using it share $variables on particular views but maybe this can help you achieve what you want. Or u can just use Illuminate\Contracts\View\View; to load your view that you need! A: Couple issues I see: * *You want to use views, but your package does not require the illuminate/view package. You need to update your composer.json file to require "illuminate/view": "~5". *The view() function is a helper method included at Illuminate\Foundation\helpers.php. Unless you want to depend on the entire Laravel framework just for this function, you will need to create your own view() function. The code is below, where you put it is up to you. if (! function_exists('view')) { /** * Get the evaluated view contents for the given view. * * @param string $view * @param array $data * @param array $mergeData * @return \Illuminate\View\View|\Illuminate\Contracts\View\Factory */ function view($view = null, $data = [], $mergeData = []) { $factory = app(ViewFactory::class); if (func_num_args() === 0) { return $factory; } return $factory->make($view, $data, $mergeData); } } *Once you get the view stuff working, you can make views all day long, but if you don't return anything from your controller, you're not going to see anything. Make sure you return something from your controller methods.
doc_3647
OperationalError at / no such column: imgProcess_image.username # model class Image(models.Model): username = models.CharField(unique=True, max_length=30) image = models.ImageField(upload_to='user_images') # form class Upload(forms.ModelForm): username = Image.username class Meta: model = Image fields = ['image'] def set_user(self, un): self.username = un # views def delete_image_of_user(request): Image.objects.get(username=request.user.username).delete() def home(request): delete_image_of_user(request) hash = {} comments = CommentModel.objects.all() hash["comments"] = comments return render(request, "imgProcess/home.html", hash) A: Your database has unapplied migrations if you see in your database you wont find username column in Image table. You should build and apply migrations. Run python manage.py makemigrations then python manage.py migrate to apply them.
doc_3648
Whoops, looks like something went wrong. Property [id] does not exist on this collection instance. What I've done so far This is my Route Route::get('book/edit/{id}', 'BookController@edit')->name('admin.book.edit'); Route::PATCH('book/edit/{id}', 'BookController@update')->name('admin.book.edit'); This is my controller $books = $this->bookModel ->join('author', 'author.id', '=', 'book.author_id') ->where('book.id', '=', $id) ->select('book.*', 'author.name_1 as authorname1') ->get(); return view('backend.book.edit', compact('books', $books)); Finally view file have the following in form part {{ Form::model($books, ['route' => ['admin.book.edit', $books->id], 'class' => 'form-horizontal', 'role' => 'form', 'method' => 'PATCH']) }} <!--form content--> {{ Form::close() }} Any help will be appreciated. Thanks A: The error is here: $books->id When you're using get() you get a collection and $books is a collection. In this case you need to iterate over it to get its properties: @foreach ($books as $book) {{ $book->id }} @endforeach A: You have to retrieve one record with first() not a collection with get(), i.e: $book = $this->bookModel ->join('author', 'author.id', '=', 'book.author_id') ->where('book.id', '=', $id) ->select('book.*', 'author.name_1 as authorname1') ->first(); Please sobstitute $books with $book in the rest of the code also. A: I too had the similar error where I was using eloquent relationship, and the problem was I was using return $this->hasMany(ClassName::class); But the relation was of One-to-One so the solution for the problem is return $this->hasOne(ClassName::class);. Here in above sample the first code segment will return array of objects which will be breakdown the flow of eloquent relation in chained eloquent code like $firstChain->middleChain->requiredData Here if middleChain has arrayOfObjects it cause above error saying property doesn't exist. Be careful when using eloquent relation to properly mention the type of relation it has A: I think your code need to update like: $books = $this->bookModel ->join('author', 'author.id', '=', 'book.author_id') ->where('book.id', '=', $id) ->select('book.*', 'author.name_1 as authorname1') ->first(); return view('backend.book.edit', compact('books')); Hope this work for you! A: As Mayank mentioned above you get a collection, you neeed to itreate over the FIELDS to get the right field you want. I am giving the same answer in the sytax which is working for me foreach ($books as $book) { $book_id = $book->id }
doc_3649
I am supposed to use all views in Angular but I couldn't do on certain views like landing_page, sign_up, and log_in pages because I need to use devise. home.html.erb is a landing page where the user is being directed to when they first come to my web app. When they click contact on the nav bar, it starts rendering Angular view and shows since contact view is made of Angular. The logic for rendering is in application_controller like below: def home if current_user render :file => 'public/index.html', :layout => false and return else if request.url == "#{request.base_url}/contact" render :file => 'public/index.html', :layout => false and return else render :file => '/pages/home.html.erb' end end end route.rb set up: root 'application#home' If user is not logged in and click contact view, it renders index.html which is Angular view. And Angular routes to /contact/ and shows appropriate view. Contact.html is like following: <header class="page-header"> <div class="page-inner"> <a href="/" class="page-header-logo"><img src="/assets/logo-green.svg" alt="logo"></a> </div> </header> <body> //the view <body> When the user clicks the logo in the contactview, it goes back to landing_page and starts killing the css in home.html.erb. Some of CSS is not correctly loaded and end up changing fonts and fonts color. Why is this happening?
doc_3650
https://your_domain/login?response_type=token&client_id=your_app_client_id&redirect_uri=your_callback_url and getting a response back that looks like: https://www.example.com/#id_token=123456789tokens123456789&expires_in=3600&token_type=Bearer How do I use this to then automatically add the user to a configured AWS Identity Pool? Do I then get credentials back from the Identity Pool allowing access to services like S3 and DynamoDB, and if so how do I do that? The documentation is very confusing, and any help would be much appreciated. A: If you do this without a library then you have to pass that token to cognito identity pool and exchange it for temporary access key and secret key. I would suggest you use a library like AWS-Amplify to manage your authentication needs. The library handles token refreshing as well. Here is the documentation for Amplify: https://aws-amplify.github.io/docs/js/authentication#social-provider-federation
doc_3651
When testing with Instruments, the tool shows that I am leaking memory, the source being SimpleAudioEngine and a bunch of other classes related to playing sounds. Is preloadEffect and preloadBackgroundMusic really that bad? How can I fix my memory leaks? Thank you! A: Preloading effects is not bad practice, to the contrary. When the sound effect plays for the first time, it is loaded just like with the preload methods. The only thing preloading does is to avoid a stutter or freeze while the effect plays for the first time. For large audio files this can cause the app to pause for a tenth of a second or possibly more.
doc_3652
Now according to the docs I can see how one can inject AngularFireAnalytics in their component to log page views: import { AngularFireAnalytics } from '@angular/fire/compat/analytics'; constructor(analytics: AngularFireAnalytics) { analytics.logEvent('custom_event', { ... }); } But Im not able to find a way to only enable the whole analytics only on a specific route, and no where else in the website. I want to set up different paths for the same LandingPageComponent, so that I can visualize the page views from different advertisement funnels. In general I do not want any means of analytics on any other part of the website except for the page view events related to these URLs that end up in the same component after all. A: I managed to solve my question by defining a custom event and adding a condition to check for the specific route that I wanted in the component by injecting Location service from Angular: import {Component, OnInit} from '@angular/core'; import {Location} from "@angular/common"; import {AngularFireAnalytics} from "@angular/fire/compat/analytics"; @Component({ selector: 'app-xxx', templateUrl: './xxx.component.html', styleUrls: ['./xxx.component.scss'], }) export class XxxComponent implements OnInit { constructor(readonly location: Location, readonly analytics: AngularFireAnalytics) { } ngOnInit(): void { if (this.location.path() === '/myPath') { this.analytics.logEvent('custom_event', { ... }); } } } According to what I read, it is not possible to disable the default analytics data collection and instead to just send your custom event. Therefore, you either have to have default data collection enabled and send your custom event, or completely turn analytics off. Although, you can turn on and off the analytics from the component, which I'm not sure if its a good practice. Please let me know if there is an alternative and better solution.
doc_3653
print(user_normalized[1].reshape(1, -1).shape) print(user_normalized[1].reshape(1, -1)) ___________________________________________________________________ (1, 20) [[0. 0.00239107 0.00131709 0. 0.00355872 0.00212352 0.00300639 0.00044287 0.001469 0.00358637 0.01520913 0. 0. 0. 0.00174978 0.00237691 0.0026616 0.00241604 0. 0. ]] Which gives me first user's preference vector. And I have a dataset of movie's content table: print(movie_content.shape) print(movie_content) ___________________________________________________________________ (27278, 20) [[1 0 0 ... 0 0 0] [1 0 0 ... 0 0 0] [0 0 0 ... 0 0 0] ... [0 0 0 ... 0 0 0] [0 0 1 ... 0 0 0] [1 0 0 ... 0 0 0]] I am trying to get dot product of user's preference vector and movie's content table in order to find most preferential movies (cosine similarity): distances = np.dot(user_normalized[1], movie_content) but this gives me the following error: ValueError: shapes (1,20) and (27278,20) not aligned: 20 (dim 1) != 27278 (dim 0) Is it the right way to find distance measure in order to find most preferential movies? If it is what's wrong with the code? A: While the answer above correct, it only works for matrices whose first dimension is exactly 1. Using the transpose of user_normalized (user_normalized.T) will work for more dimensions. So, the short answer is: use distances = np.dot(movie_content, user_normalized.T) The more involved answer is that the dot product is only defined for two matrices X and Y if the second dimension of X matches the first one of Y, i.e., X has shape (M, N) and Y has shape (N, D). The result of the dot product is then a new matrix with dimensions (M, D). In your case, you have a (27278, 20) matrix, and a (1, 20) matrix. The transpose turns the (1, 20) matrix into a (20, 1) matrix, thereby satisfying the conditions for a dot product. The end result is a (27278, 1) matrix, where each cell contains the product of the Nth movie and Dth user. A: You need to reshape the vector to (-1, 1). If you want to take a dot product of two arrays of shape (m, k) and (t, n) then k must be equal to t. As there is no concept of vectors in numpy, you basically have an array of shape (27278, 20) (movie_content) and another array of shape (1, 20) (user_normalized). To be able to take a dot product, you will have to reshape the user_normalized array to shape (20, 1) making the movie_content and user_normalized arrays "aligned" (that's what numpy likes to call it) for dot product. Hence, your code will look like import numpy as np distances = np.dot(movie_content, user_normalized[1].reshape(-1, 1)) Edit: This solution only works when user_normalized is a vector. In case user_normalized is a matrix, you will need to transpose it. See @amdex's answer for that case.
doc_3654
<?xml version="1.0" encoding="utf-8"?> <dskh> <khachhang maso="kh01"> <ten_kh>thehung</ten_kh> <tuoi_kh>15</tuoi_kh> <dchi_kh>hochiminh</dchi_kh> </khachhang> <khachhang maso="kh02"> <ten_kh>hung</ten_kh> <tuoi_kh>15</tuoi_kh> <dchi_kh>hcm</dchi_kh> </khachhang> </dskh> My Encrypt and Decrypt code: class Program { // Call this function to remove the key from memory after use for security. [System.Runtime.InteropServices.DllImport("KERNEL32.DLL", EntryPoint = "RtlZeroMemory")] public static extern bool ZeroMemory(ref string Destination, int Length); // Function to Generate a 64 bits Key. static string GenerateKey() { // Create an instance of Symetric Algorithm. Key and IV is generated automatically. DESCryptoServiceProvider desCrypto = (DESCryptoServiceProvider)DESCryptoServiceProvider.Create(); // Use the Automatically generated key for Encryption. return ASCIIEncoding.ASCII.GetString(desCrypto.Key); } static void EncryptFile(string sInputFilename, string sOutputFilename, string sKey) { FileStream fsInput = new FileStream(sInputFilename,FileMode.Open,FileAccess.Read); FileStream fsEncrypted = new FileStream(sOutputFilename,FileMode.Create,FileAccess.Write); DESCryptoServiceProvider DES = new DESCryptoServiceProvider(); DES.Key = Encoding.UTF8.GetBytes(sKey); DES.IV = Encoding.UTF8.GetBytes(sKey); ICryptoTransform desencrypt = DES.CreateEncryptor(); CryptoStream cryptostream = new CryptoStream(fsEncrypted,desencrypt,CryptoStreamMode.Write); byte[] bytearrayinput = new byte[fsInput.Length - 1]; fsInput.Read(bytearrayinput, 0, bytearrayinput.Length); cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length); } static void DecryptFile(string sInputFilename, string sOutputFilename, string sKey) { DESCryptoServiceProvider DES = new DESCryptoServiceProvider(); //A 64 bit key and IV is required for this provider. //Set secret key For DES algorithm. DES.Key = Encoding.UTF8.GetBytes(sKey); //Set initialization vector. DES.IV = Encoding.UTF8.GetBytes(sKey); //Create a file stream to read the encrypted file back. FileStream fsread = new FileStream(sInputFilename, FileMode.Open, FileAccess.Read); //Create a DES decryptor from the DES instance. ICryptoTransform desdecrypt = DES.CreateDecryptor(); //Create crypto stream set to read and do a //DES decryption transform on incoming bytes. CryptoStream cryptostreamDecr = new CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read); //Print the contents of the decrypted file. StreamWriter fsDecrypted = new StreamWriter(sOutputFilename); fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd()); fsDecrypted.Flush(); fsDecrypted.Close(); } static void Main(string[] args) { // Must be 64 bits, 8 bytes. // Distribute this key to the user who will decrypt this file. string sSecretKey; // Get the key for the file to encrypt. sSecretKey = GenerateKey(); // For additional security pin the key. GCHandle gch = GCHandle.Alloc(sSecretKey, GCHandleType.Pinned); // Encrypt the file. EncryptFile(@"C:\xml_kh.xml", @"C:\xml_encry.xml", sSecretKey); //Decrypt the file. DecryptFile(@"C:\xml_encry.xml", @"C:\xml_decry.xml", sSecretKey); } } When i excute Decrypt code, i get Cryptographicexception: Bad Data here: //Print the contents of the decrypted file. StreamWriter fsDecrypted = new StreamWriter(sOutputFilename); fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd()); fsDecrypted.Flush(); fsDecrypted.Close(); Please help me!!! A: Add two lines at the end of EncryptFile function: cryptostream.Flush(); cryptostream.Close(); EDIT I missed there is one more error: byte[] bytearrayinput = new byte[fsInput.Length - 1]; s/b byte[] bytearrayinput = new byte[fsInput.Length];
doc_3655
e.g. If I wasn't using a dataset then I might highlight a single data point like this: series: [ { type: 'bar', data: [ 97.7, { value: 43, itemStyle: { color: '#ff0000' } }, 92.5 ] But using a dataset I have no place for this extra information: var myChart = echarts.init(document.getElementById('main')); myChart.setOption({ dataset: { source: [ ['A', 97.7], ['B', 43], ['C', 92.5] ] }, xAxis: { type: 'category' }, yAxis: {}, series: [{ type: 'bar' }] }); If I try to set options in series[type='bar'].data then it removes the data supplied by the dataset. A: Facing the same issue and not believing that this functionality isn't implemented into ECharts. I found a solution by using a callback function. By defining an object holding the colors for each data point at its respective key I am able to return the color defined: <div id="main" style="width: 600px;height:400px;"></div> var myChart = echarts.init(document.getElementById('main')); let colors = { 'A': '#FF0000', 'B': '#00FF00', 'C': '#0000FF' }; myChart.setOption({ dataset: [{ source: [ ['name', 'value'], ['A', 97.7], ['B', 43], ['C', 92.5] ] }], xAxis: { type: 'category', }, yAxis: {}, series: { type: 'bar', itemStyle: { color: function(seriesIndex) { console.log(seriesIndex); return (colors[seriesIndex.name]); } } } }); fiddle Additionally I added an optional header row to the dataset. This is not necessary because ECharts is referencing the first column in the dataset by "name". For additional clarity I added a logging statement to the function so you can gain some insight on how the dataset is processed when the chart is rendered. If a simpler solution is needed it is achievable by creating an array of colors and setting the colorBy option to "data" in the series object - see ECharts documentation. This simply iterates through the list of colors and assigns them to each entry in the set: <div id="main" style="width: 600px;height:400px;"></div> var myChart = echarts.init(document.getElementById('main')); myChart.setOption({ dataset: [{ source: [ ['name', 'value'], ['A', 97.7], ['B', 43], ['C', 92.5] ] }], xAxis: { type: 'category', }, color: [ '#FF0000', '#00FF00', '#0000FF' ], yAxis: {}, series: { type: 'bar', colorBy: 'data', } }); fiddle
doc_3656
enter image description here A: This is exactly what Firebase Dynamic links was created for. You can configure urls to redirect based on whether the user has the app installed or not. https://firebase.google.com/docs/dynamic-links A: The solution for you would be deep linking or custom scheme. Them are practically, the same thing. Here you can find a link how to use them: https://medium.com/flutter-community/deep-links-and-flutter-applications-how-to-handle-them-properly-8c9865af9283
doc_3657
All I do is define two fit functions for different ranges of time. For time<0 I have a constant (which I called line because at first I was using a line). For time>0 I define the sum of two exponentials with different parameters. I then make a guess for these parameters, and feed everything into curve_fit. I'm really just wondering if anyone has any ideas about how to get it to recognize the first peak and fast decay... In my google searches, I can only find examples for fitting simple data (such as a single exponential or polynomial). I may be approaching this completely wrong, any help would be greatly appreciated. Thanks! Also, I would attach plots of what I get but this is my first post and I have no reputation so it won't let me... Here is a link to the data: http://www.lehigh.edu/~ivb2/teaching/smp/current/DecayData.txt Here is the code: #!/usr/bin/env python import numpy as np from scipy import optimize from scipy.optimize import curve_fit import matplotlib.pyplot as plt def line(x, *p): return p[0] def exponential(x, *p): return p[0] * np.exp(p[1] * x) + p[2] #Fit function (neg exp in this case) def fitfunc(time, *p): tempArray = np.empty_like(time) tempArray[time <= 0] = line(time, p[6]) tempArray[0 < time] = exponential(time, p[0], p[1], p[2]) + exponential(time, p[3], p[4], p[5]) return tempArray #Read in the data to 3 arrays time, decay1, decay2 = np.loadtxt('DecayData.txt', unpack=True) #An initial guess for the fit parameters guess = np.array([5e-2, -2500, 0, 5e-2, -2000, 0, 0]) #Fits the functions using curve_fit popt, pcov = curve_fit(fitfunc, time, decay1, guess) print popt fig = plt.figure() ax = fig.add_subplot(111) ax.plot(time, decay1) ax.plot(time, fitfunc(time, *popt)) plt.show() A: I see two problems: * *in fitfunc you write tempArray[time <= 0] = line(time, p[6]) tempArray[0 < time] = exponential(time, p[0], p[1], p[2]) + exponential(time, p[3], p[4], p[5]) but the size of the arrays are not the same on the two sides of the equalities. I think on the second line the times are not good; I've replaced it with tempArray[time <= 0] = line(time[time<=0], p[6]) tempArray[0 < time] = exponential(time[0<time], p[0], p[1], p[2]) + exponential(time[0<time], p[3], p[4], p[5]) * *your initial guess for p[1] if very false, I've replaced -2500 by -250000 With these two changes, it works fine on my computer. JPG
doc_3658
I followed the tutorials of "http://www.raywenderlich.com/12065/how-to-create-a-simple-android-game" which doesn't include a "Game Over" in it and I'm finding it hard to add one since I'm new to android programming. private void checkForCollisionsWithTowers(Ring ring) { Stack<Ring> stack = null; Sprite tower = null; if(ring.collidesWith(mTower1) && (mStack1.size() == 0 || ring.getmWeight() < mStack1.peek().getmWeight())) { stack = mStack1; tower = mTower1; } else if(ring.collidesWith(mTower2) && (mStack2.size() == 0 || ring.getmWeight() < mStack2.peek().getmWeight())) { stack = mStack2; tower = mTower2; } else if(ring.collidesWith(mTower3) && (mStack3.size() == 0 || ring.getmWeight() < mStack3.peek().getmWeight())) { stack = mStack3; tower = mTower3; } else { stack = ring.getmStack(); tower = ring.getmTower(); } ring.getmStack().remove(ring); if(stack != null && tower !=null && stack.size() == 0) { ring.setPosition(tower.getX() + tower.getWidth()/2 - ring.getWidth()/2, tower.getY() + tower.getHeight() - ring.getHeight()); } else if(stack != null && tower !=null && stack.size() > 0) { ring.setPosition(tower.getX() + tower.getWidth()/2 - ring.getWidth()/2, stack.peek().getY() - ring.getHeight()); } stack.add(ring); ring.setmStack(stack); ring.setmTower(tower); } } A: private void checkForCollisionsWithTowers(Ring ring) { Stack<Ring> stack = null; Sprite tower = null; if (ring.collidesWith(mTower1) && (mStack1.size() == 0 || ring.getmWeight() < ((Ring) mStack1.peek()).getmWeight())) { stack = mStack1; tower = mTower1; } else if (ring.collidesWith(mTower2) && (mStack2.size() == 0 || ring.getmWeight() < ((Ring) mStack2.peek()).getmWeight())) { stack = mStack2; tower = mTower2; } else if (ring.collidesWith(mTower3) && (mStack3.size() == 0 || ring.getmWeight() < ((Ring) mStack3.peek()).getmWeight())) { stack = mStack3; tower = mTower3; } else { stack = ring.getmStack(); tower = ring.getmTower(); } ring.getmStack().remove(ring); if (stack != null && tower !=null && stack.size() == 0) { ring.setPosition(tower.getX() + tower.getWidth()/2 - ring.getWidth()/2, tower.getY() + tower.getHeight() - ring.getHeight()); } else if (stack != null && tower !=null && stack.size() > 0) { ring.setPosition(tower.getX() + tower.getWidth()/2 - ring.getWidth()/2, ((Ring) stack.peek()).getY() - ring.getHeight()); } stack.add(ring); ring.setmStack(stack); ring.setmTower(tower); isGameOver(); } private void isGameOver() { if(mStack3.size() == 3){ Font main_font = FontFactory.create(this.getFontManager(), this.getTextureManager(), 256, 256, BitmapTextureFormat.RGBA_8888, TextureOptions.BILINEAR_PREMULTIPLYALPHA, Typeface.DEFAULT, 60, true, Color.BLACK_ABGR_PACKED_INT); main_font.load(); Text gameOverText = new Text(0, 0, main_font, "GameOver", this.getVertexBufferObjectManager()); gameOverText.setPosition(CAMERA_WIDTH/2 - gameOverText.getWidth()/2, CAMERA_HEIGHT/2 - gameOverText.getHeight()/2); scene.attachChild(gameOverText); scene.clearTouchAreas(); } }
doc_3659
Because I will run it on zapier.com it receives the link from a specific service, and sends it to my channel via telegram bot, it does not matter which language it is used (javascript or python), and this is an example of that but this example is to send a text only, I want it to download a video from the url and send it as well This example by python: detail = input_data.get('detail', 'No Detail') if detail != 'No Detail': detail = detail.replace("<p>", "").replace("</p>", "") text = f""" A New prodcut has been Released (<a href="{input_data.get('product_url', 'No URL')}">{input_data.get('name', 'No title')}</a>) <pre> {input_data.get('price', 'No Price Yet')}</pre> <b><i>{detail}</i></b> With """ url = f"https://api.telegram.org/botYOUR_API_KEY/sendMessage?chat_id=@YOUR_CHANNEL_USERNAME&parse_mode=HTML&text={text}" res = requests.get(url) I use this article, it serves me perfectly, but with sending the video by downloading it from the url This ARTICLE
doc_3660
<html><body> <script type="text/javascript" src="/aes.js" ></script> <script>function toNumbers(d) {var e=[]; d.replace(/(..)/g,function(d){e.push(parseInt(d,16))}); return e } function toHex() {for(var d=[],d=1==arguments.length&&arguments[0].constructor==Array?arguments[0]:arguments,e="",f=0;f<d.length;f++) e+=(16>d[f]?"0":"")+d[f].toString(16); return e.toLowerCase() } var a=toNumbers("f655ba9d09a112d4968c63579db590b4"),b=toNumbers("98344c2eee86c3994890592585b49f80"),c=toNumbers("5cb1c0309e553acda177d912f21ac485"); document.cookie="__test="+toHex(slowAES.decrypt(c,2,a,b))+"; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/"; location.href="http://ksos.0fees.us/pgm_list.php?day=1&hall=A&ckattempt=1"; </script> <noscript>This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support</noscript> </body></html> Following is my request to server for getting response public String makeServiceCall(String url, int method, List<NameValuePair> params){ try{ DefaultHttpClient httpclient = new DefaultHttpClient(); HttpEntity httpentity = null; HttpResponse httpresponse = null; if (method == POST) { HttpPost httppost = new HttpPost(url); httppost.setHeader("User-Agent", ua); httppost.setHeader("Accept", "application/json"); if(params!=null){ httppost.setEntity(new UrlEncodedFormEntity(params)); } httpresponse = httpclient.execute(httppost); } else if(method == GET){ if(params!=null){ String paramString = URLEncodedUtils.format(params, "utf-8"); url += "?" + paramString; } HttpGet httpget = new HttpGet(url); // HttpPost httppost = new HttpPost(url); httpget.setHeader("User-Agent", ua); httpget.setHeader("Accept", "application/json"); httpresponse = httpclient.execute(httpget); } httpentity = httpresponse.getEntity(); is = httpentity.getContent(); }catch(UnsupportedEncodingException e){ e.printStackTrace(); }catch (ClientProtocolException e) { e.printStackTrace(); }catch (IOException e) { e.printStackTrace(); } try{ BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"),8); // BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine())!= null) { sb.append(line+"\n"); } is.close(); response = sb.toString(); }catch(Exception e){ Log.e("Buffer Error", "Error : "+e.toString()); } return response; } I've tried by setting and not setting setHeader for user agent. The php part looks as follows: $q=mysql_query("SELECT ..........."); if(!empty($q)){ while($row=mysql_fetch_assoc($q)) $pgmlist[]=$row; $response["pgmlist"] = $pgmlist; echo json_encode($response); } else{ $response["success"] = 0; $response["message"] = "No record found"; echo json_encode($response); } A: Atlast found solution... The issue was not with the android or php part. It was the problem with the server. The hosting site which I used, sends cookies to client side which is not handled inside android but is automatically handled by browsers. I used to another hosting site where cookies are not involved and got the needed json output. A: I spent a long time to understand and solve the problem. Firstly, we need to understand that 0fess hosting has anti bot technique which blocks the calls from (none-browser) clients. The main idea of this technique is using a javascript script that checks if the request is coming from a normal web browser then the script encrypts the IP and sets a cookie with key __test and value of the encrypted IP. To solve such a problem we need to run a webview inside our application and request any page from the our 0fees site. then we can intercept the response and get the cookie. after that, we can use this cookie as a request header in our http rest requests. This is a sample code WebView browser=new WebView(getContext()); browser.getSettings().setJavaScriptEnabled(true); browser.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url){ final String cookies = CookieManager.getInstance().getCookie(url); Log.d("any", "All the cookies by me in a string:" + cookies); HttpPost httppost = new HttpPost("http://ksos.0fees.us/pgm_list.php"); httppost.setHeader("Accept", "application/json"); httppost.setHeader("Cookie", cookies); //continue your request paramters } } ); browser.loadUrl("http://ksos.0fees.us/");
doc_3661
@app.route("/contact", methods = ['GET', 'POST']) def contact(): form = PayRoll_Form() if request.method == 'POST': if form.validate() == False: flash('All fields are required.') return render_template('contact.html', form = form) else: N = engine.execute(PayRoll.insert(), Name = request.form['Name'], CreateUserPK = request.form['CreateUserPK'], PeriodStart = request.form['PeriodStart'], PeriodStop = request.form['PeriodStop'], DueDate = request.form['DueDate']) session.add(N) session.commit() flash('Submited') return redirect("/contact") if request.method == 'GET': return render_template('contact.html', form = form) if __name__ == '__main__': app.run(debug=True,port=5000) A: You seem to be mixing possible implementations here; the line N = engine.execute(... actually executes the INSERT against the DB directly. Trying to add the result to the current session and commit that session doesn't make sense. You would only use those methods if you had an ORM object that you made changes to (or created) and wanted to have committed, but you've already done this in the line referenced above. A: Solved the issue here: @app.route("/contact", methods = ['GET', 'POST']) def contact(): form = PayRoll_Form() if request.method == 'POST': if form.validate() == False: flash('All fields are required.') return render_template('contact.html', form = form) else: ins = PayRoll.insert().values( Name = request.form['Name'], CreateUserPK = request.form['CreateUserPK'], PeriodStart = request.form['PeriodStart'], PeriodStop = request.form['PeriodStop'], DueDate = request.form['DueDate']) result = connection.execute(ins) flash('Submited') return redirect("/contact") if request.method == 'GET': return render_template('contact.html', form = form) if __name__ == '__main__': app.run(debug=True,port=5000)
doc_3662
ERROR: Exception: Traceback (most recent call last): File "c:\users\hp\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\urllib3\response.py", line 425, in _error_catcher yield File "c:\users\hp\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\urllib3\response.py", line 507, in read data = self._fp.read(amt) if not fp_closed else b"" File "c:\users\hp\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\cachecontrol\filewrapper.py", line 62, in read data = self.__fp.read(amt) File "c:\users\hp\appdata\local\programs\python\python38\lib\http\client.py", line 454, in read n = self.readinto(b) File "c:\users\hp\appdata\local\programs\python\python38\lib\http\client.py", line 498, in readinto n = self.fp.readinto(b) File "c:\users\hp\appdata\local\programs\python\python38\lib\socket.py", line 669, in readinto return self._sock.recv_into(b) File "c:\users\hp\appdata\local\programs\python\python38\lib\ssl.py", line 1241, in recv_into return self.read(nbytes, buffer) File "c:\users\hp\appdata\local\programs\python\python38\lib\ssl.py", line 1099, in read return self._sslobj.read(len, buffer) socket.timeout: The read operation timed out A: if you are using conda first run: conda config --set ssl_verify no after that modify your default timeout: pip --default-timeout=900 install tensorflow Note: conda config --set ssl_verify no only applicable for conda if you are not on conda env skip this step. A: try: pip --default-timeout=300 install tensorflow This has worked for me as commented by Kenan since I'm using a non-conda environment.
doc_3663
This is my query without trying to preserve the final order: SELECT path.*, network_link.v0prt FROM (SELECT * // Need order preserved from this one FROM shortest_path_shooting_star( 'SELECT gid as id, source::integer, target::integer, distance::double precision as cost, x1, y1, x2, y2, rule, to_cost FROM network_link as net ORDER BY net.gid', 9, 1, false, false)) as path LEFT OUTER JOIN (SELECT DISTINCT gid, v0prt FROM network_link) as network_link ON (network_link.gid=path.edge_id); Any insight would be great. Thanks. And my attempt to add an indexing value and ORDER BY (which doesn't work). SELECT path.*, network_link.v0prt FROM (SELECT incr(0) as idx, * FROM shortest_path_shooting_star( 'SELECT gid as id, source::integer, target::integer, distance::double precision as cost, x1, y1, x2, y2, rule, to_cost FROM network_link as net ORDER BY net.gid', 9, 1, false, false)) as path LEFT OUTER JOIN (SELECT DISTINCT gid, v0prt FROM network_link) as network_link ON (network_link.gid=path.edge_id) ORDER BY idx; A: To preserve the order returned by shortest_path_shooting_star (if it gives no other way), you can use the window function row_number to keep track of the original order, and them ORDER BY its result: SELECT path.*, network_link.v0prt FROM (SELECT row_number() OVER() AS row_number, * FROM shortest_path_shooting_star( 'SELECT gid as id, source::integer, target::integer, distance::double precision as cost, x1, y1, x2, y2, rule, to_cost FROM network_link as net ORDER BY net.gid', 9, 1, false, false)) as path LEFT OUTER JOIN (SELECT DISTINCT gid, v0prt FROM network_link) as network_link ON (network_link.gid=path.edge_id) ORDER BY path.row_number; UPDATE: From PostgreSQL version 9.4 and newer, a better method would be using WITH ORDINALITY: SELECT path.*, network_link.v0prt FROM shortest_path_shooting_star( 'SELECT gid as id, source::integer, target::integer, distance::double precision as cost, x1, y1, x2, y2, rule, to_cost FROM network_link as net ORDER BY net.gid', 9, 1, false, false) ) WITH ORDINALITY AS path LEFT OUTER JOIN (SELECT DISTINCT gid, v0prt FROM network_link) as network_link ON (network_link.gid=path.edge_id) ORDER BY path.ordinality;
doc_3664
Command /usr/bin/codesign failed with exit code 1 Here is what I already did for trying to fix this: * *set the bundle identifier to com.server.pgmname *set the code signing to "Any Iphone OS Device" *set the Code Signing Identity to my Distribution identity. The error only occurs when I try to build on my device, on the simulator everything works fine. Do you have any suggestions? A: Just troubleshooted this same issue. I'd created a resources folder with my icons inside, then added it to my project via right-click > Add Files > [select resources folder]. Apparently this is a bad idea. Instead create a new group in your project (called "Resources" in my case), and then right click > add files to that and then choose the individual files. Project built immediately. A: I had the exact same error, and tried everything under the sun, including what was suggested elsewhere on this page. What the problem was for me was that in Keychain Access, the actual Apple WWDR certificate was marked as "Always Trust". It needed to be "System Defaults". That goes for your Development and Distribution certificates, too. If any of them are incorrectly set to "Always Trust", that can apparently cause this problem. So, in Keychain Access, click on the Apple Worldwide Developer Relations Certificate Authority certificate, select Get Info. Then, expand the Trust settings, and for the combo box for "When using this certificate:", choose "System Defaults". Sigh: for those insistent on downvoting this answer, I am not claiming this to be the only solution for this problem. It's one solution. It may not work for you. There are multiple reasons for this codesign failure. A: For me, I just updated to Xcode 8, and converted my Swift 2.2 code to Swift 3 code, and I got errors in the Unit Testing and UI Testing. I just cleaned and then all the errors disappeared. A: I had the exact same problem and this did the trick for me: Xcode > Preferences > Accounts > View Details > And just refresh the Provisioning Profile Seems like the accounts in Xcode were not updated with the latest provisioning profiles so a quick refresh sorted this out. A: For anyone with this problem in the future (who doesn't want to rebuild their project), an additional question to ask is whether you have a space in your product name. I'd recommend going through your properties (right-click -> get info) of your project and your target. For my project, the only place that a space was needed was in the plist for the bundle display name. A: After hours of googling and trying out different things, this is what fixed it for me: * *Make sure there are no certificates in the System > Certificates tab on Keychain Access. Remove all duplicate certificates from there. *Install the WWDR intermediate certificate under certificates from the provisioning portal, in addition to the developers certificates and make sure you see it in the Login > Certificates tab on Keychain Access. A: Very often the error /usr/bin/codesign failed with exit code 1 occurred in case the user has no file extensions for texture files in Models.scnassets folder. macOS very often generates a files with hidden extensions. For example: you have a file myTexture but it must include an extension as well – myTexture.png. A: Feel the need to share this, even though it's ridiculous. I'd set up a second developer account on my Mac and couldn't codesign anything. The error was "the user cancelled the operation". A simple reboot fixed this for me. A: I got this error the very first time I tried to make a provisioning profile by following the Provisioning Assistant and it turns out they fail to mention the WWDR Intermediate Certificate. I installed it and it worked fine for me. A: I had this same problem and couldn't figure it out for a long time. I tried everything on this page and others and it still didn't work. But eventually, I did find a fix. For this to work, make sure Xcode is not running. After you've closed Xcode, open Terminal and type in the command: xattr -rc /[The File Directory of your project found in the File Inspector of your .xcodeproj file in Xcode]/ Obviously don't put the text in brackets, just replace it with what it says. Hit enter. Don't worry if nothing shows up below the command, it didn't for me. After that, you can close out of Terminal and open Xcode. Now everything should be fine. Note: It might take a little longer to run your project, but just wait it out. Also note: Don't downvote this answer because it doesn't work. This is one way to fix it that worked for me, but it might not work for you because you might have something else that is broken. A: Here is my way to resolve: * *Open keychain access, select your iOS certificate, Delete private key *Then go back to xCode, you will see warning warning message and "Revoke" button, click it and error resolved. A: I was fighting for about 2-3 hours to codesign a project with Parse API. It turned out that the embedded frameworks caused the problem. Make sure you set "Code sign on copy" (see picture). If does not work delete the Parse and Bolts frameworks from the list and remove them from your project then add them again. A: What worked for me was to realize that Xcode did not have access to the certificates. Please check that your certs are accessible by Xcode. Go to Keychain Access -> Certificates -> Open the Cert and double click on the private key -> Select Access Control A: Most answers will tell you that you have a duplicate certificate. This is true for my case but the answers left out how to do it. For me, my account expired and I have to get a new certificate and install it. Next, I looked at Keychain and removes the expired certificate but still got the error. What works for me is actually searching for "iPhone" in Keychain and removing all expired certificates. Apparently, some of it are not shown in System/Certificates or login/Certificates. Hope this helps! A: In my case, I had an extra expired distribution certificate in my keychain - I deleted the certificate from KeyChain Access and the compilation started working again. A: If you're using phonegap/cordova: I got this when building from Cordova but the solution for me was much simpler. A permissions issue. Just set the files to correct permissions chmod -R 774 ./projectfolder And then set ownership chown -R youraccname:staff ./projectfolder A: Some of the answers above allude to the problem but don't clearly spell out the steps to correct it. Here is my attempt at after it has become super frustrating which seems to have worked for me so far : The problem is caused because there is duplicate certificates in your Apple Developer portal or potentially in your machine. I haven't had any negative consequences from doing this and its worked so far. * *Close Xcode! *You have to remove the existing certs from your developer account visit : https://developer.apple.com/account/ios/certificate/development/ and select development account ( there should be multiple certs) I revoked each one by clicking on them and selecting revoke. 2.remove certs from your keychain on your Mac * *Open Keychain app by pressing clover+space and typing in keychaing and pressing enter *Search in the top right hand corner for "developer" *Select the potential duplicate keys and export/delete them so they aren't in the list. *Lastly regenerate your certs in XCode and rebooot * *Reopen xcode *regenerate a new cert by going to project -> General --> Signing *reselect your "Team Account" * *a new cert should be generated *Reboot for good measure - and enjoy being free from this bug ( which Apple should really sort out, if it was at all possible to replicate easily) A: I recently had the same issue. Keychain Access was the culprit. Steps: Go -> Utilities -> Keychain Access Keychain Access: Edit -> Change Password for Keychain "login" Change the password. Close and reopen Xcode, Clean & build again. If option - Change Password for Keychain "login" - is greyed out: * *Make sure under Keychains selected -> login and the padlock icon is open. To open the padlock you need the keychain password. If you do not know the password, go to Step 2. *With padlock unlocked and still option is greyed out. As last resort: Keychain Access -> Preferences Preferences: "Reset My Default Keychains" Reset the login. However be careful as stored keychains will be removed and you may have re-login on other connected devices as well. A: Try finding out the details of this error in the "Build Results" view where the error is shown. On the right side of the line with the error message there is an icon with several lines. This will show you some helpful details. This way I found out for me it was a duplicate iPhone developer certificate in my keychain - one of which had been expired. Maybe search for "iphone" in your keychain (select "All Items" category first). A: One solution more works with me, If you installed two versions of XCode and you install the second without uninstalling the first in the same directory (/Developer/), you did it wrong. So the solution that works for me was: 1 - Uninstall the current Xcode version with the command sudo /Developer/Library/uninstall-devtools --mode=all. 2 - Install the first Xcode version you had first. 3 - Again sudo /Developer/Library/uninstall-devtools --mode=all. 4 - Then, all is clean and you are able to install the version you want. More things: maybe you need to restart the computer after install the Xcode or even (in some cases) install two times the Xcode. I hope I works it take me a lot of time to know that, good luck!!! A: The solution that worked for me is related to (what I think is) a change of path behavior after upgrading to Xcode 4.2: You can no longer manually enter "armv6 armv7" but must enter $(VALID_ARCHS) instead: both for the Architectures and Valid Architectures fields under the Architectures section in your project's Build Settings pane. Xcode will automatically replace the statement with 'armv6 armv7'. This string looks exactly the same as if you would have typed it in manually but nevertheless point to the actual correct paths that will be generated along with your build, ...or at least this is my take on it :P Unrelated, we used to have "armv6 armv7" as well under Other Signing Flags and now took that out and it works fine. This must be just an extra. Thanks and happy hacking. Gon A: I went to Key Access, selected the private key, and added XCode to the list of apps that can access it. That worked for me A: If anyone uses Xcode ver. 3.x.x and upgrades from Mac OS 10.7 to 10.8, dev. tools will work just fine except the new codesign binary .. To fix that just copy the old codesign and codesign_allocate binaries (I hope you have backup) to /usr/bin/ folder and rename or backup the new one. A: I had special characters in the project name,renaming it to remove the characters, question marks, and insuring a developer certificate was enabled fixed the issue. A: When I experienced this error, it was due to having been in Keychain Access, and choosing 'Disallow' when asked whether I wanted to let the program access a saved password. Going back in and selecting 'Allow' and typing my system password fixed the problem in XCode. A: For me the problem was HTTP proxy A: Here is how I solved the same problem. It may help someone. I deleted the Development Provisionning Profile (that I was using) from the server, then created one with a slightly different name. I used it and it worked. A: This issue happened for me when I had multiple targets in one project, and I changed the CFBundleExecutable plist property to something other than the target's name. So, for example, I had the following targets in one project: * *SomeApp *SomeApp WatchKit Extension *SomeApp WatchKit App *SomeApp Today Widget *SomeApp for OS X (this is the target where the codesign error happens) SomeApp for OS X had its CFBundleExecutable property set to just SomeApp, which not only conflicted with the first target called SomeApp but was different from the target it was meant for. Changing SomeApp for OS X to SomeApp and then renaming the first target worked fine for me. A: For me I had code coverage enabled on the scheme of a framework rather than it's corresponding test scheme. Disabling the code coverage sorted the problem. A: A very simple answer to this very-complicated question. It involves no knowledge of code-signing and everything connected with it. Take an old app that is not needed any more. Make sure it works, then replace its code with that of the new app having the code-signing error. The old app should now work fine, accomplishing what you wanted with the new app. Only down side: the working app has the title of the old one. A: This issue occured when I added a folder named "Resources" as "Create folder references", and when I renamed "Resources" to another random name, this issue disappeared. Hope it will help. A: Spent hours figuring out the issue, it's due very generic error by xcode. One of my frameworks was failing with codesign on one of the laptop with below error : XYZ.framework : unknown error -1=ffffffffffffffff Command /usr/bin/codesign failed with exit code 1 However, there is no Codesign set for this framework and still it fails with codesign error. Below is the answer: I have generated new development certificate (with new private key) and installed on my new mac. this error is not relevant to XYZ.frameowrk. Basically codesign failed while archiving coz we newly created certificate asks "codesign wants to sign using key "my account Name" in your keychain" and the buttons Always Allow, Deny and Allow. Issue was I never accepted it. Once I clicked on Allow. It started working. Hope this helps. A: In Xcode: Go to Preferences Logout of the current user. Close Xcode In Keychain: Go to Login and All items - Sort by kind - remove "Apple Worldwide Developer Relation Certification Authority" - remove "Developer ID Certification Authority" - remove "iPhone Developer ...." Open Xcode Go to Preferences and Login to you user apple account - This will reload your developer certificates you previous deleted Rebuild the project (Should be a successful build) Run the build on your native device A: I ran into this error code with an existing project that suddenly wouldn't sign after I added three PNG files to the project. It turns out that one of the PNG files was the culprit. All three PNG files were created with Pixelmator, should have the same structure. But it simply wouldn't sign with one of the images. Remove the image, it worked. Add it again, failed. Rename the image, still failed. I wound up building a new image from scratch, all fixed. A: That worked for me was to review all the certificates on KeyChain to be as Use systems Default, all the certificates must to be with this configuration. Was the only thing that worked, and also be shure that no certificates are repeated. A: For me, I just had to delete "Derived Data" in xcode Open Xcode (12.3) -> Xcode -> Preferences -> Locations -> Click DerivedData location arrow -> Delete "DerivedData" folder -> Clean and build A: I just created a new project, copied all my classes and resources and then it worked! A: The real FIX for me was: The only problem is I had my Provisioning Profile "invalid" in member center, because that old provisioning profile was generated by old certificate. Once you regenerate your certificate, or regenerate your Provisioning Profile, make sure you download them and feed them to Xcode. A: Following steps worked for me * *Cleaned my device from all provision profiles *Cleaned OSx Keychain from my Dev iOS Certificates & Keys *From Apple Developer Program regenerated Certificate / Provisioning profile *Installed Provisioning profile into my Xcode project *Fixed Team issues in Project Target *Configured appropriate Code Signing Identity in Project/Target/Build Settings A: All I had to do is to disable automatic signing, then re-nable it, and choose my team identity. And it worked! A: Tried out most of the solutions here and what helped me was cleaning the build folder in XCode using: Product - > Clean and rebuild the project A: Steps to Fix this issue: * *Go to Key Chain Access. *Select the i-Phone Developer certificate. *Lock the Certificate.( Menu bar - Lock Button) *Give the Machine Password. *Unlock the Certificate. Now clean and rebuild the project, this issue will resolve. A: I have solved this issue by following steps. * *open keychain access, type "deve" *delete the selected item as in the attached image *open xcode and it will ask password type system password. Hope, it will help.
doc_3665
A: You need to configure Http Caching in IIS for your content folders. There is nothing you should do in the code (unless you are using bundling). The easiest way of doing this would be to open HTTP Response Headers section in IIS Manager for that folder, click Set Common Header... and enable the Expire Web Content section and specify it to expire, for example, after 1 hour. A: I concur that it is important to first get more information on caching and what options and budget you have available: http://visualstudiomagazine.com/articles/2011/09/01/pfint_distributed-caching.aspx You may also want to take a peak at NCache: http://www.alachisoft.com/ncache/
doc_3666
Now I need to verify if all the description are available in the table or not, if all the description is not available in the table then an error has to be raised with the missing description. For example: Java application is sending message as 'tree', 'flower', 'plant'. In SQL Server, there is a column description - I need to check if 'tree', 'flower', 'plant' are available or not. If anyone is unavailable like 'plant' is not there in the table then raise an error that 'plant' is unavailable. Could you please help me with this? A: You can try to left join the table to the descriptions. If there is no match in the table, the columns from that table remain NULL, so you can filter only for NULLs. Like that you have a list of descriptions, that don't exist. SELECT i.description FROM (SELECT 'tree' UNION ALL SELECT 'flower' UNION ALL SELECT 'plant') i LEFT JOIN elbat t ON t.description = i.description WHERE t.description IS NULL; A: u meant somethin like this? if not exists (select 1 from table1 where description='plant') begin RAISERROR('your custom error',16,1) end A: ALTER FUNCTION [dbo].[SplitToItems] ( @pString NVARCHAR(3999), --!! DO NOT USE MAX DATA-TYPES @pDelimiter CHAR(1) ) RETURNS @Items TABLE (ItemNumber INT, Item NVARCHAR(100)) BEGIN IF Replace(@pString, '''', '') = '' SET @pString = ''; WITH E1 (N) AS ( SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 ), E2 (N) AS ( SELECT 1 FROM E1 a, E1 b ), E4 (N) AS ( SELECT 1 FROM E2 a, E2 b ), cteTally (N) AS ( SELECT TOP (ISNULL(DATALENGTH(@pString), 0)) ROW_NUMBER() OVER ( ORDER BY ( SELECT NULL ) ) FROM E4 ), cteStart (N1) AS ( SELECT 1 UNION ALL SELECT t.N + 1 FROM cteTally t WHERE SUBSTRING(@pString, t.N, 1) = @pDelimiter ), cteLen (N1, L1) AS ( SELECT s.N1, ISNULL(NULLIF(CHARINDEX(@pDelimiter, @pString, s.N1), 0) - s.N1, 8000) FROM cteStart s ) INSERT INTO @Items SELECT ItemNumber = ROW_NUMBER() OVER ( ORDER BY l.N1 ), Item = SUBSTRING(SUBSTRING(@pString, l.N1, l.L1), 1, 100) FROM cteLen l RETURN END SELECT * FROM dbo.SplitToItems('''tree'',''flower'',''plant''', ',')
doc_3667
Supposed solution: proxy swf file loaded in page with widget:// or file:// or chrome-extension:// protocol which loads into itself swf file located on http server. local swf bridge conects its own external interface to http swf file external interface. This solution used in youtube movies, so you can embed any youtube movie into local page and it will be shown and played fine; At the end we can get working soundmanager2 www.schillmania.com/projects/soundmanager2/ opened localy (file:// protocol), which can load and play music and video from internet. I need proxy for this version http://github.com/scottschiller/SoundManager2/tree/V2.95b.20100323/src; Some relative help.adobe.com/en_US/as3/dev/WS5b3ccc516d4fbf351e63e3d118666ade46-7e5c.html How do I call a Flex SWF from a remote domain using Flash (AS3)? I need this to play music in opera extension (using widget:// protocol) for my project http://seesu.me/ to let users play music without setting up special permissions A: Hopefully this will get you on track. http://livedocs.adobe.com/flash/9.0/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00000349.html
doc_3668
$(".temp").click(function() { $('#temperature').empty(); $("#temperature").append(temp.main.temp + " <a class='temper' href='#'>C</a>"); $(".temper").click(function() { $('#temperature').empty(); $('#temperature').append(data.main.temp +" <a class='temp' href='#'>F</a>"); }); }); A: I guess you are about to use live jquery event, this can help : $(document).on("click", ".temp", function() {}); $(document).on("click", ".temper", function() {}); A: Check this Fiddle it's working example but missing this part (temp.main.temp): $( document ).ready(function() { $(document).on("click", ".temp", function() { $('#temperature').empty(); $("#temperature").append(" <a class='temper' href='#'>C</a>"); }); $(document).on("click", ".temper", function() { $('#temperature').empty(); $("#temperature").append(" <a class='temp' href='#'>F</a>"); }); }); https://jsfiddle.net/Kanzari/n38xs8sn/2/ A: In this line: $("#temperature").append(temp.main.temp + " <a class='temper' href='#'>C</a>"); you are adding some html content dynamically. So use: $(document).on('click', '.temper', function(){ }); instead of static listener i.e. $(".temper").click() because this kind of listener works for static html only. A: why you wrote the code of temper.click inside the temp.click function? correct it as : $(".temp").click(function(){ $('#temperature').empty(); $("#temperature").append(temp.main.temp+" <a class='temper' href='#'>C</a>"); }); $(".temper").click(function(){ $('#temperature').empty(); $('#temperature').append(data.main.temp+" <a class='temp' href='#'>F</a>" ); });
doc_3669
return ( <View> <Text>{value} participants</Text> <Slider style={{ height: 40 }} minimumValue={eventDetail.minParticipants} maximumValue={eventDetail.maxParticipants + 10} minimumTrackTintColor='#000000' maximumTrackTintColor='#FF0000' step={1} onValueChange={value => setMaxParticipantsHandler(value)} /> </View> ); Once a value changes in the sliders, the function executes sending the new value. const [value, setValue] = useState(eventDetail.maxParticipants); const setMaxParticipantsHandler = value => { setValue(value); console.log('reading: ' + value); setTimeout(() => { console.log('sending: ' + value); }, 5000); }; But when I test this, the setTimeout() executes multiple times. The console log throws this: reading: 9 sending: 9 reading: 8 reading: 7 reading: 6 reading: 5 reading: 4 reading: 4 sending: 8 sending: 7 sending: 6 sending: 5 sending: 4 sending: 4 I want to delay the execution and dispatch only one value to the API (the last one instead of several); I'm figuring out if I need to do this here on the screen or do the logic on the redux-store, like first to save the value on the state, and if it is the same, I don't ask the API, but if the value of the state is different I do send an API request. A: Found the solution. The Slider component already has a prop that only triggers the callback when you're done sliding: onSlidingComplete. The prop I was using is good for other user cases, like updating the counter.
doc_3670
#include <windows.h> int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { MessageBox(NULL, "Trollface", "Title", MB_OK); return 0; } That's great and all, it shows a messagebox, but there is a pesky console behind it. How can I remove the console? A: You have probably created a console project. You can detach from a console using FreeConsole().
doc_3671
I can open the device (/dev/i2c-0), but I shaw that all i2c_smbus* functions (i2c_smbus_write_word_data, i2c_smbus_read_word_data etc..) are not declared in any i2c header. i2c Documentation said that these functions are declared in linux/i2c-dev.h header but in my centos7 are not there. I was looking for them in all headers but are not defined in any file. Any idea about why are not defined there and where are they? Here is my code: #include <stdio.h> #include <string.h> #include <errno.h> #include <linux/i2c-dev.h> #include <linux/i2c.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <memory.h> #include <fcntl.h> #include <errno.h> #include <sys/io.h> #include <sys/ioctl.h> int main() { cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!! int Address = 0x39; //Slave addr char i2c_dev_node_path[] = "/dev/i2c-0"; int ret_val = 0; /* Open the device node for the I2C adapter of bus 0 */ i2c_dev_node = open(i2c_dev_node_path, O_RDWR); if (i2c_dev_node < 0) { cout << "EROR Unable to open device node." << endl; return -1; } int i2c_dev_address = 0x39; ret_val = ioctl(i2c_dev_node,I2C_SLAVE,i2c_dev_address); if (ret_val < 0) { perror("Could not set I2C_SLAVE."); cout << "EROR Could not set I2C_SLAVE." << endl; return -1; } cout << "ALL OK!!!!!" << endl; int retVal = i2c_smbus_read_word_data ( i2c_dev_node , 0xac ); } A: Copy i2c-smbus.ko in /lib/modules/4.8.28-release/kernel/drivers/i2c/i2c-smbus.ko yum install libi2c-dev
doc_3672
A: Check this link: How to add wartermark text/image to a bitmap in Windows Store app Or better use Win2D library (you can find it on NuGet) and snippet like this: CanvasDevice device = CanvasDevice.GetSharedDevice(); CanvasRenderTarget offscreen = new CanvasRenderTarget(device, 500, 500, 96); cbi = await CanvasBitmap.LoadAsync(device, "mydog.jpg"); using (var ds = offscreen.CreateDrawingSession()) { ds.DrawImage(cbi); var format = new CanvasTextFormat() { FontSize = 24, HorizontalAlignment = CanvasHorizontalAlignment.Left, VerticalAlignment = CanvasVerticalAlignment.Top, WordWrapping = CanvasWordWrapping.Wrap, FontFamily = "Tahoma" }; var tl = new CanvasTextLayout(ds, "Some text", format, 200, 50); // width 200 and height 50 ds.DrawTextLayout(tl, 10, 10, Colors.Black); tl.Dispose(); } using (var stream = new InMemoryRandomAccessStream()) { stream.Seek(0); await offscreen.SaveAsync(stream, CanvasBitmapFileFormat.Png); BitmapImage image = new BitmapImage(); image.SetSource(stream); img.Source = image; }
doc_3673
I cannot get the bootstrap js files to link to my ejs file. I am trying to link the js files to index.ejs. I have this code: <script src="jquery.min.js"></script> <script src="popper.min.js"></script> <script src="bootstrap.min.js"></script> They are in the same original folder, so why doesn't this work? Thanks for your help Screenshot of the situation
doc_3674
As a result of my current situation, I set a break-point in an app.js file. And when I hit F5, it tells me... Cannot find runtime 'node' on PATH I am completely lost in understanding and fixing this issue in Visual Studio Code. A: first run below commands as super user sudo code . --user-data-dir='.' it will open the visual code studio import the folder of your project and set the launch.json as below { "version": "0.2.0", "configurations": [ { "type": "node", "request": "launch", "name": "Launch Program", "program": "${workspaceFolder}/app/release/web.js", "outFiles": [ "${workspaceFolder}/**/*.js" ], "runtimeExecutable": "/root/.nvm/versions/node/v8.9.4/bin/node" } ] } path of runtimeExecutable will be output of "which node" command. Run the server in debug mode. A: Had the same issue and in my case it was a problem with a vs code extension. Try running code as: $ code --disable-extensions Once in the editor, I ran my program in the debug mode and worked, and then started code with $ code And it continued working fine. Hope it works for you. A: I had a similar issue with zsh and nvm on Linux, I fixed it by adding nvm initialization script in ~/.profile and restart login session like this export NVM_DIR="$HOME/.nvm" [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm [ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" A: I use /bin/zsh, and I changed vscode to do the same, but somehow vscode still use the path from /bin/bash. So I created a .bash_profile file with node location in the path. Simply run in terminal: echo "PATH=$PATH export \$PATH" >> ~/.bash_profile Restart vscode, and it will work. A: To follow up, I just ran into this as well. When I installed Node.js there was an option that said Add to PATH (Available After Restart). Seems like Windows just needs a restart to make things work. A: Quick fix that works for me. Navigate to the root directory of your folder from command line (cmd). then once you are on your root directory, type: code . Then, press enter. Note the ".", don't forget it. Now try to debug and see if you get the same error. A: Apply a Default Node Version via NVM I'm using macOS Big Sur and setting the default version via nvm fixed this for me by running this command: nvm alias default 16 (change 16 to the version you want as your default). Note that node worked fine in the terminal for me (both with zsh and bash) but not when running via the vscode debugger and I already had the following config in both ~/.zshrc and ~/.bash_profile to load in nvm: export NVM_DIR="$HOME/.nvm" [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm [ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" # This loads nvm bash_completion It wasn't until I set the default Node version that vscode would launch node targets just fine. A: I did which node on my terminal: /usr/local/bin/node and then i added "runtimeExecutable": "/usr/local/bin/node" in my json file. A: I also ran into this error. Restart the PC works for me. A: Do not launch the VS code from the start menu separately. Use $Code . command to launch VS code. Now, create your file with the extension .js and Start debugging (F5) it. It will be executed. Otherwise, restart your system and follow the same process. A: The cause for me receiving this error was trying the new pre-release VSCode JS debugger. If you opted in, change via User settings: "debug.javascript.usePreview": true|false Everything in my normal configuration and integrated terminal was correct and finding executables. I wasted a lot of time trying other things! A: (CMD+SHIFT+P) Shell command: Install 'code' command in PATH should do the trick! A: Just relaunch your project from the termial e.g. yourprojectdir code . A: On OSX and VSCode 1.56.2 all I had to do was to close and restart VSCode and the problem went away. A: For me, the node binary is in PATH and I can run it from the terminal (iTerm or Terminal), and the Terminal apps are set to use zsh If you are on a Mac, with iTerm and Zsh, please use the following VSCode settings for Node to work. After this change, you can get rid of this line from your launch.json config file. (the debug settings in VSCode) "runtimeExecutable": "/usr/local/bin/node" If this doesn't work, make sure you choose the default shell as zsh. To do this, * *Open the command palette using Cmd+Shift+P *Look for the Terminal: Select Default Shell command *Select zsh from the options A: So node got kicked out of path. you can do SET PATH=C:\Program Files\Nodejs;%PATH% Or simply reinstall node to fix this. which ever you think is easiest for you A: i resolved this problem after disable ESLint extention. A: I am on OSX, this did not work for me: code . --user-data-dir='.' but this DID work: code . -data-dir='.' A: This is the solution according to the VS code debugging page. This worked for my setup on Windows 10. "version": "0.2.0", "configurations": [ { "type": "node", "request": "launch", "name": "Launch Program", "program": "${file}" } The solution is here: https://code.visualstudio.com/docs/editor/debugging Here is the launch configuration generated for Node.js debugging A: I also encountered this issue. Did the following and it got fixed. * *Open your computer terminal (not VSCode terminal) and type node --version to ensure you have node installed. If not, then install node using nvm. *Then head to your bash file (eg .bashrc, .bash_profile, .profile) and add the PATH: [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm [ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" *If you have multiple bash files, you ensure to add the PATH to all of them. *Restart your VSCode terminal and it should be fine. A: Mine was more project specific. We use "Auto Reload" to run our launch.json for the backend. The error states the file path of the runtimeExecutable and allows you to open launch.json. In my launch.json case: "runtimeExecutable": "${workspaceFolder}/functions/node_modules/.bin/nodemon" I tried the restarts and answers here originally but no luck, so I manually explored into my functions/node_modules folder and realized .bin was missing. I used my terminal to path into functions like so: cd functions Terminal directory path example: ( ~/OneDrive/Desktop/{project dir covered}/{project dir covered}/functions ) Then I did an npm install using npm i, and now everything is back to normal. Keep in mind, most of these answers are general fixes. If your situtation is more specific, be sure to break it down from the start. Hope this might help others!
doc_3675
In the case where the result is zero or less something happens. So far this seems straightforward - I can just do something like this for each node: if (value <= 0.0f) something_happens(); A problem has arisen, however, after some recent changes I made to the program in which I re-arranged the order in which certain calculations are done. In a perfect world the values would still come out the same after this re-arrangement, but because of the imprecision of floating point representation they come out very slightly different. Since the calculations for each step depend on the results of the previous step, these slight variations in the results can accumulate into larger variations as the simulation proceeds. Here's a simple example program that demonstrates the phenomena I'm describing: float f1 = 0.000001f, f2 = 0.000002f; f1 += 0.000004f; // This part happens first here f1 += (f2 * 0.000003f); printf("%.16f\n", f1); f1 = 0.000001f, f2 = 0.000002f; f1 += (f2 * 0.000003f); f1 += 0.000004f; // This time this happens second printf("%.16f\n", f1); The output of this program is 0.0000050000057854 0.0000050000062402 even though addition is commutative so both results should be the same. Note: I understand perfectly well why this is happening - that's not the issue. The problem is that these variations can mean that sometimes a value that used to come out negative on step N, triggering something_happens(), now may come out negative a step or two earlier or later, which can lead to very different overall simulation results because something_happens() has a large effect. What I want to know is whether there is a good way to decide when something_happens() should be triggered that is not going to be affected by the tiny variations in calculation results that result from re-ordering operations so that the behavior of newer versions of my program will be consistent with the older versions. The only solution I've so far been able to think of is to use some value epsilon like this: if (value < epsilon) something_happens(); but because the tiny variations in the results accumulate over time I need to make epsilon quite large (relatively speaking) to ensure that the variations don't result in something_happens() being triggered on a different step. Is there a better way? I've read this excellent article on floating point comparison, but I don't see how any of the comparison methods described could help me in this situation. Note: Using integer values instead is not an option. Edit the possibility of using doubles instead of floats has been raised. This wouldn't solve my problem since the variations would still be there, they'd just be of a smaller magnitude. A: I've worked with simulation models for 2 years and the epsilon approach is the sanest way to compare your floats. A: Generally, using suitable epsilon values is the way to go if you need to use floating point numbers. Here are a few things which may help: * *If your values are in a known range you and you don't need divisions you may be able to scale the problem and use exact operations on integers. In general, the conditions don't apply. *A variation is to use rational numbers to do exact computations. This still has restrictions on the operations available and it typically has severe performance implications: you trade performance for accuracy. *The rounding mode can be changed. This can be use to compute an interval rather than an individual value (possibly with 3 values resulting from round up, round down, and round closest). Again, it won't work for everything but you may get an error estimate out of this. *Keeping track of the value and a number of operations (possible multiple counters) may also be used to estimate the current size of the error. *To possibly experiment with different numeric representations (float, double, interval, etc.) you might want to implement your simulation as templates parameterized for the numeric type. *There are many books written on estimating and minimizing errors when using floating point arithmetic. This is the topic of numerical mathematics. Most cases I'm aware of experiment briefly with some of the methods mentioned above and conclude that the model is imprecise anyway and don't bother with the effort. Also, doing something else than using float may yield better result but is just too slow, even using double due to the doubled memory footprint and the smaller opportunity of using SIMD operations. A: If it absolutely has to be floats then using an epsilon value may help but may not eliminate all problems. I would recommend using doubles for the spots in the code you know for sure will have variation. Another way is to use floats to emulate doubles, there are many techniques out there and the most basic one is to use 2 floats and do a little bit of math to save most of the number in one float and the remainder in the other (saw a great guide on this, if I find it I'll link it). A: I recommend that you single step - preferably in assembly mode - through the calculations while doing the same arithmetic on a calculator. You should be able to determine which calculation orderings yield results of lesser quality than you expect and which that work. You will learn from this and probably write better-ordered calculations in the future. In the end - given the examples of numbers you use - you will probably need to accept the fact that you won't be able to do equality comparisons. As to the epsilon approach you usually need one epsilon for every possible exponent. For the single-precision floating point format you would need 256 single precision floating point values as the exponent is 8 bits wide. Some exponents will be the result of exceptions but for simplicity it is better to have a 256 member vector than to do a lot of testing as well. One way to do this could be to determine your base epsilon in the case where the exponent is 0 i e the value to be compared against is in the range 1.0 <= x < 2.0. Preferably the epsilon should be chosen to be base 2 adapted i e a value that can be exactly represented in a single precision floating point format - that way you know exactly what you are testing against and won't have to think about rounding problems in the epsilon as well. For exponent -1 you would use your base epsilon divided by two, for -2 divided by 4 and so on. As you approach the lowest and the highest parts of the exponent range you gradually run out of precision - bit by bit - so you need to be aware that extreme values can cause the epsilon method to fail. A: Certainly you should be using doubles instead of floats. This will probably reduce the number of flipped nodes significantly. Generally, using an epsilon threshold is only useful when you are comparing two floating-point number for equality, not when you are comparing them to see which is bigger. So (for most models, at least) using epsilon won't gain you anything at all -- it will just change the set of flipped nodes, it wont make that set smaller. If your model itself is chaotic, then it's chaotic.
doc_3676
app.js var express = require('express'); var app = express(); app.use(express.static('public')); var handlebars = require('express-handlebars').create({defaultLayout:'main'}); app.engine('handlebars', handlebars.engine); app.set('view engine', 'handlebars'); app.set('port', 8080); app.get('/',function(req,res,next){ var context = {}; res.render('home', context); }); app.get('/notify',function(reg,res,next){ console.log('I got a GET request!'); }); app.listen(app.get('port'), function(){ console.log('Express started on http://localhost:' + app.get('port') + '; press Ctrl-C to terminate.'); }); home.handlebars <input type="submit" id="Submit"> main.handlebars <!doctype html> <html> <head> <title>Test Page</title> <link rel="stylesheet" href="css/style.css"> <script src="scripts/buttons.js" type="text/javascript"></script> </head> <body> {{{body}}} </body> </html> buttons.js document.addEventListener('DOMContentLoaded', bindButtons); function bindButtons(){ document.getElementById('Submit').addEventListener('click', function(event){ var req = new XMLHttpRequest(); req.open("GET", "http://localhost:8080/notify", true); req.send(null); event.preventDefault(); }); } A: If you go to http://localhost:8080/notify you'll see the page keeps loading forever and never actually loads. This is because there is no response to your request. In your app, the subsequent requests take too long because there are previous ones still unresponded. Try adding this to you /notify GET handler after the console.log: res.send('This is a cool message from server');
doc_3677
The JBOSS server itself runs on Java 1.7.0_45. The logged reason for the failure is a ClassNofFoundException for a class that is actually there (even for the failing .ear): log4j:ERROR Could not create the Layout. Reported error follows. java.lang.ClassNotFoundException: dbs.common.logger.CsvLayout at java.net.URLClassLoader$1.run(URLClassLoader.java:366) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:425) at java.lang.ClassLoader.loadClass(ClassLoader.java:358) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:190) at org.apache.log4j.helpers.Loader.loadClass(Loader.java:178) at org.apache.log4j.xml.DOMConfigurator.parseLayout(DOMConfigurator.java:555) at org.apache.log4j.xml.DOMConfigurator.parseAppender(DOMConfigurator.java:269) at org.apache.log4j.xml.DOMConfigurator.findAppenderByName(DOMConfigurator.java:176) at org.apache.log4j.xml.DOMConfigurator.findAppenderByReference(DOMConfigurator.java:191) at org.apache.log4j.xml.DOMConfigurator.parseChildrenOfLoggerElement(DOMConfigurator.java:523) at org.apache.log4j.xml.DOMConfigurator.parseCategory(DOMConfigurator.java:436) at org.apache.log4j.xml.DOMConfigurator.parse(DOMConfigurator.java:999) at org.apache.log4j.xml.DOMConfigurator.doConfigure(DOMConfigurator.java:867) at org.apache.log4j.xml.DOMConfigurator.doConfigure(DOMConfigurator.java:773) at org.apache.log4j.xml.DOMConfigurator.configure(DOMConfigurator.java:901) at org.jboss.logging.Log4jService$URLWatchTimerTask.reconfigure(Log4jService.java:643) at org.jboss.logging.Log4jService$URLWatchTimerTask.run(Log4jService.java:582) at org.jboss.logging.Log4jService.setup(Log4jService.java:460) at org.jboss.logging.Log4jService.createService(Log4jService.java:476) at org.jboss.system.ServiceMBeanSupport.jbossInternalCreate(ServiceMBeanSupport.java:260) at org.jboss.system.ServiceMBeanSupport.jbossInternalLifecycle(ServiceMBeanSupport.java:243) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155) at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94) at org.jboss.mx.interceptor.AbstractInterceptor.invoke(AbstractInterceptor.java:133) at org.jboss.mx.server.Invocation.invoke(Invocation.java:88) at org.jboss.mx.interceptor.ModelMBeanOperationInterceptor.invoke(ModelMBeanOperationInterceptor.java:142) at org.jboss.mx.server.Invocation.invoke(Invocation.java:88) at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264) at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659) at org.jboss.system.ServiceController$ServiceProxy.invoke(ServiceController.java:978) at com.sun.proxy.$Proxy0.create(Unknown Source) at org.jboss.system.ServiceController.create(ServiceController.java:330) at org.jboss.system.ServiceController.create(ServiceController.java:273) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155) at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94) at org.jboss.mx.server.Invocation.invoke(Invocation.java:86) at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264) at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659) at org.jboss.mx.util.MBeanProxyExt.invoke(MBeanProxyExt.java:210) at com.sun.proxy.$Proxy4.create(Unknown Source) at org.jboss.deployment.SARDeployer.create(SARDeployer.java:260) at org.jboss.deployment.MainDeployer.create(MainDeployer.java:969) at org.jboss.deployment.MainDeployer.deploy(MainDeployer.java:818) at org.jboss.deployment.MainDeployer.deploy(MainDeployer.java:782) at org.jboss.deployment.MainDeployer.deploy(MainDeployer.java:766) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155) at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94) at org.jboss.mx.interceptor.AbstractInterceptor.invoke(AbstractInterceptor.java:133) at org.jboss.mx.server.Invocation.invoke(Invocation.java:88) at org.jboss.mx.interceptor.ModelMBeanOperationInterceptor.invoke(ModelMBeanOperationInterceptor.java:142) at org.jboss.mx.server.Invocation.invoke(Invocation.java:88) at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264) at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659) at org.jboss.mx.util.MBeanProxyExt.invoke(MBeanProxyExt.java:210) at com.sun.proxy.$Proxy5.deploy(Unknown Source) at org.jboss.system.server.ServerImpl.doStart(ServerImpl.java:482) at org.jboss.system.server.ServerImpl.start(ServerImpl.java:362) at org.jboss.Main.boot(Main.java:200) at org.jboss.Main$1.run(Main.java:508) at java.lang.Thread.run(Thread.java:744) Normally, I would easily find a real reason for a ClassNofFoundException, but this time I am baffled, considering the following facts: * *The entire environment (including the CLASSPATH!) for the .ear is identical. *The aforementioned "not found class" dbs.common.logger.CsvLayout is in the common.jar file in exactly the same path where it is supposed to be. *There are no errors in the build whatsoever. *On someone else's development workstation (same Eclipse, etc.) building that .ear with JDK 7u79 (i.e. later update than 7u45), results in a .ear that properly loads and runs (on same server and environment). What could possibly explain such ClassNofFoundException? What am I missing? Update: Comparing the "not found" CsvLayout.class between the working and not working common.jar file, shows that there is a difference in the major_version of the class file format. The working one has 0x33 (Java SE 7), the failing has 0x34 (Java SE 8). I have been careful to always work with Execution Environments that are jre7 only. How did that 0x34 sneak in? A: The problem comes from the fact that the library common.jar: is built using java 8 without specifying the target classfile version, and so a jar file with java 8 class file versions is generated. To build Java 7 classfile with Java 8 you need to * *pure java compilation: add the target option javac -target 1.7 <javafile> *maven: add the property <maven.compiler.target>1.7</maven.compiler.target> *ant: add <property name="ant.build.javac.source" value="1.7"/> <property name="ant.build.javac.target" value="1.7"/>to your build.xml
doc_3678
output i am getting till now this is what i have tried [assembly: ExportRenderer(typeof(BottomNavTabPage), typeof(BottomNavTabPageRenderer))] namespace HealthMobile.Droid.Renderers { public class BottomNavTabPageRenderer : TabbedPageRenderer { private bool _isShiftModeSet; public BottomNavTabPageRenderer(Context context) : base(context) { } protected override void OnVisibilityChanged(Android.Views.View changedView, [GeneratedEnum] ViewStates visibility) { base.OnVisibilityChanged(changedView, visibility); var tabs = changedView.FindViewById<TabLayout>(Resource.Id.sliding_tabs); if (tabs != null) { ViewGroup vg = (ViewGroup)tabs.GetChildAt(0); int tabsCount = vg.ChildCount; } } //protected override void DispatchDraw (global::Android.Graphics.Canvas canvas) // { // base.DispatchDraw (canvas); // SetTabIcons(); // // var tabLayout = (TabLayout)GetChildAt(1); // } // private void SetTabIcons() // { // var element = this.Element; // if (null == element) // { // return; // } // Activity activity = this.Context as Activity; // if ((null != activity) && (null != activity.ActionBar) && (activity.ActionBar.TabCount > 0)) // { // for (int i = 0; i < element.Children.Count; i += 1) // { // var tab = activity.ActionBar.GetTabAt(i); // var page = element.Children[i]; // if ((null != tab) && (null != page) && (null != page.Icon) // && (tab.CustomView == null)) // { // var resourceId = activity.Resources.GetIdentifier(page.Icon.File.ToLowerInvariant(), "drawable", this.Context.PackageName); // LinearLayout tabHeader // = new LinearLayout(activity) { Orientation = Orientation.Vertical }; // ImageView tabImg = new ImageView(activity); // TextView tabTitle = new TextView(activity); // tabImg.SetImageResource(resourceId); // tabTitle.Text = page.Title; // tabTitle.SetTextColor(Android.Graphics.Color.White); // tabHeader.AddView(tabTitle); // tabHeader.AddView(tabImg); // tab.SetCustomView(tabHeader); // } // } // } // } protected override void OnElementChanged(ElementChangedEventArgs<TabbedPage> e) { base.OnElementChanged(e); var childViews = GetAllChildViews(ViewGroup); //tab.SetIcon(Resource.Drawable.icon); var scale = Resources.DisplayMetrics.Density; var paddingDp = 0; var dpAsPixels = (int)(paddingDp * scale + 0.5f); foreach (var childView in childViews) { if (childView is BottomNavigationItemView tab) { //tab.SetPadding(-50, -100, -50, -100); } else if (childView is TextView textView) { textView.SetTextColor(Android.Graphics.Color.Transparent); } } } protected override void SetTabIcon(TabLayout.Tab tab, FileImageSource icon) { base.SetTabIcon(tab, icon); } protected override void OnLayout(bool changed, int l, int t, int r, int b) { base.OnLayout(changed, l, t, r, b); try { if (!_isShiftModeSet) { var children = GetAllChildViews(ViewGroup); if (children.SingleOrDefault(x => x is BottomNavigationView) is BottomNavigationView bottomNav) { bottomNav.SetShiftMode(false, false); _isShiftModeSet = true; } } } catch (Exception e) { Console.WriteLine($"Error setting ShiftMode: {e}"); } } private List<View> GetAllChildViews(View view) { if (!(view is ViewGroup group)) { return new List<View> {view }; } var result = new List<View>(); for (int i = 0; i < group.ChildCount; i++) { var child = group.GetChildAt(i); var childList = new List<View> {child}; childList.AddRange(GetAllChildViews(child)); result.AddRange(childList); } return result.Distinct().ToList(); } } } i am trying to make this look like this somewhat output expecting also i tried setting up the icons but SetTabIcons method never get triggered
doc_3679
$cars = array ( array($_COOKIE[pr1],$_COOKIE['1']), array($_COOKIE[pr2],$_COOKIE['2']), array($_COOKIE[pr3],$_COOKIE['3']), array($_COOKIE[pr4],$_COOKIE['4']), array($_COOKIE[pr5],$_COOKIE['5']) ); A: Try: array_multisort($cars[0], $cars[1], $cars[2], $cars[3], $cars[4]); A: You can use the code below for sorting as per your order. function multiarray_sort ($cars, $key) { $sorter=array(); $ret=array(); reset($cars); foreach ($cars as $ii => $va) { $sorter[$ii]=$va[$key]; } asort($sorter); foreach ($sorter as $ii => $va) { $ret[$ii]=$cars[$ii]; } $cars=$ret; } multiarray_sort($cars,"order"); A: Sorting multi dimensional arrays can be done using this : bool array_multisort ( array &$array1 [, mixed $array1_sort_order = SORT_ASC [, mixed $array1_sort_flags = SORT_REGULAR [, mixed $... ]]] ) Please click here for detailed information.
doc_3680
It gets more specific than that. A second card must be a sibling to the first card. Then, scrolling to the bottom of the first card renders the items un-interactable/un-clickable. Minimal Bootstrap example: /* obviously not showing Bootstrap styles */ .list-group { overflow: auto; max-height: 128px; } <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/> <div class="card-columns"> <!-- Card 1 --> <div class="card"> <div class="card-header">Overflow Card 1</div> <div class="list-group list-group-flush"> <a class="list-group-item list-group-item-action" href="#">Item 1</a> <a class="list-group-item list-group-item-action" href="#">Item 2</a> <a class="list-group-item list-group-item-action" href="#">Item 3</a> <a class="list-group-item list-group-item-action" href="#">Item 4</a> <a class="list-group-item list-group-item-action" href="#">Item 5</a> <a class="list-group-item list-group-item-action" href="#">Item 6</a> <a class="list-group-item list-group-item-action" href="#">Item 7</a> <a class="list-group-item list-group-item-action" href="#">Item 8</a> <a class="list-group-item list-group-item-action" href="#">Item 9</a> <a class="list-group-item list-group-item-action" href="#">Item 10</a> </div> </div> <!-- Card 2 --> <div class="card"> <div class="card-header">Overflow Card 2</div> <div class="list-group list-group-flush"> <a class="list-group-item list-group-item-action" href="#">Item 1</a> <a class="list-group-item list-group-item-action" href="#">Item 2</a> <a class="list-group-item list-group-item-action" href="#">Item 3</a> <a class="list-group-item list-group-item-action" href="#">Item 4</a> <a class="list-group-item list-group-item-action" href="#">Item 5</a> <a class="list-group-item list-group-item-action" href="#">Item 6</a> <a class="list-group-item list-group-item-action" href="#">Item 7</a> <a class="list-group-item list-group-item-action" href="#">Item 8</a> <a class="list-group-item list-group-item-action" href="#">Item 9</a> <a class="list-group-item list-group-item-action" href="#">Item 10</a> </div> </div> </div> Okay, still there? With all this in mind, I decided to eliminate Bootstrap styles one-by-one. Process of elimination. Perfect, I'm probably just doing something dumb. Minimal Native example: /* stripped down Bootstrap styles, plus styles from earlier */ body { font-family: sans-serif; padding: 1rem; } .card-columns { column-count: 3; } .list-group { max-height: 256px; overflow: auto; } .list-group-item { /* problem style */ position: relative; /* -------------*/ display: block; padding: .75rem 1.25rem; } .list-group-item:hover { background-color: #eee; } <div class="card-columns"> <!-- Card 1 --> <div class="card"> <div class="card-header">Overflow Card 1</div> <div class="list-group list-group-flush"> <a class="list-group-item list-group-item-action" href="#">Item 1</a> <a class="list-group-item list-group-item-action" href="#">Item 2</a> <a class="list-group-item list-group-item-action" href="#">Item 3</a> <a class="list-group-item list-group-item-action" href="#">Item 4</a> <a class="list-group-item list-group-item-action" href="#">Item 5</a> <a class="list-group-item list-group-item-action" href="#">Item 6</a> <a class="list-group-item list-group-item-action" href="#">Item 7</a> <a class="list-group-item list-group-item-action" href="#">Item 8</a> <a class="list-group-item list-group-item-action" href="#">Item 9</a> <a class="list-group-item list-group-item-action" href="#">Item 10</a> </div> </div> <!-- Card 2 --> <div class="card"> <div class="card-header">Overflow Card 2</div> <div class="list-group list-group-flush"> <a class="list-group-item list-group-item-action" href="#">Item 1</a> <a class="list-group-item list-group-item-action" href="#">Item 2</a> <a class="list-group-item list-group-item-action" href="#">Item 3</a> <a class="list-group-item list-group-item-action" href="#">Item 4</a> <a class="list-group-item list-group-item-action" href="#">Item 5</a> <a class="list-group-item list-group-item-action" href="#">Item 6</a> <a class="list-group-item list-group-item-action" href="#">Item 7</a> <a class="list-group-item list-group-item-action" href="#">Item 8</a> <a class="list-group-item list-group-item-action" href="#">Item 9</a> <a class="list-group-item list-group-item-action" href="#">Item 10</a> </div> </div> </div> Here's where it gets fun. It comes down to removing column-count from .card-columns or removing position from .list-group-item. If you're in the correct environment, running the CodePen will prevent that .list-group-item:hover style being activated (following the rules above). With all that said... I'm not a fan of long SO questions. I rarely read them. So, hypocrite I am, I thought I'd tap the brains of you guys. I'm fairly certain this is a Chrome bug. This code works properly in both Firefox and Edge. (I couldn't seem to find anything with a quick search on the Chromium bug tracker and this seems like such a very edge case that there may be no point in moving forward with this.) Oh, and resizing the page or double-tapping-to-select unusable list items must force some sort of redraw/layout because the issue isn't present after that. Agh. I'm hoping you can either point out an existing bug report somewhere, a workaround for this issue, or proof that my computer is simply haunted. Thanks for reading this far. Looking forward to your responses! TL;DR Combining column-count, overflow:auto, and position:relative makes Chrome 69 get spooky in October style. Send help. Edit 1 My question was edited by community to favor SO snippets over a CodePen. In the SO snippet, resizing the page will not cause the lists to redraw as mentioned above. However, resizing the preview pane on the original CodePen will reproduce these results. Trivial, but worth mentioning. Edit 2 Tested this morning on macOS Mojave. Issue is present in Chrome, but not in Firefox 62 or Safari 12. So it's not an issue isolated to webkit or Windows. I've resolved to carve pumpkins and avoid the position property altogether. A: This issue is not present in Chrome 71 Canary on macOS. I'm going to assume this issue has been resolved and will be pushed out eventually.
doc_3681
<ribbon:RibbonGallery> <ribbon:RibbonGallery.Resources> <Style TargetType="ribbon:RibbonGalleryItem"> <Setter Property="Width" Value="24" /> <Setter Property="Padding" Value="0" /> </Style> <Style TargetType="Rectangle"> <Setter Property="Width" Value="16" /> <Setter Property="Height" Value="16" /> </Style> </ribbon:RibbonGallery.Resources> </ribbon:RibbonGalleryCategory> <ribbon:RibbonGalleryCategory x:Name="themeColors" Header="Theme Colors" MinColumnCount="10" MaxColumnCount="10"> <ribbon:RibbonGalleryCategory.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal" > <Rectangle Fill="{Binding}" /> </StackPanel> </DataTemplate> </ribbon:RibbonGalleryCategory.ItemTemplate> </ribbon:RibbonGalleryCategory> </ribbon:RibbonGallery> my width and height are not applied to the rectangles. i wondering whats wrong A: You need to give your style a Key and then reference that key in your code: <Style x:Key="RectStyle"> <Setter Property="Width" Value="16" /> <Setter Property="Height" Value="16" /> </Style> Then: <StackPanel Orientation="Horizontal" > <Rectangle Fill="{Binding}" Style="{StaticResource RectStyle}" /> </StackPanel> To get the style to apply to all elements of a type you need to define it like this: <Style TargetType="{x:Type Rectangle}"> Use the former if you want to have several styles for an element and choose which one you want to apply. Source
doc_3682
I have tried the following code that splits the image into RGB and produces a histogram. Histogram then shows that blue channel is left the same but green and red are distorted. I would appreciate any help, thank you. cl = imread('raw3-image22.png'); % Extract colour channels redChannel = cl(:,:,1); % Red channel greenChannel = cl(:,:,2); % Green channel blueChannel = cl(:,:,3); % Blue channel allBlack = zeros(size(cl, 1), size(cl, 2), 'uint8') red = cat(3, redChannel, allBlack, allBlack); green = cat(3, allBlack, greenChannel, allBlack); blue = cat(3, allBlack, allBlack, blueChannel); imshow(cl); improfile; Chromatic abberation image: (https://i.stack.imgur.com/ajNd6.png) A: From what I can see, the blue color plane is in focus, while the green and red are increasingly blurred. You might try supervised deblurring, using stars for the point spread functions, green and red planes separately. Deblurring is never perfect, though. [Presumably, you won't appreciate this other solution: to blur the green and blue planes and after recomposition, reduce the image resolution by decimation.]
doc_3683
I am facing one strange issue wherein custom form validation is not getting called on android device but its getting called and working as per expectation. After going into detail it seems that if the input type is text then it is causing problem and it is working if input type is password. Have confirmed below points * *No error at console level *Same code working when run on ios device/run with ionic serve command. .ts file code this.loginForm = new FormGroup({ username: new FormControl('', Validators.required), password: new FormControl('', Validators.required) },this.loginFormValidator()); .html file code <fd-form-input-validation-message [errorType]="'error'" [errorVisible]="loginForm.errors?.username && loginForm.dirty ? 'true': 'false'" [errorMessage]="'Please enter username'"> <input #username formControlName="username" fd-form-control type="text" id="form-input-1" name="username" id="username" autocapitalize="none" autocomplete="off" autocorrect="off" required type="text" (keyup.enter)="onClickNext(password)" [state]="loginForm.errors?.username && loginForm.dirty?'invalid':''" placeholder="{{ 'LOGIN.USER_NAME_PLACEHOLDER' | translate }}" /> </fd-form-input-validation-message> Validation function code is loginFormValidator(): ValidatorFn { debugger; console.log("validation function called"); return (control: FormGroup): ValidationErrors | null => { const errors: ValidationErrors = {}; if ((control.get('username').value.length>=1 && control.get('password').value.length>=1)) { this.footerButtonConfig.disableStatus=false; } else{ this.footerButtonConfig.disableStatus=true; if(control.get('username').value.length==0 && control.get('username').dirty){ errors.username = { message: 'Please enter username' }; } if(control.get('password').value.length==0 && control.get('password').dirty){ errors.password = { message: 'Please enter password' }; } } return Object.keys(errors).length ? errors : null; }; } Package.json is "@angular/core": "~8.1.2", "@angular/forms": "~8.1.2", "@angular/http": "^7.2.15", As mentioned above if type="password" then validation function is getting called on all 3 platforms(web,ios,android) What could be the possible root cause of this issue?
doc_3684
Not enough random bytes available. Please do some other work to give the OS a chance to collect more entropy! (Need 278 more bytes) gpg (GnuPG) 1.4.16 Ubuntu 14.04.2 LTS A: Edit: This advice should not be followed in general as it does not generate secure keys. See juacala's answer, or stackoverflow.com/questions/11708334 for details. Turns out this is a known issue: https://bugs.launchpad.net/ubuntu/+source/gnupg/+bug/706011 I resolved it by installing rng-tools. ie sudo apt-get install rng-tools Then gpg --gen-key works as expected. A: Although rng-tools will work, this is not suggested since it doesn't provide real entropy. See the discussion here: https://bugs.launchpad.net/ubuntu/+source/gnupg/+bug/706011 For users that are frustrated by this, here are some things I found helpful on a server with no mouse/desktop. 1) Go through the process of creating the GPG key. If it hangs waiting for more entropy, go to the next step. 2) You can watch how much entropy your system has by opening a terminal and type (this will look at that file every second): watch -n1 cat /proc/sys/kernel/random/entropy_avail 3) Open a third terminal to generate your entropy. You can try various things to try to boost that entropy. Here are some things that I noticed increased the entropy sufficiently to make gpg work. Note that this was somewhat random (no pun intended). Sometimes doing something would increase the entropy; but when I do it again, it does not: Get a large file from the internet wget http://us1.php.net/get/php-7.2.2.tar.bz2/from/this/mirror Do something that prints a lot of stuff to the terminal: ls -R / sudo find /folder/with/lots/of/files/ -type f | xargs grep 'simple string that shows up in lots of files' 4) If what you are doing does not increase the entropy_avail, then try something else. A: sudo apt install haveged That will install haveged service, which collects entropy and fills /dev/random much more effectively. You don't need to run any additional commands after installing haveged, it will automatically start the service. systemctl status haveged to verify the service is running. You can also cat /dev/random to demonstrate that it can continuously provide values. In my test, gpg --gen-key completed in 10 seconds with haveged installed. If you don't want to install anything, you can generate entropy in other ways, but it's much slower than haveged (about 10x slower in my tests). Run this in another terminal while gpg --gen-key is running: while true; do # print entropy available cat /proc/sys/kernel/random/entropy_avail # write a 1 MB stream of zeros to /tmp/foo # "conv=fdatasync" flushes the disk cache dd bs=1M count=1 if=/dev/zero of=/tmp/foo conv=fdatasync done # one liner while true; do cat /proc/sys/kernel/random/entropy_avail; dd bs=1M count=1 if=/dev/zero of=/tmp/foo conv=fdatasync; done
doc_3685
def exItem_activated (self, widget, data=None): for i in range (0, 15): self.builder.get_object ('exItem' + (str)(i + 1)).set_expanded (False) widget.expanded = True print widget.name widget.name does not work, however; AttributeError: 'Expander' object has no attribute 'name'. So basically, when expander2 is clicked, I want to get "expander2" as a string. When expander14 is clicked, I want to get "expander14" as a string. Is there any way to do this? If this can't (easily) be done, it would also be an acceptable if I could just get some other property by which I could tell which widget was clicked. A: The corresponding method is called get_name() as far as I understand, eg.: print expander.get_name() Edit: for glade-based UI with gtk 2.20+ the gtk.Buildable.get_name() method should be used instead of gtk.Widget.get_name() since widget names are stored in id attribute of UI definition.
doc_3686
<ServiceUsers xmlns=""> <ServiceUser> <ID>280334</ID> <USER_NAME>YVELAMGAMOIYENET12:206322102</USER_NAME> <UN_ID>731937</UN_ID> <IP>91.151.136.178</IP> <NAME>?????????????????????: 123456</NAME> </ServiceUser> <ServiceUser> <ID>266070</ID> <USER_NAME>ACHIBALANCE:206322102</USER_NAME> <UN_ID>731937</UN_ID> <IP>185.139.56.37</IP> <NAME>123456</NAME> </ServiceUser> </ServiceUsers> my Code looks like this, but i am getting null point exception. XDocument doc = XDocument.Parse(xml) List<XElement> xElementList = doc.Element("ServiceUsers").Descendants().ToList(); foreach (XElement element in xElementList) { string TEST= element.Element("Name").Value; comboBoxServiceUser.Items.Add(element.Element("Name").Value); } A: Use doc.Element("ServiceUsers").Elements() to get the<ServiceUser> elements. Then you can loop over the child values of those in a nested loop. var doc = XDocument.Parse(xml); foreach (XElement serviceUser in doc.Element("ServiceUsers").Elements()) { foreach (XElement element in serviceUser.Elements()) { Console.WriteLine($"{element.Name} = {element.Value}"); } Console.WriteLine("---"); } Prints: ID = 280334 USER_NAME = YVELAMGAMOIYENET12:206322102 UN_ID = 731937 IP = 91.151.136.178 NAME = ?????????????????????: 123456 --- ID = 266070 USER_NAME = ACHIBALANCE:206322102 UN_ID = 731937 IP = 185.139.56.37 NAME = 123456 --- Note: Elements() gets the (immediate) child elements where as Descendants() returns all descendants. Using Elements() gives you a better control and allows you to get the properties grouped by user. You can also get a specific property like this serviceUser.Element("USER_NAME").Value. Note that the tag names are case sensitive! A: I think the basis of the problem is your trailing 's' to put it short, You iterate ServiceUser not ServiceUsers Anyway this runs through fine: [Fact] public void CheckIteratorTest() { var a = Assembly.GetExecutingAssembly(); string[] resourceNames = a.GetManifestResourceNames(); string nameOf = resourceNames.FirstOrDefault(x => x.Contains("SomeXml")); Assert.NotNull(nameOf); using var stream = a.GetManifestResourceStream(nameOf); Assert.NotNull(stream); var reader = new StreamReader(stream, Encoding.UTF8); var serialized = reader.ReadToEnd(); var doc = XDocument.Parse(serialized); var elemList = doc.Root.Elements("ServiceUser").ToList(); Assert.NotEqual(0, elemList.Count); foreach(var serviceUser in elemList) { System.Diagnostics.Debug.WriteLine($"Name : {serviceUser.Name ?? "n.a."}"); } } A: I used the example from XmlSerializer.Deserialize Method as the base for the following snippet that reads the provided xml. var serializer = new XmlSerializer(typeof(ServiceUsers)); ServiceUsers i; using (TextReader reader = new StringReader(xml)) { i = (ServiceUsers)serializer.Deserialize(reader); } [XmlRoot(ElementName = "ServiceUsers")] public class ServiceUsers : List<ServiceUser> { } public class ServiceUser { [XmlElement(ElementName = "ID")] public string Id {get; set;} } A: As being said: XML is case-sensitive. Next issue is .Descendants() returns all the descendant nodes, nested ones, etc, 12 nodes in this case. So NullPointerException will happen even if you fix a "typo". Here is your fixed code: XDocument doc = XDocument.Parse(xml); var xElementList = doc .Element("ServiceUsers") // picking needed root node from document .Elements("ServiceUser") // picking exact ServiceUser nodes .Elements("NAME") // picking actual NAME nodes .ToList(); foreach (XElement element in xElementList) { var TEST = element.Value; Console.WriteLine(TEST); // do what you were doing instead of console }
doc_3687
I've user panel and admin panel, which is user panel controller already put on: application/controllers/User.php, and this user panel work 100%. But there is error for admin panel and login panel, which are already put on subfolder: application/controllers/staff/Login.php screenshoot: error login so the problem is occurred, when i put controller on sub folder, example: mt.domain.com/subfolder/admin How to solve this problem? thanks this is my controller Login.php <?php defined('BASEPATH') OR exit('No direct script access allowed'); class Login extends CI_Controller{ function __construct(){ parent:: __construct(); $this->load->model('m_admin'); $this->load->helper('captcha'); $this->load->library('encryption'); } function index(){ $this->load->view('admin/login/v_login'); } and this is my view's file on views/admin/login/v_login.php <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Login - Bootstrap Admin Template</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <meta name="apple-mobile-web-app-capable" content="yes"> <link href="<?php echo base_url('assets/admin/css/bootstrap.min.css');?>" rel="stylesheet" type="text/css" /> <link href="<?php echo base_url('assets/admin/css/bootstrap-responsive.min.css');?>" rel="stylesheet" type="text/css" /> <link href="<?php echo base_url('assets/admin/css/font-awesome.css');?>" rel="stylesheet"> <link href="http://fonts.googleapis.com/css?family=Open+Sans:400italic,600italic,400,600" rel="stylesheet"> <link href="<?php echo base_url('assets/admin/css/style.css" rel="stylesheet');?>" type="text/css"> <link href="<?php echo base_url('assets/admin/css/pages/signin.css');?>" rel="stylesheet" type="text/css"> </head> <body> <div class="navbar navbar-fixed-top"> <div class="navbar-inner"> <div class="container"> <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </a> <a class="brand" > Login Admin MBill V.1.0 </a> <div class="nav-collapse"> <ul class="nav pull-right"> <li class=""> <a href="https://mt.adrihost.com/" class=""> <i class="icon-chevron-left"></i> Back to Homepage </a> </li> </ul> </div><!--/.nav-collapse --> </div> <!-- /container --> </div> <!-- /navbar-inner --> </div> <!-- /navbar --> <div class="account-container"> <div class="content clearfix"> <form action="<?php echo base_url('staff/login/aksi_login');?>" method="post"> <h1>Admin Login</h1> <div class="login-fields"> <p>Please provide your details</p> <div class="field"> <label for="username">Username</label> <input type="text" id="username" name="username" value="" placeholder="Username" class="login username-field" /> </div> <!-- /field --> <div class="field"> <label for="password">Password:</label> <input type="password" id="password" name="password" value="" placeholder="Password" class="login password-field"/> </div> <!-- /password --> </div> <!-- /login-fields --> <div class="login-actions"> <span class="login-checkbox"> <input id="Field" name="Field" type="checkbox" class="field login-checkbox" value="First Choice" tabindex="4" /> <label class="choice" for="Field">Keep me signed in</label> </span> <input type="submit" class="button btn btn-success btn-large" value="Sign In"> </div> <!-- .actions --> </form> </div> <!-- /content --> </div> <!-- /account-container --> <div class="login-extra"> <a href="#">Reset Password</a> </div> <!-- /login-extra --> <script src="js/jquery-1.7.2.min.js"></script> <script src="js/bootstrap.js"></script> <script src="js/signin.js"></script> </body> </html> A: You should use / to find the base directory in all assets replace 'assets'/... to '/assets/...' Example Old : <link href="<?php echo base_url('assets/admin/css/bootstrap.min.css');?>" rel="stylesheet" type="text/css" /> New : <link href="<?php echo base_url('/assets/admin/css/bootstrap.min.css');?>" rel="stylesheet" type="text/css" /> And also put your assets folder on the root directory Change all and you are done I think A: problem solved. the problem is on css file, which is need to be properly installed an assets folder on root. So i decided to put all css files on root. and then problem is solved. thanks very much.
doc_3688
--no-tree-shake-icons Without this, I get an error when building an Archive for distribution (which I would like ignored). I'm guessing that somewhere buried in the Xcode settings is the "flutter build ..." command, but cannot find it. A: I have found the answer! In Xcode, open the Runner/Flutter/Generated.xcconfig file. In there you should find the following: TREE_SHAKE_ICONS=true Set it to false and re-run Archive. If its missing, just add it. I think this file gets generated by Android Studio when you build your flutter app, so you may need to change it each time you need to do a release. But it works!
doc_3689
Error in ./src/containers/Signup.js Module not found: ../components/LoaderButton in C:\Users\AH\Desktop\notes-app-client\src\containers @ ./src/containers/Signup.js 25:20-57 Error in ./src/containers/Signup.js Module not found: ../libs/contextLib in C:\Users\AH\Desktop\notes-app-client\src\containers @ ./src/containers/Signup.js 29:18-47 Error in ./src/containers/Signup.js Module not found: ../libs/hooksLib in C:\Users\AH\Desktop\notes-app-client\src\containers @ ./src/containers/Signup.js 31:16-43 Error in ./src/containers/Signup.js Module not found: ../libs/errorLib in C:\Users\AH\Desktop\notes-app-client\src\containers
doc_3690
Here is a test code, with explanations. DROP DATABASE IF EXISTS bug; CREATE DATABASE bug; USE bug; CREATE TABLE test (id INT, purchased DATE) PARTITION BY RANGE (YEAR(purchased)) ( PARTITION p0 VALUES LESS THAN (2000), PARTITION p1 VALUES LESS THAN (2010), PARTITION p2 VALUES LESS THAN MAXVALUE ); INSERT INTO test(id, purchased) VALUES (1, '1990-01-01'), (2, '2001-01-01'), (3, '2011-01-01'); SELECT * FROM test; /*+------+------------+ | id | purchased | +------+------------+ | 1 | 1990-01-01 | | 2 | 2001-01-01 | | 3 | 2011-01-01 | +------+------------+*/ SELECT PARTITION_NAME, TABLE_ROWS FROM INFORMATION_SCHEMA.PARTITIONS WHERE 1=1 AND TABLE_NAME = 'test' ; -- one row per partition /*+----------------+------------+ | PARTITION_NAME | TABLE_ROWS | +----------------+------------+ | p0 | 1 | | p1 | 1 | | p2 | 1 | +----------------+------------+*/ /* now we want to split partition p0 to values up to year 1990 and up to 2000 */ ALTER TABLE test REORGANIZE PARTITION p0 INTO ( PARTITION n0 VALUES LESS THAN (1990), PARTITION n1 VALUES LESS THAN (2000) ); SELECT * FROM test; /*+------+------------+ | id | purchased | +------+------------+ | 1 | 1990-01-01 | | 2 | 2001-01-01 | | 3 | 2011-01-01 | +------+------------+ The data is still in the table */ SELECT PARTITION_NAME, TABLE_ROWS FROM INFORMATION_SCHEMA.PARTITIONS WHERE 1=1 AND TABLE_NAME = 'test' ; /*+----------------+------------+ | PARTITION_NAME | TABLE_ROWS | +----------------+------------+ | n0 | 0 | | n1 | 0 | | p1 | 0 | | p2 | 0 | +----------------+------------+ But no rows in the partitions ????? */ /* However, selecting the data from the partitions shows the data */ SELECT * FROM test PARTITION (n1, p1, p2); /*+------+------------+ | id | purchased | +------+------------+ | 1 | 1990-01-01 | | 2 | 2001-01-01 | | 3 | 2011-01-01 | +------+------------+*/ /* Flush tables did not help, and also closing and reopening the database */
doc_3691
[timestep + 1] [i] [j] [vx(i,j)] [vy(i,j)] [vz(i,j)] Each file number corresponds to a particular time step. Given the amount of data I have in this time series (~ 4 GB), bash wasn't cutting it so it seemed to be time to head over to awk... specifically mawk. It was pretty stupid to try this in bash but here is my ill-fated attempt: for x in $(seq 1 78) do tfx=${tf[$x]} # an array of padded zeros for y in $(seq 1 1568) do for z in $(seq 1 1344) do echo $x $y $z $(awk -v i=$z -v j=$y "FNR == i {print j}" $tfx.vx.dat) $(awk -v i=$z -v j=$y "FNR == i {print j}" $tfx.vy.dat) $(awk -v i=$z -v j=$y "FNR == i {print j}" $tfx.vz.dat) >> $file done done done edit: Thank you, ruakh, for pointing out that I had kept j in shell variable format with a $ in front! This is just a snippet of the original script, but I guess would be considered the guts of it! Suffice it to say this would have taken about six months because of all the memory overhead in bash associated with O(MxN) algorithms, subshells and pipes and whatnot. I was looking for more along the lines of a day at most. Each file is around 18 MB, so it should not be that much of a problem. I would be happy with doing this one timestep at a time in awk provided that I get one output file per timestep. I could just cat them all together without much issue afterwords, I think. It is important, though, that the time step number be the first item on the coordinate list. I could achieve this with an awk -v argument (see above) in with a bash routine. I do not know how to look up specific elements of matrices in three separate files and put them all together into one output. This is the main hurdle I would like to overcome. I was hoping mawk could provide a nice balance between effort and computational speed. If this seems to be too much for an awk script, I could go to something lower level, and would appreciate any of those answering letting me know I should just go to C instead. Thank you in advance! I really like awk, but am afraid I am a novice. The three files, 0000.vx.dat, 0000.vy.dat, and 0000.vz.dat would read as follows (except huge and of the correct dimensions): 0000.vx.dat: 1 2 3 4 5 6 7 8 9 0000.vy.dat: 10 11 12 13 14 15 16 17 18 0000.vz.dat: 19 20 21 22 23 24 25 26 27 I would like to be able to input: awk -v t=1 -f stackoverflow.awk 0000.vx.dat 0000.vy.dat 0000.vz.dat and get the following output: 1 1 1 1 10 19 1 1 2 2 11 20 1 1 3 3 12 21 1 2 1 4 13 22 1 2 2 5 14 23 1 2 3 6 15 24 1 3 1 7 16 25 1 3 2 8 17 26 1 3 3 9 18 27 edit: Thank you, shellter, for suggesting I put the desired input and output more clearly! A: Personally, I use gawk to process most of my text files. However, since you have requested a mawk compatible solution, here's one way to solve your problem. Run, in your present working directory: for i in *.vx.dat; do nawk -f script.awk "$i" "${i%%.*}.vy.dat" "${i%%.*}.vz.dat"; done Contents of script.awk: FNR==1 { FILENAME++ c=0 } { for (i=1;i<=NF;i++) { c++ a[c] = (a[c] ? a[c] : FILENAME FS NR FS i) FS $i } } END { for (j=1;j<=c;j++) { print a[j] > sprintf("%04d.dat", FILENAME) } } When you run the above, the results should be a single file for each set of three files containing your coordinates. These output files will have the filenames in the form: timestamp + 1 ".dat". I decided to pad these filenames with four 0's for your convenience. But you can change this to whatever format you like. Here's the results I get from the sample data you've posted. Contents of 0001.dat: 1 1 1 1 10 19 1 1 2 2 11 20 1 1 3 3 12 21 1 2 1 4 13 22 1 2 2 5 14 23 1 2 3 6 15 24 1 3 1 7 16 25 1 3 2 8 17 26 1 3 3 9 18 27
doc_3692
e.g. int [] [] ArrayToFillIn = new int [3] [3] int [] FillingArray = {1, 2}; for (int i = 1; i < 3; i++) { ArrayToFillIn [i-1] [2] = FillingArray [i - 1]; } in R it would be like: ArrayToFillIn [c(1:2),3] = FillingArray [] (considering that R does not start from 0) Thanks! A: Sure. Without a loop it would be ArrayToFillIn [0] [2] = FillingArray [0]; ArrayToFillIn [1] [2] = FillingArray [1]; A: What with this initialization: int [] FillingArray = {1, 2}; int [][] ArrayToFillIn = new int[][]{{0, 0, FillingArray[0]}, {0, 0, FillingArray[1]}, {}}; //---------------------------------------------^-----------------------^----------------^
doc_3693
http://grails.org/doc/latest/guide/6.%20The%20Web%20Layer.html#6.2.3%20Views%20and%20Templates But this just plain didn't work. The tag I used was: <g:render template="/includes/mySearch"></g:render> I created a directory under the views called "includes" and created a gsp file, with a very basic form in it, named mySearch.gsp. However, grails reported being unable to find the file: java.io.FileNotFoundException: C:\springsource\sts-2.8.1.RELEASE\grails-1.3.7\src\grails\templates\scaffolding_mySearch.gsp According to the documentation: "In this case you can place them in the root views directory at grails-app/views or any subdirectory below that location and then with the template attribute use a / before the template name to indicate the relative template path." It would appear that this is exactly what I did, but grails was not looking there? Any advice? Many thanks, Alexx A: Template files need to be starting with an underscore. Therefore you need to rename your mySearch.gsp to _mySearch.gsp.
doc_3694
I don't need much security, as I am aware that if people put some effort in they can view/modify the save, and I have no interest in stopping them. I just want the average user to not be tempted and/or see unnecessary information. Thanks in advance. A: you can use base64 encoding to encode your json String. it would be faster approach. If you with pure javascript : var encodedData = btoa("stringToEncode"); If you are using nodejs: base-64 encoding: var encodedStr = new Buffer("Hello World").toString('base64') decode to original value: var originalString = new Buffer("SGVsbG8gV29ybGQ=", 'base64').toString('utf-8') A: Well... given that there is no security concern and you only want users to see what appears to be garbled data you can "encode" all the json data var jsonData = {"key":"value"}; // turn it into a string var jsonString = JSON.stringify(jsonData); // replace some letters var awkardString = jsonString.replace(/a/g, '!Ax6'); // be carefull, you should replace a letter with a pattern that does not already exist on the string. // encode it with some type of reversible encoding var garbledData = encodeURI(jsonString); // output is: %7B%22key%22:%22v!Ax6lue%22%7D // to "decode" it do the same steps in reverse awkardString = decodeURI(garbledData); jsonString = awkardString.replace(/!Ax6/g, 'a'); // now you see, if '!Ax6' existed on the source string, you would loose it and get an 'a' in return. That is why the replacement should be as unique as possible jsonData = JSON.parse(jsonString);
doc_3695
I want to make this view available temporarily to a development team that is working on improving functionality in a connecting system and I don't have time to be the middle man retrieving data for them while they're doing that. Hence, a view for them to test their (hopefully) improved SQL statements. I want this view however, to only ever return a maximum of 1000 rows that meets the WHERE criteria the connected user constructs. For the life of me I can't find some guidance on how to do this. A: I believe you are looking for the expression "TOP" https://msdn.microsoft.com/en-us/library/ms189463.aspx In management studio you can right click the table and select the first option, this will generate the code for you. It should look something like this: SELECT TOP 1000 column1, column2, column3 FROM mytable A: You should use TOP function to retrieve specific number of rows from table. Select TOP 100 column1, column2 from sample_table; You can also use 'ORDER BY' in you query to specify which rows (last or first) you need to retrieve. Select TOP 100 column1, column2 from sample_table order by column1 DESC.
doc_3696
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <link href="bootstrap/css/bootstrap.css" rel="stylesheet" /> </head> <body> <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <div id="imageCarousel" class="carousel slide" data-interval="2000"> <div class="carousel-indicators"> <ol> <li data-target="#imageCarousel" data-slide-to="0" class="active" ></li> <li data-target="#imageCarousel" data-slide-to="1" ></li> <li data-target="#imageCarousel" data-slide-to="2" ></li> <li data-target="#imageCarousel" data-slide-to="3" ></li> </ol> </div> <div class="carousel-inner"> <div class="item active"> <img src="Images/img1.jpg" class="img-responsive" /> <div class="carousel-caption"> <h3>Image 1</h3> <p>This is the description for Image1</p> </div> </div> <div class="item"> <img src="Images/img2.jpg" class="img-responsive" /> <div class="carousel-caption"> <h3>Image 2</h3> <p>This is the description for Image2</p> </div> </div> <div class="item"> <img src="Images/img3.jpg" class="img-responsive" /> <div class="carousel-caption"> <h3>Image 3</h3> <p>This is the description for Image3</p> </div> </div> <div class="item"> <img src="Images/img4.jpg" class="img-responsive" /> <div class="carousel-caption"> <h3>Image 4</h3> <p>This is the description for Image4</p> </div> </div> </div> </div> </div> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script src="bootstrap/js/bootstrap.min.js"></script> <script type="text/javascript"> $(document).ready(function () { $(imageCarousel).carousel(); }); </script> </body> </html> This is the first slide when the page loads. It works well when I go to next slides. But when I navigate to the first slide I face with some inconsistency with carousel position, here is the second snapshot. How can I overcome this issue? A: Are you sure you are initializing your carousel correctly? $(document).ready(function () { $('#imageCarousel').carousel(); }); I found the problem, your markup is wrong. ol must have carousel-indicators class but you wrap this to div. Correct markup is: <ol class="carousel-indicators"> <li data-target="#imageCarousel" data-slide-to="0" class="active" ></li> <li data-target="#imageCarousel" data-slide-to="1" ></li> <li data-target="#imageCarousel" data-slide-to="2" ></li> <li data-target="#imageCarousel" data-slide-to="3" ></li> </ol> Look here for more details: https://getbootstrap.com/javascript/#carousel And this is the workingjsfiddle
doc_3697
I'd like to post each object in the array to mongo db. I keep running out on memory. I know I can increase the memory allocation, but that isn't the solution I want. I don't want to use the bulk method of mongo, either, for reasons beyond the scope of this example. I'm aware that there must be some method of posting these objects which means that memory is released at each iteration (garbage collected?) - can anyone tell me what it is? Thanks! Current code here for reference (which causes allocation error): var results = []; for(var i = 1; i < 1000001; i++){ results.push({"num":i}); } async = require("async"); var mongodb = require('mongodb'); var MongoClient = mongodb.MongoClient; var mongoUrl = 'mongodb://root@localhost:27017/results'; MongoClient.connect(mongoUrl, function (err, db) { var collection = db.collection('results'); // 1st para in async.each() is the array of items async.each(results, // 2nd param is the function that each item is passed to function(item, callback){ // Call an asynchronous function, often a save() to DB collection.insert(item, function (err, result) { if(err) console.log(err); console.log(item); callback(); }); }, // 3rd param is the function to call when everything's done function(err){ // All tasks are done now db.close(); } ); }); A: async.each() runs the inserts in parallel, so it basically starts 1000000 concurrent insert operations. You may want to limit that to, say, 100, by using async.eachLimit() A: Consider using the bulk operation if you want to optimize the insertions since it also reduces the network usage back and forth. Also storing huge arrays especially if they are just getting computed would be eating too much of memory. var bulk = collection.initializeUnorderedBulkOp(); var count = 1, i = 0; var bulkSize = 1000; var generator = function (mx) { if(i < mx){ return {num: i++} } return null; } var run = function () { doc = generator(); if(doc) { bulk.insert(doc) } if(doc == null || count % bulkSize == 0) { bulk.execute(function (err, res) { if(err) {} // do something if(doc == null) { db.close } run(); }) } } run() Here, no big arrays are stored at any step of your program. Only while the bulk array is created you would be storing it. That too is flushed to MongoDB once it reached the bulkSize A: Use setImmediate to prevent out of memory error var results = []; for(var i = 1; i < 1000001; i++){ results.push({"num":i}); } run(0, results.length, results, function(err){ // do stg }); function run(done, todo, results, callback) { if(++done >= todo) { // return callback if all done return callback(null); } else { // save one using index //collection.insert(results[done], function(err, res){ // OR save one and remove it from results collection.insert(results.splice(0,1), if(err) return callback(err); else { // use setImmediate to recall run while releasing stack return setImmediate(run, ++done, todo, results, callback); } }); } } A: Old question but I came across this when trying to do something similar. I kept running out of memory while trying to insert about 4 million documents. The solution for me was to dump all of the data to a JSON file, example: users.json { "name", "John", "city": "San Francisco" } { "name", "Jane", "city": "New York" } I then used mongoimport to import the file into mongo: mongoimport -u root --authenticationDatabase admin --host="localhost:27017" --db="my_db" --collection="Users" --numInsertionWorkers 4 --file="users.json" mongoimport managed the memory and had a nice output display (see below). For 4 million documents, it took less than 2 minutes and only used 900 MB of RAM. 2022-06-21T17:46:46.711+0000 [........................] my_db.Users 30.9MB/903MB (3.4%) 2022-06-21T17:46:49.714+0000 [#.......................] my_db.Users 62.2MB/903MB (6.9%) 2022-06-21T17:46:52.711+0000 [##......................] my_db.Users 93.3MB/903MB (10.3%) 2022-06-21T17:46:55.711+0000 [###.....................] my_db.Users 124MB/903MB (13.7%) 2022-06-21T17:46:58.718+0000 [####....................] my_db.Users 155MB/903MB (17.2%) 2022-06-21T17:47:01.711+0000 [####....................] my_db.Users 186MB/903MB (20.6%) 2022-06-21T17:47:04.712+0000 [#####...................] my_db.Users 217MB/903MB (24.0%) 2022-06-21T17:47:07.716+0000 [######..................] my_db.Users 248MB/903MB (27.5%) 2022-06-21T17:47:10.711+0000 [#######.................] my_db.Users 279MB/903MB (30.8%) 2022-06-21T17:47:13.712+0000 [########................] my_db.Users 310MB/903MB (34.3%) 2022-06-21T17:47:16.712+0000 [#########...............] my_db.Users 341MB/903MB (37.7%) 2022-06-21T17:47:19.713+0000 [#########...............] my_db.Users 371MB/903MB (41.0%) 2022-06-21T17:47:22.717+0000 [##########..............] my_db.Users 401MB/903MB (44.4%) 2022-06-21T17:47:25.712+0000 [###########.............] my_db.Users 432MB/903MB (47.9%) 2022-06-21T17:47:28.711+0000 [############............] my_db.Users 464MB/903MB (51.4%) 2022-06-21T17:47:31.712+0000 [#############...........] my_db.Users 495MB/903MB (54.8%) 2022-06-21T17:47:34.713+0000 [#############...........] my_db.Users 526MB/903MB (58.3%) 2022-06-21T17:47:37.711+0000 [##############..........] my_db.Users 557MB/903MB (61.7%) 2022-06-21T17:47:40.713+0000 [###############.........] my_db.Users 588MB/903MB (65.1%) 2022-06-21T17:47:43.712+0000 [################........] my_db.Users 619MB/903MB (68.6%) 2022-06-21T17:47:46.711+0000 [#################.......] my_db.Users 650MB/903MB (71.9%) 2022-06-21T17:47:49.713+0000 [##################......] my_db.Users 680MB/903MB (75.3%) 2022-06-21T17:47:52.711+0000 [##################......] my_db.Users 712MB/903MB (78.8%) 2022-06-21T17:47:55.711+0000 [###################.....] my_db.Users 742MB/903MB (82.2%) 2022-06-21T17:47:58.717+0000 [####################....] my_db.Users 766MB/903MB (84.8%) 2022-06-21T17:48:01.715+0000 [####################....] my_db.Users 783MB/903MB (86.7%) 2022-06-21T17:48:04.712+0000 [#####################...] my_db.Users 810MB/903MB (89.7%) 2022-06-21T17:48:07.720+0000 [######################..] my_db.Users 840MB/903MB (93.0%) 2022-06-21T17:48:10.711+0000 [#######################.] my_db.Users 870MB/903MB (96.3%) 2022-06-21T17:48:13.712+0000 [#######################.] my_db.Users 899MB/903MB (99.6%) 2022-06-21T17:48:14.124+0000 [########################] my_db.Users 903MB/903MB (100.0%) 2022-06-21T17:48:14.124+0000 imported 4027382 documents
doc_3698
If I launch the Job using the standalone resource manager: spark-submit \ --master local \ --deploy-mode client \ --repositories "http://central.maven.org/maven2/" \ --packages "org.postgresql:postgresql:42.2.2" \ --py-files https://storage.googleapis.com/foo/some_dependencies.zip \ https://storage.googleapis.com/foo/script.py some args It works fine. But if I try the same using Kubernetes: spark-submit \ --master k8s://https://xx.xx.xx.xx \ --deploy-mode cluster \ --conf spark.kubernetes.container.image=gcr.io/my-spark-image \ --repositories "http://central.maven.org/maven2/" \ --packages "org.postgresql:postgresql:42.2.2" \ --py-files https://storage.googleapis.com/foo/some_dependencies.zip \ https://storage.googleapis.com/foo/script.py some args Then the main script runs, but it can't find the modules in the dependencies files. I know I can copy all the files inside the Docker image but I would prefer doing it this way. Is this possible? Am I missing something? Thanks A: So the idea behind the k8s scheduler is to put absolutely everything in the container. So your CI/CD would build a Dockerfile with the Apache Spark kubernetes Docker as its base and then have a zipped copy of your python repo and driver python script inside the docker image. Like this: $ bin/spark-submit \ --master k8s://<k8s-apiserver-host>:<k8s-apiserver-port> \ --deploy-mode cluster \ --py-files local:///path/to/repo/in/container/pyspark-repo.zip \ --conf spark.kubernetes.container.image=pyspark-repo-docker-image:1.0.0 \ local:///path/to/repo/in/container/pyspark-driver.py Your spark.kubernetes.container.image should be your full application complete with a * *zip of the repo for --py-files (ex: repo.zip) *your requirements.txt installed to the container's version of python (done in your repo's Dockerfile) *driver script (ex: driver.py) A: Actually --py-files can be used to distribute dependencies to executors. Can you display the errors you get ? Do you import your zips (SparkContext.addPyFile) in the main .py ? A: ENV: spark 2.4.3 UPDATED answer: In https://spark.apache.org/docs/latest/running-on-kubernetes.html#dependency-management, docs says: Note that using application dependencies from the submission client’s local file system is currently not yet supported. OLDER answer: I am facing the same issue. I don't think files in --py-files will be distributed to driver and executors. I submit a python file to K8s cluster with following command: bin/spark-submit \ --master k8s://https://1.1.1.1:6443 \ --deploy-mode cluster \ --name spark-test \ --conf xxx.com/spark-py:v2.4.3 \ --py-files /xxx/spark-2.4.3-bin-hadoop2.7/spark_test1.py \ http://example.com/spark/__main__.py I got logs in driver pod: + PYTHONPATH='/opt/spark/python/lib/pyspark.zip:/opt/spark/python/lib/py4j-*.zip:file:///xxx/spark-2.4.3-bin-hadoop2.7/spark_test1.py' I got errors like following: Traceback (most recent call last): File "/tmp/spark-5e76171d-c5a7-49c6-acd2-f48fdaeeb62a/__main__.py", line 1, in <module> from spark_test1 import main ImportError: No module named spark_test1 From the errors, the main python file is get uploaded and distributed to driver. For --py-files, PYTHONPATH contains an exact same path in my cmd which I don't think those files get uploaded to that path in driver pod and executor pod. I tried to replace the spark_test1.py from a local path to a HTTP URL. The PYTHONPATH changed accrodingly, but the error is the same. A: I mount pvc to the container by persistentVolumeClaim and before submit the spark application, download the -py-files to the pv(like glusterfs) first, the spark on k8s will not downlod it for you, and spark on yarn driver and exector will do download files for you with spark.yarn.archive param sh bin/spark-submit \ --master k8s://https://xxx:6443 \ --deploy-mode cluster \ --conf spark.kubernetes.namespace=spark \ --conf spark.kubernetes.authenticate.driver.serviceAccountName=spark \ --conf spark.kubernetes.container.image=xxx/spark:latest \ --conf spark.kubernetes.container.image.pullPolicy=Always \ --conf spark.eventLog.dir=/xxx/spark-eventlog \ --conf spark.eventLog.enabled=true \ --conf spark.executor.instances=1 \ --conf spark.executor.memory=1024m \ --conf spark.driver.memory=1024m \ --conf spark.kubernetes.driver.request.cores=1 \ --conf spark.kubernetes.executor.request.cores=1 \ --name spark-demo \ --py-files local:///xxx/spark_utils.zip \ /xxx/pyspark_demo.py as I tested with spark-2.4.8 with hadoop 2.6.0-cdh5.16.1 the --py-files is working ,it pass to the PYTHONPATH and in the Dockerfile ENV PYTHONPATH ${SPARK_HOME}/python/lib/pyspark.zip:${SPARK_HOME}/python/lib/py4j-*.zip so generated spark-submit like this 'PYTHONPATH': '/opt/spark/python/lib/pyspark.zip:/opt/spark/python/lib/py4j-0.10.7-src.zip:/opt/spark/jars/spark-core_2.11-2.4.8.jar:/opt/spark/python/lib /pyspark.zip:/opt/spark/python/lib/py4j-*.zip:file:/xxx/spark_utils.zip',
doc_3699
https://outlook.office365.com/ews/odata/Me/Events?$select=Start,End,IsAllDay,Subject&$filter=Start+ge+2014-09-10T05%3A00%3A00Z+and+Start+le+2014-09-11T04%3A59%3A59Z This works perfectly for 'SingleInstance' and 'SeriesMaster' Type meeting instances; however, I am seeing some strange behavior with recurring meetings. For only some users any 'Occurrences' type meetings (a specific occurrence of a recurring meeting) are not returned from the API call; even if the meeting displays on their calendar in the OWA portal. Other users see recurring and non-recurring meetings as expected. As a test I created a recurring meeting and invited users who were reporting the issue and users who were getting the expected response and then ran the query again for all users. That meeting followed the pattern described above with users either seeing all of the expected occurrences or no recurring meeting occurrences. Has anyone else come across this? Is there a better way to get all meeting events for a specific date range? A: Thanks for your question! Can you please try your query with the following change marked in bold? https://outlook.office365.com/ews/odata/Me/Events?$select=Start,End,IsAllDay,Subject&$filter=End+ge+2014-09-10T05%3A00%3A00Z+and+Start+le+2014-09-11T04%3A59%3A59Z This returns all occurrences of recurring meetings that fall within the time range you have specified, in addition to single meetings. Having said that, we are aware that the current method for retrieving all events (single and recurring meeting occurrences) in a specified time period isn't intuitive, and are working to address this. Please let me know if you have any questions or need more info. Thanks, Venkat A: Change the name of the first parameter to "End", i.e.: https://outlook.office365.com/ews/odata/Me/Events?$select=Start,End,IsAllDay,Subject&$filter=End+ge+2014-09-10T05%3A00%3A00Z+and+Start+le+2014-09-11T04%3A59%3A59Z I know, it is bizarre but the only way to retrieve a complete list of events within a date range is to have the "End" argument first followed by the "Start". $filter=End ge {0} and Start le {1} Note: the API could change in the near future and none of this will longer apply.