id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23532400
(Thanks for those tools guys) We have no errors in the compilation or displaying in the console log. Serves fine but our geojson object is nowhere to be found. I'm just looking to display the geojson data on the map. Any help or advice is appreciated. Angular CLI: 1.6.5 Node: 8.3.0 OS: darwin x64 Angular: 5.2.1 ... common, compiler, compiler-cli, core, forms, http ... language-service, platform-browser, platform-browser-dynamic ... router @angular/animations: 5.2.2 @angular/cdk: 5.1.1 @angular/cli: 1.6.5 @angular/material: 5.1.1 @angular-devkit/build-optimizer: 0.0.41 @angular-devkit/core: 0.0.28 @angular-devkit/schematics: 0.0.51 @ngtools/json-schema: 1.1.0 @ngtools/webpack: 1.9.5 @schematics/angular: 0.1.16 typescript: 2.5.3 webpack: 3.10.0 <div leaflet style="height: 600px;" [leafletOptions]="options" [leafletLayers]="layers" [leafletLayersControl]="layersControl"> </div> State Component import { Component, OnInit } from '@angular/core'; import { StateService } from "../state.service"; import {tileLayer, Layer, latLng} from "leaflet"; import {HttpClient} from "@angular/common/http"; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/map'; import { LeafletLayersDemoModel } from './layers-demo.model'; import * as L from 'leaflet'; @Component({ selector: 'app-state', templateUrl: './state.component.html', styleUrls: ['./state.component.css'] }) export class StateComponent implements OnInit { public geo_json_data; constructor(private state_service:StateService, public http:HttpClient) { this.apply(); } LAYER_OSM = { id: 'openstreetmap', name: 'Open Street Map', enabled: false, layer: tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 18, attribution: 'Open Street Map' }) }; geoJSON = { id: 'geoJSON', name: 'Geo JSON Polygon', enabled: true, layer: L.geoJSON(this.geo_json_data) }; model = new LeafletLayersDemoModel( [ this.LAYER_OSM], this.LAYER_OSM.id, [ this.geoJSON ] ); layers: Layer[]; layersControl = { baseLayers: { 'Open Street Map': this.LAYER_OSM.layer }, overlays: { GeoJSON: this.geoJSON.layer } }; options = { zoom: 6, center: latLng(41.2033, -74.2179) }; apply() { // Get the active base layer const baseLayer = this.model.baseLayers.find((l: any) => (l.id === this.model.baseLayer)); // Get all the active overlay layers const newLayers = this.model.overlayLayers .filter((l: any) => l.enabled) .map((l: any) => l.layer); newLayers.unshift(baseLayer.layer); this.layers = newLayers; return false; } ngOnInit() { console.log(this.state_service.state_id); this.http.get('http://localhost:4200/assets/data/pa.geojson') .subscribe((data) => { this.geo_json_data = data; console.log(this.geo_json_data); }, error => { console.log(error.text()); alert('GEO JSON GET FAILED'); }); } } A: You should try initialise the layers var (and others) in subscribe, after receiving the data: Here is an example: You should install the following: ng new geojsondemo cd geojsondemo/ npm install leaflet --save npm install @types/leaflet --save-dev npm install @asymmetrik/ngx-leaflet --save npm install leaflet-providers --save npm install @types/leaflet-providers --save-dev Your app.module.ts should like this: import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; import { LeafletModule } from '@asymmetrik/ngx-leaflet'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, LeafletModule, HttpClientModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } Your app.component.html should look like this: <div leaflet style="height: 300px" [leafletLayers]="layers" [leafletLayersControl]="layersControl" [leafletCenter]="center" [leafletFitBounds]="fitBounds"></div> Your app.component.ts should look like this: import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Layer, tileLayer, geoJSON, LayerOptions } from 'leaflet'; import 'leaflet-providers'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { layers: Layer[]; layersControl: any; center = [59.9386300, 30.3141300]; fitBounds = [[60.2448369, 29.6998985], [59.6337832, 30.254172]]; constructor(private http: HttpClient) { } ngOnInit() { this.http.get<any>('/assets/geojson/admin_level_4.geojson') .subscribe(geo1 => { this.http.get<any>('/assets/geojson/admin_level_5.geojson') .subscribe(geo2 => { let defaultBaseLayer = tileLayer.provider('OpenStreetMap.Mapnik'); let defaultOverlay = geoJSON(geo1); this.layers = [ defaultBaseLayer, defaultOverlay ]; this.layersControl = { baseLayers: { 'OpenStreetMap Mapnik': defaultBaseLayer, 'OpenStreetMap BlackAndWhite': tileLayer.provider('OpenStreetMap.BlackAndWhite') }, overlays: { 'Overlay One': defaultOverlay, 'Overlay Two': geoJSON(geo2) } }; }); }); } } There are two base layers and two overlays. For base layes I used leaflet-prividers (much cleaner code). For overlay I used two geojson files. Provide your own and change the paths. Also provide a center and a fitBounds. And don't forget to add leaflet.css to .angular-cli.json like so "styles": ["../node_modules/leaflet/dist/leaflet.css","styles.css"]
doc_23532401
@IBOutlet weak var selectedCountry: UIButton! var pickedCountry: String? func checkForPickedCountry() { if self.pickedCountry != nil { selectedCountry.setTitle("\(pickedCountry!)", forState: .Normal); } else { selectedCountry.setTitle("Tap here pick a country", forState: .Normal); } UPDATE Now like i mentioned, I'm using a pickerView to update the value of pickedCountry, and when a country is selected from the pickerView, it then displays a second button titled selectedFlag that shoots another pickerView to choose a country flag. Now the reason I want to listen to the 1st pickedCountry var for change is so I can change the title of the selectedFlag button to the default. So here is the final code I have: @IBOutlet weak var selectedCountry: UIButton! @IBOutlet weak var selectedFlag: UIButton! var pickedCountry: String? var pickedFlag: String? func checkForPickedCountry() { if self.pickedCountry != nil { selectedCountry.setTitle("\(pickedCountry!)", forState: .Normal); selectedFlag.hidden = false } else { selectedCountry.setTitle("Tap here pick a country", forState: .Normal); selectedFlag.hidden = true } if self.pickedFlag != nil { selectedFlag.setTitle("\(pickedCountry!)", forState: .Normal); } else { selectedFlag.setTitle("Tap here to pick a flag", forState: .Normal) } Now how do i set selectedFlag's title to "Tap here to picka flag when the value of `PickedCountry is changed?? A: You can implement willSet in your variable to call your function everytime when variable is changing. Also you can modify your function to get new value like this: var pickedCountry: String? { willSet(newValue) { guard let oldValue = str, new = newValue else { return } if oldValue != new { //....Your value is changed } } } func checkForPickedCountry(updatedValue: String) {...} A: You can monitor it with a key value observer. In the class that is supposed to look for the changes, do the following: Add the observer func addObservers() { let observerKeyLocation = "pickedConuntry" classThatMonitors.addObserver(self, forKeyPath: observerKeyLocation, options: .New, context: nil) } Then, override the observerValueForKeyPath function: override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if keyPath == observerKeyLocation { if self.pickedCountry != nil { selectedCountry.setTitle("\(pickedCountry!)", forState: .Normal); } else { selectedCountry.setTitle("Tap here pick a country", forState: .Normal); } } } Now, whenever that value is changed, your observer will immediately be updated and can call the code you place inside it. Just remember, if you deinit the class being observed, you must also remove the observer to avoid a crash. A: You can use simple logic as Below:: Set one Int Variable var flag : Int = 0 Now In whole program flag has 0 value. Again when you tap Button change its value to 1 by self.flag = 1. Again when you tap second one make it 0 by self.flag = 0. By getting the value of that flag variable you will listen the event. You can Do same for more then two by providing values 2, 3, 4... To flag variable
doc_23532402
Error Domain=FlurryAds Code=117 "FlurryAds: Ad request to server failed." UserInfo=0x7fbf7e605000 {NSLocalizedDescription=FlurryAds: Ad request to server failed.} Has anyone experienced this and was able to solve this issue? Anyone on the Flurry team monitoring Stackoverflow? A: The most likely possibilities are that we either do not have an ad to fill in your geographic location or there is a problem with your Flurry integration. You can test the first possibility by VPN to the US and see if you get ads. Otherwise please send the following information to support@flurry.com 1) The API key for this project found under Manage -> App Info 2) SDK version 3) Adspace name 4) A code snippet where you fetch the ad 5) The corresponding output to your console logs
doc_23532403
canvas = tk.Canvas(root) canvas.create_rectangle(0,0,50,100, fill='green') I want to darken it. So: canvas.itemconfig(1, fill=?????) The issue is, what should I put in the ????? aka the 'darker' color of the original color. Sure, I can just find a hex for a darker shade of green or something like that, but the point is: How can I find the darkened the widget based on the original color? I don't necessarily need to find the darker version of the color if there is something like: canvas.itemconfig(1, darkness=-100). A: Here is a simple example of how to use a function to lower the color based on a RGB tuple that is converted to hex. We start out with a lightish green and with each button press it gets darker. This is a simple example but I am sure you can adapt it for your needs. import tkinter as tk root = tk.Tk() cv = (110, 160, 50) canvas = tk.Canvas(root) rect = canvas.create_rectangle(0,0,50,100, fill="#%02x%02x%02x" % cv) canvas.pack() def darker(): global cv greater = True cv = (cv[0]- 10, cv[1] - 10, cv[2] - 10) for item in cv: if item < 0: greater = False if greater == True: canvas.itemconfig(rect, fill = "#%02x%02x%02x" % cv) tk.Button(root, text="Darker", command=darker).pack() root.mainloop() Or you can do this using the current preferred concatenation with format(): import tkinter as tk root = tk.Tk() cv = (110, 160, 50) canvas = tk.Canvas(root) rect = canvas.create_rectangle(0,0,50,100, fill = "#{}".format("".join("{:02X}".format(a) for a in cv))) canvas.pack() def darker(): global cv greater = True cv = (cv[0]- 10, cv[1] - 10, cv[2] - 10) for item in cv: if item < 0: greater = False if greater == True: canvas.itemconfig(rect, fill = "#{}".format("".join("{:02X}".format(a) for a in cv))) tk.Button(root, text="Darker", command=darker).pack() root.mainloop()
doc_23532404
This is how a Slider looks when I try to add the value label: This is the sample code: Slider( value: sliderValue, activeColor: color, min: 0.0, max: 100.0, divisions: 2000, //TO COMMENT label: sliderValue.toStringAsFixed(2), //TO COMMENT onChanged: (value) { setState(() { sliderValue = value; }); }), In this code, if I comment out the marked //TO COMMENT lines which are the divisions and label properties, the `label goes away as expected, and the animation is smooth again. I assume this is due to divisions, and any amount of it, even just 100 does not change the lag in any way. Additionally, it seems that the label property does not work on its own. It needs the divisions property to also be set so that the value label can be displayed. What is the workaround so that I can achieve a Slider with the smoothness shown in the first image, but have the default value label or what looks the same? A: If you take a look on source code, you can find _positionAnimationDuration which is responsible to animate the slider Change it to static const Duration _positionAnimationDuration = Duration.zero; Changing on source-code will affect on others project, instead create a local dart file, paste the full slider code and make changes. Let say we have created customSlider.dart file . Make sure to replace some(./xyz.dart) top imports with import 'package:flutter/cupertino.dart'; or material on our customSlider.dart. Then replace _positionAnimationDuration. To use this, import the file import 'customSlider.dart' as my_slider; ... //use case my_slider.Slider(....) A: // create class // .yaml > another_xlider: ^1.0.0 import 'package:another_xlider/another_xlider.dart'; import '../res/res_controller.dart'; import '../utils/utils_controller.dart'; import 'package:flutter/material.dart'; class RangeBar extends StatelessWidget { final List<double>? values; final double? min; final double? max; final Function(int, dynamic, dynamic)? onDragging; const RangeBar( {Key? key, @required this.values, @required this.onDragging, @required this.min, @required this.max}) : super(key: key); @override Widget build(BuildContext context) { return FlutterSlider( values: values!, // pre set values rangeSlider: true, handlerAnimation: FlutterSliderHandlerAnimation( curve: Curves.elasticOut, reverseCurve: Curves.bounceIn, duration: Duration(milliseconds: 500), scale: 1.5), jump: true, min: min ?? 0, max: max ?? 0, touchSize: Sizes.s13, trackBar: FlutterSliderTrackBar( activeTrackBar: BoxDecoration(color: AppColors.orange), ), tooltip: FlutterSliderTooltip( boxStyle: FlutterSliderTooltipBox( decoration: BoxDecoration( color: Colors.greenAccent, borderRadius: BorderRadius.all(Radius.circular(Sizes.s5)), border: Border.all( color: AppColors.steelGray, ), ), ), positionOffset: FlutterSliderTooltipPositionOffset(top: -Sizes.s15), alwaysShowTooltip: true, textStyle: TextStyles.defaultRegular.copyWith(fontSize: FontSizes.s11), ), onDragging: onDragging); } } // try to call Container( child: _size(), ) Widget _size() { { double sizeMin; double sizeMax; sizeMin = 0; sizeMax = 0; sizeMax = sizeMin.round() == sizeMax.round() ? sizeMax + 1 : sizeMax; return RangeBar( values: [ // add values ], min: sizeMin, max: sizeMax.ceilToDouble(), onDragging: (p0, lowerValue, upperValue) { log(lowerValue); log(upperValue); }, ); return C0(); } }
doc_23532405
import java.util.Arrays; import java.util.Iterator; import java.util.List; public class X { public static void main(String[] argv) { String strAra[] = new String[4]; //{ "Lionel Messi", "Drake", "Adele", "Dwayne Johnson", "Beyonce" }; strAra[0] = "Lionel Messi"; strAra[1] = "Drake"; strAra[2] = "Adele"; strAra[3] = "Dwayne Johnson"; strAra[4] = "Beyonce"; List<String> lList = Arrays.asList(strAra); System.out.println("Here is the list:"); Iterator<String> iterator = lList.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } System.out.println("Here is the new list"); for (int i = 0; i < lList.size(); i++) { System.out.println(lList.get(i)); } } } A: In the "second attempt ",you are putting five strings into the array,but you init the array that the length is four. You need to change "new String[4];" to "new String[5];" I think. = = A: From what it appears you are trying to do, you need to instantiate an ArrayList, not turn an Array into a List. Check the Java API out for the different methods and constructors you can call with an ArrayList. The ArrayList can be instantiated and the data added by doing the following: ArrayList<String> arr = new ArrayList<String>(); Then you can add data by doing: arr.add("Lionel Messi"); After populating the ArrayList, you can use the ArrayList's methods of add(element, index) and remove(index) to manipulate the data.
doc_23532406
I want the orange fill the green space.. and turn the green space to transparant of course. Basically it's just a size/position problem. CSS: @media all and (max-width: 600px) { .example-header .container { width: auto; height:auto; margin:0 auto; padding:auto; } /*Zwarte MENU balk */ a.menu-link { display: block; color: #fff; background-color: #333; text-decoration: none; padding: 19px 10px; width:auto; height:auto; margin:0 auto; padding:auto; margin-bottom:2em; } .menu { border-top: 10px solid #333; border-bottom:10px solid #333; height:13.2em; margin:0 auto; padding:auto; width:100%; background-color:blue; } .menu ul { width:auto; height:auto; margin:0 auto; padding:auto; } .menu > ul { height:auto; margin-top:; background-color:TRANSPARANT; } .menu li, .menu > ul > li { width:100%; height:auto; margin:0 auto; padding:0px; background-color:green; } .menu li a { color: #000; display: inline; border-bottom: 1px solid #333; position: relative; height:auto; margin:0 auto; padding:auto; background-color:orange; } } A: It looks like a padding-related issue, try setting it to 0 instead of auto for .menu ul. HTML would be helpful though. A: My guess is that the anchor elements' should be display: block; instead of display: inline;. And possibly their margin should also be just 0 instead of 0 auto Can't say much without the HTML.
doc_23532407
Parse.com documentation: // Create the object. var gameScore = new ParseObject("GameScore") { { "score", 1337 }, { "playerName", "Sean Plott" }, { "cheatMode", false }, { "skills", new List<string> { "pwnage", "flying" } }, }; await gameScore.SaveAsync(); // Now let's update it with some new data. In this case, only cheatMode // and score will get sent to the cloud. playerName hasn't changed. gameScore["cheatMode"] = true; gameScore["score"] = 1338; await gameScore.SaveAsync(); What I tried most recently: ParseQuery<ParseObject> query = ParseObject.GetQuery("cust_tbl"); IEnumerable<ParseObject> customers = await query.FindAsync(); customers["user"] = admin; record["score"] = 1338; await record; A: In your example, you are getting an list (IEnumerable) of objects instead of single object. Instead, try something like this: ParseQuery<ParseObject> query = ParseObject.GetQuery("cust_tbl"); // you need to keep track of the ObjectID assigned when you first saved, // otherwise you will have to query by some unique field like email or username ParseObject customer = await query.GetAsync(objectId); customer["user"] = admin; customer["score"] = 1338; await customer.SaveAsync();
doc_23532408
can someone explain what is happening in the first line ? line1: setSeconds((seconds) => seconds + 1); line2: setSeconds(seconds + 1) A: In React useState hook if you want to set a value directly in state this is how it is done in line2: where seconds can be a variable with some number value such as const seconds = 0; setSeconds(seconds + 1) If there is a previous value in state that you want to increment, this is how it is done as in line1: setSeconds((seconds) => seconds + 1); Here consider it like, setState((previousValue) => previousValue + 1) previousValue holds the value which contained in your previous state e.g seconds which in above example was 0, after execution of line 2 it will become 0 + 1 = 1; For more information A: In many cases there won't be a functional difference. It depends on whether you're just updating a state value or whether you're queueing a bunch of state value updates. The former (longer) version updates state based on the state within the queue of state updates. So if you have multiple updates, each one will see the previous update as well and can add to it. The latter (shorter) version updates state directly, based on the value you have at that time. This can be more effectively illustrated with multiple updates. For example, this code: setSeconds((sec) => sec + 1); setSeconds((sec) => sec + 1); (I've changed the variable name to illustrate that seconds was being shadowed in your example, which is often a bad practice and leads to confusion.) In this case, if the seconds state value was originally 0, then the new state after re-rendering will be 2. Because each state update queued here used the previous update. But with this code: setSeconds(seconds + 1); setSeconds(seconds + 1); Even though there are still two state updates, the second one has no knowledge of what happened in the first one. Both of them explicitly update state to 0 + 1. So when the component re-renders, even though both of these updates executed, the resulting state value will be 1 instead of 2. The main takeaway here is that state updates are queued and asynchronous. For simple one-update-and-re-render operations, it doesn't matter. But for more complex operations with potentially multiple updates to state, the callback version is how you would manage those updates. A: Line 1 is a call to function that take a callback Line 2 is a call to function that take the variable seconds + 1
doc_23532409
The error occurs in my program.cs when i use from, it underlines r. I don't understand what this error means. program.cs: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace _3._4 { class Program { static void Main(string[] args) { Reeks r = new Reeks(); var query = from i in r// error is here where i > 10 && i < 1000 select 2 * i; foreach (int j in query) { Console.Write(j); } } } } Reeks.cs: using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace _3._4 { class Reeks : IEnumerable { private int i = 1; public Reeks() { } public IEnumerator GetEnumerator() { while (true) { i = i * 2; yield return i; } } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } } } A: Linq (i.e. the from i in r syntax you are using) requires you to implement the IEnumerable<T> interface, not IEnumerable. So, as Lee pointed out, you can just implement IEnumerable<int> like this: class Reeks : IEnumerable<int> { private int i = 1; public Reeks() { } public IEnumerator<int> GetEnumerator() { while (true) { i = i * 2; yield return i; } } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } } As a note, your enumerable returns an infinite list. As such, when you enumerate it, you need to terminate it manually using something like Take() or TakeWhile(). Using where will NOT terminate the enumeration, since the .NET framework does not know that your enumerator only emits increasing values, so it will keep enumerating forever (or until you kill the process). You might try a query like this instead: var query = r.Where(i => i > 10) .TakeWhile(i => i < 1000) .Select(i => 2 * i);
doc_23532410
I have removed the cloudwatch event from lambda console but still I can see it has been invoked for few hours every 15 mins. Is this a bug or some architectural concept issue? Thanks
doc_23532411
However, when I run: Add-Type -AssemblyName System.Speech $speak = New-Object System.Speech.Synthesis.SpeechSynthesizer $speak.GetInstalledVoices().VoiceInfo It only returns "Microsoft Zira Desktop": Gender : Female Age : Adult Name : Microsoft Zira Desktop Culture : en-US Id : TTS_MS_EN-US_ZIRA_11.0 Description : Microsoft Zira Desktop - English (United States) SupportedAudioFormats : {} AdditionalInfo : {[Age, Adult], [Gender, Female], [Language, 409], [Name, Microsoft Zira Desktop]...} My goal is to be able to list all installed voices and then select one with PowerShell. I'm really confused as to why the voices work and can be selected in the UI but not via PowerShell? A: Thanks to Jeff Zeitlin for pointing me in the right direction! You have to copy voices to different paths within the registry. This script from GitHub does the trick :) Now all voices can be used and selected within PowerShell AND other third party programs! $sourcePath = 'HKLM:\software\Microsoft\Speech_OneCore\Voices\Tokens' #Where the OneCore voices live $destinationPath = 'HKLM:\SOFTWARE\Microsoft\Speech\Voices\Tokens' #For 64-bit apps $destinationPath2 = 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\SPEECH\Voices\Tokens' #For 32-bit apps cd $destinationPath $listVoices = Get-ChildItem $sourcePath foreach($voice in $listVoices) { $source = $voice.PSPath #Get the path of this voices key copy -Path $source -Destination $destinationPath -Recurse copy -Path $source -Destination $destinationPath2 -Recurse } https://gist.github.com/hiepxanh/8b6ad80f6d620cd3eaaaa5c1d2c660b2 Detailed explanation: https://www.reddit.com/r/Windows10/comments/96dx8z/how_unlock_all_windows_10_hidden_tts_voices_for/
doc_23532412
Currently i have a twitter bot that retweets, Likes & follows the user but the only problem i have is that it will only do that with a hashtag. its running off tweepy. is there anyway i can change the hashtag to a url instead. so i replace the hashtag with url to the tweet and it will still follow, like and retweet? Heres my code from time import sleep from anettecurtain import * from config import QUERY, FOLLOW, LIKE, SLEEP_TIME auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) print("Twitter bot which retweets,like tweets and follow users") print("Bot Settings") print("Like Tweets :", LIKE) print("Follow users :", FOLLOW) for tweet in tweepy.Cursor(api.search, q=QUERY).items(): try: print('\nTweet by: @' + tweet.user.screen_name) tweet.retweet() print('Retweeted the tweet') # Favorite the tweet if LIKE: tweet.favorite() print('Favorited the tweet') # Follow the user who tweeted #check that bot is not already following the user if FOLLOW: if not tweet.user.following: tweet.user.follow() print('Followed the user') sleep(SLEEP_TIME) except tweepy.TweepError as e: print(e.reason) except StopIteration: break``` ***AND MY CONFIG FILE *** ```# Edit this config file as you like QUERY = '#hashtag' LIKE = True FOLLOW = True SLEEP_TIME = 1``` A: You can change the query string you pass to Tweepy api.search QUERY = 'url:"https://github.com"' According to Twitter documentation you can search by URL using the format above (url:<your url>)
doc_23532413
This is part of the setup relevant: config { prefixLocalAnchors = all doctype = xhtml_trans baseURL = absRefPrefix = auto absRelPath = / tx_realurl_enable = 1 prefixLocalAnchors = all I have already deleted all caches, the RealURL configuration (to re-generate) and even uninstalled the extension and db tables and re-installed. Any ideas? A: Just a shot in the dark maybe on your https vhost apache configuration is missing the AllowOverride Configuration for the ssl vhost. In this case the .htaccess file will not be parsed and the nessesary rewrite rules for realurl will not be executed.
doc_23532414
I would like to optimize my iteration by improving cache performance, so I would like to allocate the objects [and not the reference] contiguously on the memory, so I'll get fewer cache misses, and the overall performance could be segnificantly better. In C++, I could just allocate an array of the objects, and it will allocate them as I wanted, but in java - when allocating an array, I only allocate the reference, and the allocation is being done one object at a time. I am aware that if I allocate the objects "at once" [one after the other], the jvm is most likely to allocate the objects as contiguous as it can, but it might be not enough if the memory is fragmented. My questions: * *Is there a way to tell the jvm to defrag the memory just before I start allocating my objects? Will it be enough to ensure [as much as possible] that the objects will be allocated continiously? *Is there a different solution to this issue? A: Sadly, there is no way of ensuring objects are created/stay at adjacent memory locations in Java. However, objects created in sequence will most likely end up adjacent to each other (of course this depends on the actual VM implementation). I'm pretty sure that the writers of the VM are aware that locality is highly desirable and don't go out of their way to scatter objects randomly around. The Garbage Collector will at some point probably move the objects - if your objects are short lived, that should not be an issue. For long lived objects it then depends on how the GC implements moving the survivor objects. Again, I think its reasonable that the guys writing the GC have spent some thought on the matter and will perform copies in a way that does not screw locality more than unavoidable. There are obviously no guarantees for any of above assumptions, but since we can't do anything about it anyway, stop worring :) The only thing you can do at the java source level is to sometimes avoid composition of objects - instead you can "inline" the state you would normally put in a composite object: class MyThing { int myVar; // ... more members // composite object Rectangle bounds; } instead: class MyThing { int myVar; // ... more members // "inlined" rectangle int x, y, width, height; } Of course this makes the code less readable and duplicates potentially a lot of code. Ordering class members by access pattern seems to have a slight effect (I noticed a slight alteration in a benchmarked piece of code after I had reordered some declarations), but I've never bothered to verify if its true. But it would make sense if the VM does no reordering of members. On the same topic it would also be nice to (from a performance view) be able to reinterpret an existing primitive array as another type (e.g. cast int[] to float[]). And while you're at it, why not whish for union members as well? I sure do. But we'd have to give up a lot of platform and architecture independency in exchange for these possibilities. A: New objects are creating in the Eden space. The eden space is never fragmented. It is always empty after a GC. The problem you have is when a GC is performed, object can be arranged randomly in memory or even surprisingly in the reverse order they are referenced. A work around is to store the fields as a series of arrays. I call this a column-based table instead of a row based table. e.g. Instead of writing class PointCount { double x, y; int count; } PointCount[] pc = new lots of small objects. use columns based data types. class PointCounts { double[] xs, ys; int[] counts; } or class PointCounts { TDoubleArrayList xs, ys; TIntArrayList counts; } The arrays themselves could be in up to three different places, but the data is otherwise always continuous. This can even be marginally more efficient if you perform operations on a subset of fields. public int totalCount() { int sum = 0; // counts are continuous without anything between the values. for(int i: counts) sum += i; return i; } A solution I use is to avoid GC overhead for having large amounts of data is to use an interface to access a direct or memory mapped ByteBuffer import java.nio.ByteBuffer; import java.nio.ByteOrder; public class MyCounters { public static void main(String... args) { Runtime rt = Runtime.getRuntime(); long used1 = rt.totalMemory() - rt.freeMemory(); long start = System.nanoTime(); int length = 100 * 1000 * 1000; PointCount pc = new PointCountImpl(length); for (int i = 0; i < length; i++) { pc.index(i); pc.setX(i); pc.setY(-i); pc.setCount(1); } for (int i = 0; i < length; i++) { pc.index(i); if (pc.getX() != i) throw new AssertionError(); if (pc.getY() != -i) throw new AssertionError(); if (pc.getCount() != 1) throw new AssertionError(); } long time = System.nanoTime() - start; long used2 = rt.totalMemory() - rt.freeMemory(); System.out.printf("Creating an array of %,d used %,d bytes of heap and tool %.1f seconds to set and get%n", length, (used2 - used1), time / 1e9); } } interface PointCount { // set the index of the element referred to. public void index(int index); public double getX(); public void setX(double x); public double getY(); public void setY(double y); public int getCount(); public void setCount(int count); public void incrementCount(); } class PointCountImpl implements PointCount { static final int X_OFFSET = 0; static final int Y_OFFSET = X_OFFSET + 8; static final int COUNT_OFFSET = Y_OFFSET + 8; static final int LENGTH = COUNT_OFFSET + 4; final ByteBuffer buffer; int start = 0; PointCountImpl(int count) { this(ByteBuffer.allocateDirect(count * LENGTH).order(ByteOrder.nativeOrder())); } PointCountImpl(ByteBuffer buffer) { this.buffer = buffer; } @Override public void index(int index) { start = index * LENGTH; } @Override public double getX() { return buffer.getDouble(start + X_OFFSET); } @Override public void setX(double x) { buffer.putDouble(start + X_OFFSET, x); } @Override public double getY() { return buffer.getDouble(start + Y_OFFSET); } @Override public void setY(double y) { buffer.putDouble(start + Y_OFFSET, y); } @Override public int getCount() { return buffer.getInt(start + COUNT_OFFSET); } @Override public void setCount(int count) { buffer.putInt(start + COUNT_OFFSET, count); } @Override public void incrementCount() { setCount(getCount() + 1); } } run with the -XX:-UseTLAB option (to get accurate memory allocation sizes) prints Creating an array of 100,000,000 used 12,512 bytes of heap and took 1.8 seconds to set and get As its off heap, it has next to no GC impact. A: Doesn't work that way in Java. Iteration is not a matter of increasing a pointer. There is no performance impact based on where on the heap the objects are physically stored. If you still want to approach this in a C/C++ way, think of a Java array as an array of pointers to structs. When you loop over the array, it doesn't matter where the actual structs are allocated, you are looping over an array of pointers. I would abandon this line of reasoning. It's not how Java works and it's also sub-optimization.
doc_23532415
I am using the correct UTF code in the HTML headers like: <meta content='text/html; charset=UTF-8' http-equiv='Content-Type'> <meta charset="UTF-8"> Here are the PHP code snippets: `<?php //Create connection credentials $db_host = 'localhost'; $db_name = 'quizzer'; $db_user = 'root'; $db_pass = ''; $mysqli = new mysqli ($db_host, $db_user, $db_pass, $db_name); if($mysqli->connect_error){ printf("Connect failed: %s\n", $mysqli->connect_error); exit(); } //Set question number $number = (int) $_GET['n']; /* * Get total questions */ $query = "SELECT * FROM `questions`"; //Get result $results = $mysqli->query($query) or die($mysqli->error.__LINE__); $total = $results->num_rows; /* * Get Question */ $query = "SELECT * FROM `questions` WHERE question_number = $number"; //Get result $result = $mysqli->query($query) or die($mysqli->error.__LINE__); $question = $result->fetch_assoc(); /* * Get Choices */ $query = "SELECT * FROM `choices` WHERE question_number = $number"; //Get results $choices = $mysqli->query($query) or die($mysqli->error.__LINE__); <?php $question['question_number']; ?> of <?php echo $total; ?> <?php echo $question['text']; ?> <?php while($row = $choices->fetch_assoc()): ?> <?php echo $row['id']; ?>" /><?php echo $row['text']; ?> <?php endwhile; ?>` A: (continuing from comment section) After connecting to mysql :- $mysqli->set_charset("utf8mb4"); This is will set your default charset to "utfmb4", so every query after this will maintain this charset. To make this 'permanent', in my.cnf: [mysqld] character-set-server=utf8mb4 collation-server=utf8mb4_unicode_ci A: Just add mysqli_set_charset($mysqli,"utf8"); $mysqli = new mysqli ($db_host, $db_user, $db_pass, $db_name); mysqli_set_charset($mysqli,"utf8");
doc_23532416
Exception in thread "main" java.awt.IllegalComponentStateException: contentPane cannot be set to null. at java.desktop/javax.swing.JRootPane.setContentPane(JRootPane.java:594) at java.desktop/javax.swing.JFrame.setContentPane(JFrame.java:679) at com.AdamT.MergeSortGui.<init>(MergeSortGui.java:18) at com.AdamT.MergeSortGui.main(MergeSortGui.java:13) My code: package com.AdamT; import javax.swing.*; class MergeSortGui extends JFrame { private JPanel panel; private JTextField inputList; private JButton submitButton; private JLabel inputLabel; private JLabel outputLabel; public static void main(String[] args) { new MergeSortGui(); } MergeSortGui() { this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setContentPane(panel); this.setTitle("MergeSort GUI"); this.add(inputList); this.add(submitButton); this.add(inputLabel); this.add(outputLabel); this.pack(); this.setVisible(true); } } I would add my form, too, but I can't because then this woudld be mostly code... I uploaded all of my project here. From what I have seen from the error, it is because it's assuming that the content of each variable is null, even though it's taken care of by my .form file. Any ideas? (I know this is a dupe of this, but that has no working answer so I really am at completely lost)
doc_23532417
I am looking for a way to pause the loop for 30 seconds and then continue. Any good advice will be appreciated. EDIT #1 The program shows "special" information based on date and time: As the time changes the information changes: 06:00 = math; 07:30 = biology. The program also shows you the time left until the next class starts. Thus the program needs to run continuously to update the time so that it knows exactly what period it is and how much time is left until the next period. EDIT #2 I want put in a "refresh" so that script I want the script to be called on a set interval so that it is not running constantly and eating the ram. This interval must be 30 seconds. A: Based on your update that provides more details I think I would use a single thread with a timer to provide a pulse to drive updates. Set the timer interval to be whatever rate you wish updates to the GUI to occur at. For instance, perhaps a refresh rate of twice a minute is what you want, in which case set the timer interval to 30*1000. Whenever the timer fires, use the current system time to work out the information that you need to display, and then display that information. Note that this answer does not tell you how to wait 30 seconds and continue. However, I suspect that this is the easiest solution to your actual problem. You don't want to block your program because that would stop the UI being responsive. It would stop you being able to interact with the UI and stop the UI from being able to paint itself. In a GUI program you must not block in the main thread. You should only block in background threads. But threads add complexity that is just needless. You don't want to block. You don't want to wait. You just need a regular pulse to drive updates. A timer. A: If you have code that blocks the GUI, you can use a background thread and an event to provide a non blocking timer. Create a new Forms application and put a TMemo component on your form. This example will add a new line with the current time to your TMemo. Main form: unit u_frm_main; interface uses u_workthread, SysUtils, Windows, Forms, SyncObjs, Classes, Controls, StdCtrls; type TForm1 = class(TForm) Memo1: TMemo; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private { Private declarations } Worker : TWorkThread; procedure ShowData; public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.ShowData; begin // do whatever you need to do here... // show current time in memo Memo1.Lines.Add(FormatDateTime('HH:NN:SS', Now)); end; procedure TForm1.FormCreate(Sender: TObject); begin // create our worker thread and start it Worker := TWorkThread.Create(3, ShowData); Worker.Start; end; procedure TForm1.FormDestroy(Sender: TObject); begin // signal our worker thread that we are done here Worker.ThreadEvent.SetEvent; // terminate and wait Worker.Terminate; Worker.WaitFor; end; end. Worker Thread: unit u_workthread; interface uses SysUtils, SyncObjs, Classes; type TWorkProc = procedure of object; TWorkThread = class(TThread) private { Private declarations } Counter : Integer; FTimeout : Integer; FEventProc: TWorkProc; procedure DoWork; protected procedure Execute; override; public ThreadEvent : TEvent; constructor Create(TimeoutSeconds : Integer; EventProc: TWorkProc ); // timeout in seconds destructor Destroy; override; end; implementation procedure TWorkThread.DoWork; begin // put your GUI blocking code in here. Make sure you never call GUI elements from this procedure //DoSomeLongCalculation(); end; procedure TWorkThread.Execute; begin Counter := 0; while not Terminated do begin if ThreadEvent.WaitFor(FTimeout) = wrTimeout then begin DoWork; // now inform our main Thread that we have data Synchronize(FEventProc); end; else // ThreadEvent has been signaled, exit our loop Break; end; end; constructor TWorkThread.Create(TimeoutSeconds : Integer; EventProc: TWorkProc); begin ThreadEvent := TEvent.Create(nil, True, False, ''); // Convert to milliseconds FTimeout := TimeoutSeconds * 1000; FEventProc:= EventProc; // call inherited constructor with CreateSuspended as True inherited Create(True); end; destructor TWorkThread.Destroy; begin ThreadEvent.Free; inherited; end; end.
doc_23532418
To do this, the propfindMethod() of a WebdavResource-object is called. When I call the method with a depth of 1, I get status 207 and a list of the 1st level files. But when I go over 1 or use DepthSupport.DEPTH_INFINITY, all I get is status 404. If further information on any aspect of this problem is needed, just ask, because I'm not even really sure where to start. A: There is no "over 1" in WebDAV PROPFIND, just 0, 1, or infinity. That being said, some servers are known not to support depth infinity for performance reasons (but in that case, you shouldn't get a 404). Do you have an HTTP trace?
doc_23532419
When I set FilesToProcess equal or less than MaxThreads it works perfectly although if I make it higher, the app freezes. I am sure it is something simple, but I just can't see it. using System; using System.ComponentModel; using System.Threading; using System.Windows.Forms; namespace bgwtest { public partial class Form1 : Form { private const int MaxThreads = 20; private const int FilesToProcess = 21; private BackgroundWorker[] threadArray = new BackgroundWorker[MaxThreads]; public Form1() { InitializeComponent(); } private void Form1Load(object sender, EventArgs e) { InitializeBackgoundWorkers(); } private void InitializeBackgoundWorkers() { for (var f = 0; f < MaxThreads; f++) { threadArray[f] = new BackgroundWorker(); threadArray[f].DoWork += new DoWorkEventHandler(BackgroundWorkerFilesDoWork); threadArray[f].RunWorkerCompleted += new RunWorkerCompletedEventHandler(BackgroundWorkerFilesRunWorkerCompleted); threadArray[f].WorkerReportsProgress = true; threadArray[f].WorkerSupportsCancellation = true; } } private void button1_Click(object sender, EventArgs e) { for (var f = 0; f < FilesToProcess; f++) { var fileProcessed = false; while (!fileProcessed) { for (var threadNum = 0; threadNum < MaxThreads; threadNum++) { if (!threadArray[threadNum].IsBusy) { Console.WriteLine("Starting Thread: {0}", threadNum); threadArray[threadNum].RunWorkerAsync(f); fileProcessed = true; break; } } if (!fileProcessed) { Thread.Sleep(50); } } } } private void BackgroundWorkerFilesDoWork(object sender, DoWorkEventArgs e) { ProcessFile((int)e.Argument); e.Result = (int)e.Argument; } private static void ProcessFile(int file) { Console.WriteLine("Processing File: {0}", file); } private void BackgroundWorkerFilesRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { if (e.Error != null) { MessageBox.Show(e.Error.Message); } Console.WriteLine("Processed File: {0}", (int)e.Result); } } } A: The problem appears to be that your workers are never completing. Why this is, I'm not sure; it has something to do with the fact that the method (and thread) you are running them from is not itself completing. I was able to solve the problem by creating another worker to assign files to the worker array: private BackgroundWorker assignmentWorker; private void InitializeBackgoundWorkers() { assignmentWorker = new BackgroundWorker(); assignmentWorker.DoWork += AssignmentWorkerOnDoWork; // ... } private void AssignmentWorkerOnDoWork( object sender, DoWorkEventArgs doWorkEventArgs ) { for( var f = 0; f < FilesToProcess; f++ ) { var fileProcessed = false; while( !fileProcessed ) { for( var threadNum = 0; threadNum < MaxThreads; threadNum++ ) { if( !threadArray[threadNum].IsBusy ) { Console.WriteLine( "Starting Thread: {0}", threadNum ); threadArray[threadNum].RunWorkerAsync( f ); fileProcessed = true; break; } } if( !fileProcessed ) { Thread.Sleep( 50 ); break; } } } } private void button1_Click( object sender, EventArgs e ) { assignmentWorker.RunWorkerAsync(); } I'm not happy with this answer because I don't know why, exactly, it didn't work as you originally designed it. Perhaps someone else can answer that...? At least this will get you a working version. EDIT: Your original version didn't work because the BackgroundWorkerFilesRunWorkerCompleted runs on the same thread as button1_Click (the UI thread). Since you are not freeing up the UI thread, the thread is never getting marked as complete. A: In completion to Ethan Brown's answer, the problem effectively comes from the fact that you are running a forever busy loop inside the UI thread. If filesToProcess is lower than the max number of threads, the loop will assign each file to one thread and exit. No problems there. But if you have more files than threads, then look at what happens when you try process the file while all threads are already running : * *you check if all threads are busy, yes they are. *You wait by doing a thread sleep. The problem is that when a background worker completes, it will post a message into the UI Thread message queue. And your UI thread is actually busy checking your threads and waiting. To solve this : * *Either you put the loop in another thread (as Ethan Brown's solution) *Eihter you add Application.DoEvents() before or after the Thread.Sleep() in order to force your UI thread to process the messages. It is not really good practice, but illustrates very well the problem here.
doc_23532420
Here's the filter: # Exim filter save /srv/domain.com/bin/mail 660 pipe "/srv/domain.com/bin/sendToMailChimp.py" It works - i.e. I can see it saving to the mail file and it does call the script.. so great! So far so good.. Here's the script: #!/usr/bin/python MAILBOX_DIR = '/srv/domain.com/mailboxes/enqace/mail' import mailbox import logging import time time.sleep(10) logging.basicConfig(filename='/srv/domain.com/mailboxes/enqace/logging.log',level=logging.DEBUG) inbox = mailbox.mbox(MAILBOX_DIR) logging.info('Script called') for key in inbox.iterkeys(): logging.info(key) message = inbox[key] subject = message['subject'] logging.info(subject) logging.info('===FINISH====') (Prints 0-6 along with subject lines of each) I can tail the log. It runs on getting an email - but seems to parse the mail mbox and completes before getting to the most recent email (i.e. the last one). It then hits the last one (the most recent) the next time an email comes in. So if there were 6 mails already in the mail file the new one - the 7th - subject line doesn't come up in the log entry. Only when an 8th comes in.. Is the script in effect running to quickly - like before exim has had a chance to send to the mail file? If so whats the work around? Adding a sleep(10) doesn't seem to do anything as seen above.. UPDATE: By pulling up a python prompt I can see that python does get the correct amount of keys (i.e. message num) when called outside of the pipe MAILBOX_DIR = 'mail' import mailbox inbox = mailbox.mbox(MAILBOX_DIR) for key in inbox.iterkeys(): print key (Prints 0-7)
doc_23532421
=> the function cor.test(M[i,], M[j,], method='spearman') where i and j are two rows from the matrix (all possible combinations are tested). The problem as you know is that I'm doing too many tests to get a very reliable p-value returned by this test. My strategy to overcome this limitation would be to generate a new probability distribution by Bootstrap on my matrix M: I would like to get 100 random matrices generated from M to do the multiple correlations on these matrices and choose the right cut-off for the p-value to get a FDR of 5%. My question is: * *What is the most efficient way to randomize my matrix? *Since it's quite time consumming (I suppose) it could be interresting if the solution could be parallelized. Thank you in advance for all the usefull answers that you'll provide to me. A: In python there is a function random.sample() in module random. If you store M as list of rows, randomly sampling n rows from matrix M without replacement would be like this M_sample = random.sample(M,n) However, for bootstrapping, you might want to do random sampling with replacement. To do this, you can use numpy.random.choice(): import numpy M_sample = numpy.random.choice(M,n,replace=True) In R, we use sample() to randomly decide the row indices to take, and then use row access to take the rows from the matrices. Randomly sampling n rows from matrix M without replacement is done as follows: indices = sample(nrow(M), n,replace=FALSE) M_sample = M[indices, ] And for randomly sampling with replacement, replace the first line with this: indices = sample(nrow(M), n,replace=TRUE)
doc_23532422
Edit for example code: /** * Integration test for Create Record **/ class CreateAndRemoveRecordSpec extends GebSpec { def 'check to make sure record 999 does not exist'() { given: 'user is at Account Page' to MyAccountPage when: 'the user clicks the sign in link' waitFor { header.signInLink.click() } and: 'user logs on with credentials' at LoginPage loginWith(TEST_USER) then: 'user is at landing page.' at MyAccountPage and: 'list of saved records is displayed' myList.displayed /* I would like some sort of if here so the test doesn't fail if there is no record*/ when: 'record 999 exists' record(999).displayed then: 'remove record 999' deleteRecord(999).click() /* continue on with other tests without failing whether or not the record exists */ } def 'test to create record 999'() {} def 'test to remove record 999'() {} A: You could do something like: when: 'record 999 exists' def displayed = record(999).displayed then: 'remove record 999' !displayed || deleteRecord(999).click() If record(999) isn't displayed then the !displayed statement will evaluate to true, and so the deleteRecord(999).click() shouldn't get evaluated, therefore causing the test to pass. When the record is displayed, !displayed will evaluate to false, and so spock will have to evaluate the deleteRecord(999).click() statement, providing the desired behavior. This works based on short-circuit evaluation (which Java and Groovy both use) http://en.wikipedia.org/wiki/Short-circuit_evaluation
doc_23532423
I don't understand the following: When I use an object literal {} in initial state immutability works fine but once const byId = (state = {}, action) => produce(state, draft => { switch (action.type) { case RECEIVE_PRODUCTS: ... ) } }) I change literal to instance of object immutability stop works const byId = (state = new SomeObject(), action) => produce(state, draft => { switch (action.type) { case RECEIVE_PRODUCTS: ... ) } }) Can you someone idea why? Thanks.. A: I have created parent object export class Immerable { public [immerable] = true; } and all classes which I need to use within produce function has this parent. Thanks. A: You typically want the first argument to produce to be a plain object or array. Optionally it could be an "immerable class", though I'm not familiar with what that would be specifically (sounds like an internal thing to me) but it's not likely what your new SomeObject() call returns. https://github.com/immerjs/immer/blob/master/src/immer.js#L61 If the first argument to produce is not one of these then it will not be "drafted". https://github.com/immerjs/immer/blob/master/src/common.js#L20
doc_23532424
@FindBy(id="TAXEI") //@FindBy(xpath="//*[@id='TAXEI']") public WebElement taxesEIvalue; public void verifyTaxesEIvalue() { //jse.executeScript("arguments[0].setAttribute('type', '')",taxesEIvalue); String value=taxesEIvalue.getAttribute("value"); System.out.println("the value is "+value); } I am facing problem to get the value in an application to compare it from excel,but unable to get value through Dom structure.The Html structure did't provide Value attribute Here is the html code for the element unable to get the value that is in text box,i have compare with that value with the excel data using data driven <div class="col-lg-6 col-md-6 col-sm-6"> <fieldset class="fsStyle"> <legend class="legendStyle"> <label class="control-label main">TAXES</label> </legend> <div class="wages"> <div class="form-group"> <div class="row"> <div class="col-sm-5"> <label class="control-label">EI</label> </div> <div class="col-sm-7"> <input type="text" class="control-label TAX pull-right" id="TAXEI" disabled="disabled"> </div> </div> </div> <div class="form-group"> <div class="row"> <div class="col-sm-5"> <label class="control-label">QPIP</label> </div> <div class="col-sm-7"> <input type="text" class="control-label TAX pull-right" id="TAXQPIP" disabled="disabled"> </div> </div> </div> <div class="form-group"> <div class="row"> <div class="col-sm-5"> <label class="control-label">CPP</label> </div> <div class="col-sm-7"> <input type="text" class="control-label TAX pull-right" id="TAXCPP" disabled="disabled"> </div> </div> </div> <div class="form-group"> <div class="row"> <div class="col-sm-5"> <label class="control-label">QPP</label> </div> <div class="col-sm-7"> <input type="text" class="control-label TAX pull-right" id="TAXQPP" disabled="disabled"> </div> </div> </div> <div class="form-group"> <div class="row"> <div class="col-sm-5"> <label class="control-label">Income Tax</label> </div> <div class="col-sm-7"> <input type="text" class="control-label TAX pull-right" id="TAXIT" disabled="disabled"> </div> </div> </div> <div class="form-group"> <div class="row"> <div class="col-sm-5"> <label class="control-label">Quebec Tax</label> </div> <div class="col-sm-7"> <input type="text" class="control-label TAX pull-right" id="TAXQTax" disabled="disabled"> </div> </div> </div> <a id="divExemptNamesIncome"></a> <p class="form-control-static"><strong id="divExemptNamesIncome"></strong></p> </div> </fieldset> </div>
doc_23532425
[someNode addChild:SKEmitterNode] A: Without parent node? SKScene:SKNode, so SKEmitterNode will always have parent node. Try setting targetNode property on emitter node to self (current SKScene).
doc_23532426
I know that the Block component outside of the map function displays but doesn't seem to be calling the Block component while running the map function. Any ideas? This is my index page: import fetch from 'isomorphic-unfetch'; import {Block} from 'components/text/block'; interface Props { games: [{ _id: string; name: string; }] } const Home: NextPage<Props> = ({games}) => { console.log(games); return ( <div> {games.map((g) => { console.log("Inside Map " + JSON.stringify(g.name)); <Block key={g._id} name={g.name}></Block> })} <Block key={games[0]._id} name={games[0].name}></Block> </div> ) }; Home.getInitialProps = async () => { const response = await fetch('http://localhost:3000/api/games') const games = await response.json(); return {games}; }; export default Home; This is my Block component: import React from 'react'; interface Props { name: string; key: string; } export let Block: React.FC<Props> = ({name}) => { console.log("JSX Block " + name); return ( <div> <h1>{name}</h1> </div> ) } A: you are not returning anything from inside the map thus (implicit) undefined gets returned and renders nothing. you need to return your Block JSX element. {games.map((g) => { console.log("Inside Map " + JSON.stringify(g.name)); return <Block key={g._id} name={g.name}></Block> // <---------------------- })}
doc_23532427
I have a table with three columns (id, text1, text2). What I want to do is generate a selectList in my view which has DataValue set to table.id, and DataText set to be = text1 + ", " + text2; (i.e. join text1 and text2 with comma separation). What do you reckon is the best way to achieve this? Cheers, Tim. A: Something like this perhaps? var v = dc.threecolumntable.Select(x => new {DataValue = x.id, DataText = x.text1 + ", " + x.text2 })
doc_23532428
My question is very simple. I want to add a directory as a "Folder Reference" to my Swift xCode project. But no way to access them. I don't need to add then using Group Reference, any suggestions? A: Update: if you are using folder references, there is no way to import them and you must reference them using the full directory path. EX: let image = UIImage(named: "Images/Icons/GoPago") That is the only way. Depending on what your project requires, I would suggest using groupings like below. The problem is that you are using folders and not grouping. There is no import needed. You just need to take everything in the folder and "group" it through xCode. Then you will be able to access it in your code. It should look as a yellow folder when you group it in there. Like so: and it should look like this: if you are copying over a directory, you would want to make sure to select create groups as follows. : A: import TestFolder works on frameworks not on group creation , actually groups are shown only for good user experience for the developers, If you right click on groups you will not find any references.
doc_23532429
plotOptions: { series: { stacking: 'normal', cursor: 'pointer', point: { events: { click:function(event){ console.log(event); //this.filter.emit([this.category, this.serie.name]); alert('Name: '+ this.category + ', Value: ' + this.y + ', Series :' + this.series.name); } } } } }, So far so good, but I need to use those values in my compoenent. The problem is that the 'this' keyword refers to the Point object and I dont see how i can use the parameters of my component if can't refer to them with 'this.'... Is there a way to access both scope(my component and the Point object) in the function triggered by the click?
doc_23532430
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@android:color/holo_blue_bright"> <androidx.appcompat.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/cardview_light_background" android:minHeight="?attr/actionBarSize" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="invites_fragment" android:textSize="30sp" android:layout_centerInParent="true"> </TextView> </androidx.appcompat.widget.Toolbar> <ListView android:id="@+id/chatList" android:layout_width="match_parent" android:layout_height="wrap_content" /> </RelativeLayout> A: Just add property in ListView android:layout_below="@+id/toolbar”
doc_23532431
I installed a model called Anuga,When I do the test_all.py. there is a failure as follows. FAIL: test_parabolic_solve_rectangular_cross_velocities_zero_h (test_kinematic_viscosity_operator.Test_kinematic_viscosity) Traceback (most recent call last): File "/home/lili/anuga_core/source/anuga/operators/test_kinematic_viscosity_operator.py", line 772, in test_parabolic_solve_rectangular_cross_velocities_zero_h assert num.allclose(u.centroid_values, num.where(h.centroid_values > 0.0, 1.0, 0.0), rtol=1.0e-1) AssertionError it is the asserterror, I don't know how to resolve it. And is it necessary I should pass all the test an validate, and then I could use the model correctly? but I still could run something even though I didn't pass all the test and validate, I don't know why. It's interesting. Thank you very much for your kindly help. Looking forwards to your help. LI LI A: To get answer question related to anuga hydro dynamic model, you should mail on their user forum. They will be in a good position to solve your queries. The email id of user forum is as follows. anuga-user-request@lists.sourceforge.net
doc_23532432
LocationWorker locationTask = new LocationWorker(); locationTask .execute(new Boolean[] {true}); class LocationWorker extends AsyncTask<Boolean, Integer, Boolean> { @Override protected void onPreExecute() {} @Override protected void onPostExecute(Boolean result) { /* Here you can call myLocationHelper.getLat() and myLocationHelper.getLong() to get the location data.*/ latitude= = myLocationHelper.getLat(); longitude= = myLocationHelper.getLong(); = } @Override protected Boolean doInBackground(Boolean... params) { //while the location helper has not got a lock while(myLocationHelper.gotLocation() == false){ //do nothing, just wait } //once done return true return true; } } This works fine inside an Activity but I am trying to run the same from inside A Service *I GET THIS ERROR AND CRASH * 01-16 22:31:57.854: W/dalvikvm(23413): threadid=11: thread exiting with uncaught exception (group=0x41f42700) 01-16 22:31:57.869: E/AndroidRuntime(23413): FATAL EXCEPTION: AsyncTask #1 01-16 22:31:57.869: E/AndroidRuntime(23413): java.lang.RuntimeException: An error occured while executing doInBackground() 01-16 22:31:57.869: E/AndroidRuntime(23413): at android.os.AsyncTask$3.done(AsyncTask.java:299) 01-16 22:31:57.869: E/AndroidRuntime(23413): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352) 01-16 22:31:57.869: E/AndroidRuntime(23413): at java.util.concurrent.FutureTask.setException(FutureTask.java:219) 01-16 22:31:57.869: E/AndroidRuntime(23413): at java.util.concurrent.FutureTask.run(FutureTask.java:239) 01-16 22:31:57.869: E/AndroidRuntime(23413): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 01-16 22:31:57.869: E/AndroidRuntime(23413): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) 01-16 22:31:57.869: E/AndroidRuntime(23413): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) 01-16 22:31:57.869: E/AndroidRuntime(23413): at java.lang.Thread.run(Thread.java:841) 01-16 22:31:57.869: E/AndroidRuntime(23413): Caused by: java.lang.NullPointerException Thank You A: You have it in your logcat (you have not pasted the most interesting part): Caused by: java.lang.NullPointerException probably NPE cause will be few lines below it. probably your myLocationHelper is null, also remember to execute asynctask always from GUI thread.
doc_23532433
How do I get the number threads that can be supported by a CPU in python? I know how to get number of cores(see code below) but don't know how to get number of threads. import multiprocessing multiprocessing.cpu_count() I am using windows 10, python 3.7. EDIT: multiprocessing.cpu_count() is right answer. It includes the effects of hyper-threading. A: I will answer my own question. The answer is already in the question. multiprocessing.cpu_count() returns the number of CPU threads supported by the CPU and this number includes the effects of hyper-threading.
doc_23532434
I tried to run the simple "Hello World" program but I encountered the error: Program "g++" not found in PATH I downloaded (on another computer and copied it) the g++_4.8.2-1ubuntu6_i386.deb and tried to install it: sudo dpkg -i g++_4.8.2-1ubuntu6_i386.deb and I got this error message: dpkg: dependency problems prevent configuration of g++:i386: g++:i386 depends on cpp (>= 4:4.8.2-1ubuntu6) g++:i386 depends on gcc (>= 4:4.8.2-1ubuntu6) g++:i386 depends on g++-4.8 (>= 4.8.2-5~) g++:i386 depends on gcc-4.8 (>= 4.8.2-5~) dpkg: error processing g++:i386 (--install) How can I install that g++ properly with no internet connection? I will be happy for some guidance. A: You have to connect your computer to internet and update the OS. sudo apt-get update sudo apt-get upgrade sudo apt-get dist-upgrade Then Try to install g++ A: You could use apt-offline. You'll need to download and install the deb file using: dpkg -i apt-offline_1.3.1_all.deb This program will download dependencies on an online machine, ready for you to copy across to install on your offline machine. Here's a link on how to use it.
doc_23532435
It looks like the following: str <- "Regular Expression Language (AbcDfE-BB)" So I would like two new columns, one with the "AbcDfE" part, and the other with the after - part, in this case "BB". A: I would try this https://regex101.com/r/oH1dV5/1 Regex > ([a-zA-Z]*)-([a-zA-Z]*) Data >AbcDfE-BB A: You may remove what you do not need with sub and then strsplit with -: str <- "Regular Expression Language (AbcDfE-BB)" strsplit(sub(".*\\(([^()]+)\\).*", "\\1", str), "-", fixed=TRUE) See the R demo Here, sub(".*\\(([^()]+)\\).*", "\\1", str) will remove all text that is not the last (...) subtext (with the parentheses), and then will split with a literal hyphen character. Pattern details: * *.* - any 0+ characters as many as possible (greedy) *\\( - a literal ( *([^()]+) - Group 1 that will be later accessed via \\1 capturing 1 or more characters other than ( and ) *\\) - a literal ) *.* - any zero or more chars up to the end of string. A: Perhaps this would do: strsplit(str,"(\\+)|\\-([a-zA-Z]+)")[[1]] A: I use this for extracting these pieces: (It's a variation on the parse.one function from ?regexpr) getMatchingPatterns <- function(data, pattern) { result <- gregexpr(pattern, data, perl = TRUE) do.call(rbind,lapply(seq_along(data), function(i) { if(any(result[[i]] == -1)) return("") st <- data.frame(attr(result[[i]], "capture.start")) le <- data.frame(attr(result[[i]], "capture.length") - 1) mapply(function(start,leng) substring(data[i], start, start + leng), st, le) })) } Then we define a perl style pattern where we name each variable, in this case (And this is a big assumption, based on one example), pattern <- "\\((?<ABCPart>.*?)-(?<BPart>.*?)\\)" so the first part I'm naming ABCPart, and the second one Bpart then call the above function with that pattern: > getMatchingPatterns(str,pattern) ABCPart BPart [1,] "AbcDfE" "BB" It returns it in a matrix form, which is easily convertible to data.frame, data.table etc... The above function will find ALL matches for the given pattern, so beware how general your pattern is.
doc_23532436
Here is my RegistrationModel where I store user data: public class CRegistrationSessionManagement { ; // User name (make variable public to access from outside) public static final String s_szKEY_MOBILENUMBER = "mobileNumebr"; public static final String s_szKEY_PASSWORD = "pin"; public static final String s_szKEY_EMAILID = "emailId"; // Sharedpref file name public static final String s_szREGIS_FILE_NAME = "RegistrationData"; // All Shared Preferences Keys private static final String s_szIS_REGISTERED = "IsRegistered"; public static String mobile; public SharedPreferences m_Regis_Pref; // Editor for Shared preferences public SharedPreferences.Editor m_editor; // Context public Context m_Context; public CRegistrationSessionManagement(Context m_Context) { this.m_Context = m_Context; m_Regis_Pref = m_Context.getSharedPreferences(s_szREGIS_FILE_NAME, Context.MODE_PRIVATE); m_editor = m_Regis_Pref.edit(); } // Registration Session Management. public void setRegisteredData(String mobile, String pin, String emailId) { m_editor.putBoolean(s_szIS_REGISTERED, true); m_editor.putString(s_szKEY_MOBILENUMBER, mobile); m_editor.putString(s_szKEY_PASSWORD, pin); m_editor.putString(s_szKEY_EMAILID, emailId); m_editor.commit(); } /** * checkRegistrtaion() session wil check user Registrtaion status * If false it will redirect user to Registrtaion page * Else won't do anything */ public boolean checkRegistration() { if (!isRegistered()) { Intent i = new Intent(m_Context, CMainActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); m_Context.startActivity(i); return true; } return false; } /** * Get stored Registration session data */ public HashMap<String, String> getRegistrationDetails() { HashMap<String, String> user = new HashMap<>(); // user name user.put(s_szKEY_MOBILENUMBER, m_Regis_Pref.getString(s_szKEY_MOBILENUMBER, null)); // user email id user.put(s_szKEY_PASSWORD, m_Regis_Pref.getString(s_szKEY_PASSWORD, null)); user.put(s_szKEY_EMAILID, m_Regis_Pref.getString(s_szKEY_EMAILID, null)); // return user return user; } public boolean isRegistered() { return m_Regis_Pref.getBoolean(s_szIS_REGISTERED, false); } } How can I fetch mobile and password in activity where I want to ...by only creating instance of this class...instead of creating every time a new object of that class. A: You can use static method. Instead of public HashMap<String, String> getRegistrationDetails () you can use public static HashMap<String, String> getRegistrationDetails (). So when you want to use your getter. CRegistrationSessionManagement. getRegistrationDetails () . Take a look to this example to know more about static method and their uses. Java: when to use static methods
doc_23532437
$ kubectl get service NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 4s I tried to delete the service: $ kubectl delete --all services --all-namespaces service "kubernetes" deleted $ kubectl get service NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 2s It is deleted but it restarts by itself. I have deleted all pod and deployment. But what makes the service restart? How can I delete the whole service? A: You can not delete the kubernetes service. Even if you delete it it will be re-created by kubernetes control plane. This service points to Kubernetes API Server pods and does not make sense to be deleted by users because that can render many other critical components that depends on this service non-functional.
doc_23532438
I tried passing the below snippet but doe not help much. Any help please? Application.SendKeys ("%(Y1)")
doc_23532439
I have an < Nx1 cell> 'A' and each N element measures < some multiple of 48 (which varies) x3 double> constructed using: A=arrayfun(@(x) A(A(:,end)==x,:), unique(A(:,end)), 'UniformOutput', false); I'm trying to extract the rows from 4 of the 48 slots for all multiples of 48, retaining the information for the entire row. I've tried variants of cell2mat(vertcat... without success and would really appreciate any assistance, or even a suitable link.
doc_23532440
I am doing BLE scan which needs Bluetooth as well as location permissions (Android >=23). I am NOT providing the Location permission to the App before starting the BLE scan. While starting a scan on Note 8, I am getting onScanFailed() callback with error code 2 (SCAN_FAILED_APPLICATION_REGISTRATION_FAILED) when the location permission is not given. While starting scan on A50, I do not get any callbacks. From the adb logs I can see internal log like BluetoothUtils: Permission denial: Need ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATIONpermission to get scan results 07-28 21:03:35.720 2010 2650 D I want to identify a scan failure has occurred because of missing permission. How do i do that? Note- I am building an Android library, not an Android App so please suggest accordingly. A: There are a few things it could be. Firstly note for a BLE scan you need permission to location and bluetooth. Therefore, in your developing environment you will need to specify this. For example in android studio you need to go into the manifest and specifically give permission to both bluetooth and location. See below: <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> However, this will not be enough as within your phone app you will need to give the permission from the user. As you are running android you will need to give the location permission(and turn on location and bluetooth) then the scan will work. To allow location go to: * *Settings *Your apps *Find your app *App info *Permissions *Allow location permission To summarise check your IDE has the permissions enabled. Then check on the app(on the phone) that the user has allowed the permission.
doc_23532441
I'll try like this : override/themes/default/mails/fr/order_conf.html But it doesn't works. Any idea? Thanks! A: I found the solution. To override the mails in prestashop, you need to copie de folder root/mails/ into your root/themes/your_theme_name/ Like this you can modify the mails look and It will ne not lost when you upgrade your prestashop. I hope it can help... bye
doc_23532442
I use Google App Engine to run the server,and my python version is 2.7. here is my server dir D:\PJ\Udacity\Python\engineapp my program is edited in main.py in this dir,then,i try to do this in the file: import os import webapp2 import jinja2 when i build this file,error occurs Traceback (most recent call last): File "D:\PJ\Udacity\Python\engineapp\main.py", line 18, in import webapp2 ImportError: No module named webapp2 I haved set the python path as someone said before How to add to the pythonpath in windows 7? PYTHONPATH D:\Python27; D:\Program Files (x86)\Google\google_appengine; D:\Program Files (x86)\Google\google_appengine\lib; but,after doing this,i still got the import error. If anyone had solved related problem,please tell,i really appreciate you help. A: The webapp2 you are trying to use will be deployed on the google cloud, having it in the local environment is fair enough only upto the point of testing it. webapp2 also is there in a form of a library which is available in python app engine without having to put it in the lib folder. You might want to read up this modify your app.yaml file and add the following in the libraries section if there is one or just add it whole - libraries: - name: webapp2 version: latest if this still doesn't solve your problem you might want to read up an issue raised earlier this month - [Here]. As mentioned If your SDK version is 1.9.37 or 1.9.38 downgrade to 1.9.36 until a fix is released soon.(https://stackoverflow.com/a/37764786/4495081) and use a previous sdk build as mentioned
doc_23532443
The images that display next to the KPI are already coded to be conditional on the value of the KPI itself. For one example: =Iif( ReportItems!LaborEntry.Value >= 0.95, "Green", Iif( ReportItems!LaborEntry.Value >= 0.85, "Yellow", "Red" ) ) Where "Green," "Yellow," and "Red" are the images in the report which correspond to the values. NOW, here's the question: how would I count up how many greens are in my report, for example? I need to be able to score them, but I don't necessarily know at run-time what each image will be. A: Nested calculations can get messy. When you encounter a situation like this, it usually makes sense to create a calculated field on your dataset. In this case, make your IIf statement a calculated field. This simplifies the expression to select an image. And of course it is trivial to simply aggregate your new column!
doc_23532444
here is my code on KonsumerFragment.java public class KonsumerFragment extends Fragment implements View.OnClickListener{ public KonsumerFragment() { // Required empty public constructor } float marginValue; Spinner spinnerProduct; Spinner spinnerType; EditText pengajuan; EditText tenor; TextView tvAngsuran; String[] arrayMargin; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_konsumer, container, false); //Define Variables spinnerProduct = (Spinner) v.findViewById(R.id.spinnerProduct) ; spinnerType = (Spinner) v.findViewById(R.id.spinnerType); pengajuan = (EditText) v.findViewById(R.id.etPengajuan); tenor = (EditText) v.findViewById(R.id.etTenor); // Inflate the layout for this fragment Button hitung = (Button) v.findViewById(R.id.btnHitung); hitung.setOnClickListener(this); return v; } @Override public void onClick(View view) { try { switch (view.getId()){ case R.id.btnHitung : //simulate(); readMargin(); break; } } catch (Exception e){ e.getCause(); e.printStackTrace(); } } public void readMargin() throws FileNotFoundException { try { InputStream in = getContext().getResources().openRawResource(R.raw.margingriyafix); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line = reader.readLine(); String result = ""; while(line !=null){ result += line + "\n"; } arrayMargin = result.split("\\n"); for (int i=0 ; i<arrayMargin.length ; i++){ System.out.println(arrayMargin[i]); } System.out.println(arrayMargin); } catch (Exception e){ System.out.println(e); e.getCause(); } } } MainActivity.java public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); KonsumerFragment konsFragment = new KonsumerFragment(); FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.replace(R.id.frameLayout, konsFragment); transaction.commit(); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.nav_konsumer) { KonsumerFragment konsFragment = new KonsumerFragment(); FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.replace(R.id.frameLayout, konsFragment); transaction.commit(); } else if (id == R.id.nav_produktif) { ProduktifFragment prodFragment = new ProduktifFragment(); FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.replace(R.id.frameLayout, prodFragment); transaction.commit(); } else if (id == R.id.nav_share) { } else if (id == R.id.nav_send) { } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } the part of the reading file has been in the right way. I tested it running on MainAcivity directly. but it won't run on Fragment. it has been successfully running on an Activity, I believe that the problem comes from the InputStream, but anyway I've tried doing like getActivity().getResources().openRawResource(R.raw.margingriyafix); and also getContext().getResources().openRawResource(R.raw.margingriyafix); still not working. please anyone help me.
doc_23532445
comm -23 <( find /dir1/report_dir2/dir3/2013* -name *\*MyFile* -exec basename {} \; | sort | uniq ) <( find /dir0/dir1/dir2/loadedreports/archive* -name *\*MyFile* -exec basename {} \; | sort | uniq ) > /home/Ben10/list.txt Directory 1 The files in /dir1/report_dir2/dir3/2013* are csv files that may or may not have a .gz extension in their name, unzipping them would be out of the question as they're up to a gig each, and i've thousands of them. i.e they'll look like MyFile20130618073529.csv or MyFile20130618073529.csv.gz Directory 2 The files in /dir0/dir1/dir2/loadedreports/archive* have been loaded to a BI system, and will all end in .csv, however, they will also be preceeded by dates of when they were loaded, i.e. 2013-11-06_MyFile20130618073529.csv I'm loading them into a BI DB from these csv files, and to check which ones i've loaded I need to check which ones are in /dir1/report_dir2/dir3/2013* but not in dir0/dir1/dir2/loadedreports/archive* is there any way to disregard the .gz, and the 2013-11-06_ ? note, the 2013-11-06_ can be any date preceeding MyFile. Thanks a million, any input greatly appreciated. A: Try following comm -23 <( find /dir1/report_dir2/dir3/2013* -name '*MyFile*' | perl -pe 's/.*(MyFile[^.]*\.csv)(\.gz)?$/$1/' | sort -u ) <( find /dir0/dir1/dir2/loadedreports/archive* -name '*MyFile*' | perl -pe 's/.*(MyFile[^.]*\.csv)$/$1/' | sort -u ) > /home/Ben10/list.txt Here idea is to use perl search and replace, in place of basename, on found full file names to get desired basenames discarding .gz suffix and <date>_ prefix To make above one liner more readable, I would prefer splitting it as follows find /dir1/report_dir2/dir3/2013* -name '*MyFile*' | perl -pe 's/.*(MyFile[^.]*\.csv)(\.gz)?$/$1/' | sort -u > /home/Ben10/di1_list.txt find /dir0/dir1/dir2/loadedreports/archive* -name '*MyFile*' | perl -pe 's/.*(MyFile[^.]*\.csv)$/$1/' | sort -u > /home/Ben10/di2_list.txt comm -23 /home/Ben10/di1_list.txt /home/Ben10/di2_list.txt > /home/Ben10/list.txt rm /home/Ben10/di1_list.txt /home/Ben10/di2_list.txt
doc_23532446
chmod go-w ~/ chmod 700 ~/.ssh chmod 600 ~/.ssh/authorized_keys But the problem persists. Here is the output from ssh -v localhost: (tutorial)bnels21-2:tutorial bnels21$ ssh -v localhost OpenSSH_5.9p1, OpenSSL 0.9.8r 8 Feb 2011 debug1: Reading configuration data /etc/ssh_config debug1: /etc/ssh_config line 20: Applying options for * debug1: Connecting to localhost [::1] port 22. debug1: Connection established. debug1: identity file /Users/bnels21/.ssh/id_rsa type 1 debug1: identity file /Users/bnels21/.ssh/id_rsa-cert type -1 debug1: identity file /Users/bnels21/.ssh/id_dsa type -1 debug1: identity file /Users/bnels21/.ssh/id_dsa-cert type -1 debug1: Remote protocol version 2.0, remote software version OpenSSH_5.9 debug1: match: OpenSSH_5.9 pat OpenSSH* debug1: Enabling compatibility mode for protocol 2.0 debug1: Local version string SSH-2.0-OpenSSH_5.9 debug1: SSH2_MSG_KEXINIT sent debug1: SSH2_MSG_KEXINIT received debug1: kex: server->client aes128-ctr hmac-md5 none debug1: kex: client->server aes128-ctr hmac-md5 none debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP debug1: SSH2_MSG_KEX_DH_GEX_INIT sent debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY debug1: Server host key: RSA 1c:31:0e:56:93:45:dc:f0:77:6c:bd:90:27:3b:c6:43 debug1: Host 'localhost' is known and matches the RSA host key. debug1: Found key in /Users/bnels21/.ssh/known_hosts:11 debug1: ssh_rsa_verify: signature correct debug1: SSH2_MSG_NEWKEYS sent debug1: expecting SSH2_MSG_NEWKEYS debug1: SSH2_MSG_NEWKEYS received debug1: Roaming not allowed by server debug1: SSH2_MSG_SERVICE_REQUEST sent debug1: SSH2_MSG_SERVICE_ACCEPT received debug1: Authentications that can continue: publickey,keyboard-interactive debug1: Next authentication method: publickey debug1: Offering RSA public key: /Users/bnels21/.ssh/id_rsa debug1: Authentications that can continue: publickey,keyboard-interactive debug1: Offering RSA public key: id_rsa3 debug1: Authentications that can continue: publickey,keyboard-interactive debug1: Trying private key: /Users/bnels21/.ssh/id_dsa debug1: Next authentication method: keyboard-interactive Password: Any suggestions? I'm running OSX 10.8. A: Since you seem to have multiple keys I would assign the specific key to a specific connection in ~/.ssh/config. Example: Host local HostName 127.0.0.1 Port 22 User your_username IdentityFile ~/.ssh/your_key-id_rsa Then just try to ssh local. A: I had same problem. I checked the system passwd and group files, and discovered that my user and group was not present. To build this files (my user was a domain user) I need to run two commands at cygwin shell: mkpasswd -l -d > /etc/passwd mkgroup -l -d > /etc/group After that, ssh works fine! Elvys Borges A: It looks like you are using protocol version 2.0 when connecting to localhost, so try moving authorized_keys to authorized_keys2. Source: this post explains the difference between the two keys files. A: I was at my wits end... I was under the mistaken impression ssh-copy-id was a Linux-only utility. Finally I just swallowed my pride and typed the command is the macOS Terminal and it worked! ssh-copy-id me@sshd-server I don't know what magic ssh-copy-id does, but it just worked. I was able to log in without a password successfully with the simple command: ssh me@sshd-server I had zero luck with cat id_rsa.pub >> ~/.ssh/authorized_hosts. Every time I tried ssh'ing to the server it just kept asking me for the passphrase. This is with the correct 600 permission on authorized_hosts and 700 on ~/.ssh.
doc_23532447
Install sudo easy_install pygments sudo echo 'export RAILS_ENV=production' >> ~/.bash_profile sudo adduser --system --shell /bin/sh --gecos 'git version control' --group --disabled-password --home /home/git git ssh-keygen -t rsa sudo -H -u git gitosis-init < ~/.ssh/id_rsa.pub sudo chmod 755 /home/git/repositories/gitosis-admin.git/hooks/post-update echo "gem: --no-rdoc --no-ri" > ~/.gemrc rvmsudo gem install passenger rvmsudo passenger-install-nginx-module Creating an Upstart file for nginx sudo vim /etc/init/nginx.conf description "Nginx HTTP Server" start on filesystem stop on runlevel [!2345] respawn exec /opt/nginx/sbin/nginx -g "daemon off;" Restart the VM sudo shutdown -r now Verify nginx running sudo initctl list | grep nginx A: This is not necessarily the perfect way to do this, but it should work (note I haven't tested). In your metadata for your cookbook, first make sure you have this: depends "python" then your recipe can look like this: pip_package "pygments" execute "echo 'export RAILS_ENV=production' >> ~/.bash_profile" do not_if "grep RAILS_ENV ~/.bash_profile" end user "git" do system True end execute "ssh-keygen -N '' -f ~/.ssh/id_rsa" user "git" not_if "test -f /home/git/.ssh/id_rsa" end execute "gitosis-init < ~/.ssh/id_rsa.pub && chmod 755 ~/repositories/gitosis-admin.git/hooks/postupdate" #not sure how do check if this has been run, maybe this is right: not_if "test -f /home/git/repositories/gitosis-admin.git/hooks/post-update" end gem_package "passenger" do action :install end #Instead of creating your own upstart service, why not use the stock nginx config. include_recipe "nginx" execute "passenger-install-nginx-module" do #I'm not familiar with this, so I don't know how to check if it's already been run. notifies :restart, "service[nginx]" end most of this info should be pretty accessible from the chef docs, btw.
doc_23532448
Sub Import_AccessData() Dim strtKeyMsgRange As Range Dim KeyMsgRange As Range Dim KeyMsgRangeCell As Range Dim endKeyMsgRangeCell As Range Set strtKeyMsgRange = Range("B2") Set endKeyMsgRange = Range("AC13") Set KeyMsgRange = Range(strtKeyMsgRange, endKeyMsgRange) For Each KeyMsgRangeCell In KeyMsgRange a = StripHTML(KeyMsgRangeCell) KeyMsgRangeCell.Value = a Next KeyMsgRangeCell End Sub Public Function StripHTML(cell As Range) As String Dim RegEx As Object Set RegEx = CreateObject("vbscript.regexp") Dim sInput As String Dim sOut As String sInput = cell.Value With RegEx .Global = True .IgnoreCase = True .MultiLine = True .Pattern = "<[^>]+>" 'Regular Expression for HTML Tags. .Pattern = "&nbsp;" .Pattern = "&amp;" End With sOut = RegEx.Replace(sInput, "") StripHTML = sOut Set RegEx = Nothing End Function A: You are setting the Pattern property multiple times, it will only retain the last value assigned (&amp;). You need to use 3 regular expressions("<[^>]+>" => "", "&nbsp;" => " ", "&amp;" => "&"), or one expression that matches all of your inputs ("(&amp;)|(&nbsp;)|(<[^>]+>)" => "") to actually do this.
doc_23532449
row id value 35395 776130 0 35395 776131 20 35395 776132 40 35395 776133 60 35395 776134 80 35395 776135 100 35395 776136 120 35395 776137 140 35395 776138 160 35395 776139 180 35395 776140 200 And I want to change the values so that they are ordered in descending order (flip the row 180degrees): row id value 35395 776130 200 35395 776131 180 35395 776132 160 35395 776133 140 35395 776134 120 35395 776135 100 35395 776136 80 35395 776137 60 35395 776138 40 35395 776139 20 35395 776140 0 How can I do this using an update statement without doing it one by one? A: I don't know the nature of the problem, but only based on your example, can't you update all rows doing UPDATE `thetable` SET value = 200 - value Again, I don't know the nature of the problem so it might not be this easy, but then again this seem to work in your simplified example and might as well work in your real world problem. A: With help from Seb's answer I have formulated a solution: declare @maxcoord int; declare @rowid int; set @rowid = 35395 select @maxcoord = max(value) from table where row = @rowid update table set value = @maxcoord - value where row = @rowid I think I will create a stored procedure for this as I don't think this will be the only time it will be used :) A: If you are using SQL Server 2005 or later, this might do it for you. The advantage is that it's a single query. with T1(rn,row,id,value) as ( select rank() over ( order by value,row,id ), row,id,value from T ), T2(rn,value) as ( select row_number() over ( order by value desc ), value from T ), T12(row,id,value,vnew) as ( select row,id,T1.value,T2.value from T1 join T2 on T1.rn = T2.rn ) update T12 set value = vnew; I assumed the "value" column was originally increasing, and you want it decreasing, but I allowed for the possibility of two consecutive values being the same, so long as (row,id) is a key for the table. There are other possibilities. For example, if (row,id) is a key, and you want to reverse the order of the "value" values from whatever position they're at to the "mirror" position, you could do this: with T1(rn,row,id,value) as ( select rank() over ( order by row,id ), row,id,value from T ), T2(rn,value) as ( select rank() over ( order by row desc,id desc ), value from T ), T12(row,id,value,vnew) as ( select row,id,T1.value,T2.value from T1 join T2 on T1.rn = T2.rn ) update T12 set value = vnew; With the right indexes, this could be relatively efficient. A: Do you want to actually update the rows, or do you just want to display them in reverse order? If it's just display order, try this: SELECT row, id, 200-value as Value FROM YourTable ORDER BY (200-value) DESC
doc_23532450
public class CircularList<E> implements List<E> { Node<E> list; int size; public CircularList() { list = new Node(null); list.setNext(list); size = 0; } @Override public void add(E element) { Node<E> newNode = new Node(element); newNode.setNext(list.getNext()); list.setNext(newNode); size++; } @Override public boolean remove(E element) { Node<E> location = find(element); if (location != null) { location.setNext(location.getNext().getNext()); size--; } return location != null; } @Override public E get(E element) { Node<E> location = find(element); if (location != null) { return (E) location.getNext().getInfo(); } return null; } @Override public boolean contains(E element) { return find(element) != null; } @Override public int size() { return size; } @Override public Iterator<E> iterator() { return new Iterator<E>() { Node<E> tmp = list.getNext(); @Override public boolean hasNext() { return tmp != list; } @Override public E next() { E info = tmp.getInfo(); tmp = tmp.getNext(); return info; } @Override public void remove() { throw new UnsupportedOperationException("Not supported yet."); } }; } protected Node<E> find(E element) { Node<E> tmp = list; while (tmp.getNext() != list && !tmp.getNext().getInfo().equals(element)) { tmp = tmp.getNext(); } if (tmp.getNext() == list) { return null; } else { return tmp; } } public void reversePrinter() { Stack stack = new Stack(); Node<E> temp = list; for (int i = 0; i < size; i++) { stack.push(temp.getInfo()); temp = temp.getNext(); } while (! stack.empty()) { System.out.print(stack.pop()); } } } Node.java public class Node<E> { E info; Node<E> next; public Node(E element) { info = element; next = null; } public void setInfo(E element) { info = element; } public E getInfo() { return info; } public void setNext(Node<E> next) { this.next = next; } public Node<E> getNext() { return next; } } Main.java public class Main { public static void main(String[] args) { CircularList<String> x = new CircularList<String>(); x.add("hi"); x.add("hhhh"); x.add("hi"); x.add("hhhh"); x.add("hi"); x.reversePrinter(); } } This prints: hhhh hi hhhh hi null it should print: hi hhhh hi hhhh hi Please help me fix. Thanks! A: Consider replacing your loop: for (int i = 0; i < size; i++) { stack.push(temp.getInfo()); temp = temp.getNext(); } with the following using your Iterator: for (Node<E> n : this) { stack.push(n); } equivalently: public void reversePrinter() { Stack stack = new Stack(); //create a stack for reversing order Iterator<E> it = this.iterator(); //get this object's iterator while(it.hasNext()) //while there is still another object stack.push(it.next()); //add the next object to the stack while(!stack.empty()) //while the stack is not empty System.out.print(stack.pop()); //print the data from the stack } Assuming your iterator is implemented correctly this should work A: The field list always points to an extraneous Node with a null element. Stack<E> stack = new Stack<>(); Node<E> temp = list.getNext(); A: The problem is in the reversePrinter method : public void reversePrinter() { Stack<E> stack = new Stack(); Node<E> temp = list.getNext(); for (int i = 0; i < size; i++) { stack.push(temp.getInfo()); temp = temp.getNext(); } while (! stack.empty()) { System.out.print(stack.pop()); } } Initialize Node<E> temp = list.getNext(); Instead of Node<E> temp = list; Works using iterators too.
doc_23532451
I can get my iframe like this: var iframe = document.getElementById('preview'); var win = iframe.contentWindow; var doc = win.document; And write some initial HTML to it like this: doc.write('<!DOCTYPE html><html><head><link rel="stylesheet" type="text/css" href="reset.css"></head><body>blah blah</body></html>'); And that works great, but now I want to replace the entire thing with some new content. How can I do that? To be clear, by "entire thing" I mean the <head> too. I need to link some external JS and CSS there. Preferably, this would also include the <!DOCTYPE>, but it's non-essential at this point. A: You could simply remove the old iframe node from the DOM and create a new one containing the new contents. A: I believe using innerHTML should work: doc.documentElement.innerHTML = "<script src='blah.js'></script><style></style>"
doc_23532452
is there any method to get the column name instead of column number? String name =sheets.getRow(choosenRow).getCell(choosenCell).getStringCellValue(); A: Try this: int colNum = -1; // what you need String searchingCol = "Last Name"; // what you are searching for String colHeader; // what is found in each column do { colNum++; // incrementing to move to the next column // get the header name colHeader = sheets.getRow(0).getCell(colNum).getStringCellValue(); if (searchingCol.equals(colHeader)) break; // exit the loop once the column is found } while(!colHeader.equals("")); // loop back only if the the file has more columns Note that this was not tested, and to be frank with you, I've never used Apache POI before. Try to see if there is columnIterator, which can be useful.
doc_23532453
const StyledCard = styled.div` background: #008080; color: white; border-radius: 5px; border: solid #008080; `; render() { return( <StyledCard classname = "card"> <article className="card-body"> <ButtonForm name='' label='' /> <form> <TextInput name="" label="" /> </form> </article> </StyledCard> ); } }; This is working fine, however if I want to make the StyledCard reusable in a separate file (let´s call it CardForm.js) it doesn´t work as expected. CardForm.js: const StyledCard = styled.div` background: #008080; color: white; border-radius: 5px; border: solid #008080; `; const CardForm = () => { return ( <StyledCard className="card"> <article className="card-body"> </article> </StyledCard> ); }; export default CardForm And then if CardForm is importet in MyComponent.js like so: import CardForm from '../Templates/Card'; render() { return( <CardForm> <ButtonForm name='' label='' /> <form> <TextInput name="" label="" /> </form> </CardForm> ); } }; It doesn´t Work meaning the other Form elements inside CardForm do not get rendered. What am i doing wrong here? A: Try this for CardForm. Put children inside the article. Otherwise children will override article. const CardForm = ({children}) => ( <StyledCard className="card"> <article className="card-body"> {children} </article> </StyledCard> )
doc_23532454
The server/site gets progressively slower as longer the server is online. After a fresh php-fpm restart, the performance is acceptable. However, as it progresses, time to first byte gets worse and worse. We've had sys admins here and at the hosting company with no solution. I guess the best way to find help is to ask: Has anyone experienced this problem? We don't believe the issue is related to not having enough server power or memory. A: The first place that I would check would be your error logs. Super-sized logs combined with unaddressed (and therefore continually logged) errors can lead to significant load time increases.
doc_23532455
I have a lower triangular transformation matrix A = [(a, 0), (c, d)] this matrix maps points on a unit circle to an ellipse. I want to get some information about the extent of this ellipse so I decomposed the matrix using svd: U, S, V = svd(A) My intuition says that S will have reasonably good approximations the the extent in the x and y direction. S = [(x, 0), (0, y)] I have been using S[0,0] as my x-extent and S[1, 1] as my y-extent. And this works reasonably well about half the time: when the x-extent is larger than the y-extent. I found out that the reason is because the implimentations of svd I've tried (cv2.SVDecomp, and numpy.linalg.svd) sort the elements on the diagonal of S. It also seems like this is a relatively standard thing to do. My question is if there is any way to always have S[0,0] correspond to the scale factor in the x-direction and S[1,1] correspond to the scale factor in the y-direction. This will become very important later on because when I'll need to recombine my SVD matrixes and I don't want my result matrixes to be permutations of my input matrixes. How do I work around this? Can I simply swap the rows and columns of U, S, and V if(a > d)? Could I test if abs(U[0,0]) < abs(U[0, 1])? or if abs(V[0,0]) < abs(V[0, 1])? It seems like one of those would work, but I can't prove it to myself for general cases and I really want to knick this problem in the butt. I was playing with some examples earlier. The Input: is my A matrix. The lines below the input are U * S * V = A' +---- Input: [[ 0.5 0. ] [ 1. 0.5]] [[ 0.383 -0.924] * [[ 1.207 0. ] * [[ 0.924 0.383] = [[ 5.000e-01 5.551e-17] [ 0.924 0.383]] [ 0. 0.207]] [-0.383 0.924]] [ 1.000e+00 5.000e-01]] --- +---- Input: [[ 1. 0. ] [ 1. 0.5]] [[ 0.662 -0.75 ] * [[ 1.46 0. ] * [[ 0.966 0.257] = [[ 1. 0. ] [ 0.75 0.662]] [ 0. 0.342]] [-0.257 0.966]] [ 1. 0.5]] --- +---- Input: [[ 1.5 0. ] [ 1. 0.5]] [[ 0.811 -0.585] * [[ 1.825 0. ] * [[ 0.987 0.16 ] = [[ 1.500e+00 2.776e-17] [ 0.585 0.811]] [ 0. 0.411]] [-0.16 0.987]] [ 1.000e+00 5.000e-01]] --- +---- Input: [[ 0.5 0. ] [ 0.8 0.8]] [[ 0.324 -0.946] * [[ 1.19 0. ] * [[ 0.772 0.636] = [[ 0.5 0. ] [ 0.946 0.324]] [ 0. 0.336]] [-0.636 0.772]] [ 0.8 0.8]] --- +---- Input: [[ 1. 0. ] [ 0.8 0.8]] [[ 0.643 -0.766] * [[ 1.397 0. ] * [[ 0.899 0.438] = [[ 1.000e+00 5.551e-17] [ 0.766 0.643]] [ 0. 0.573]] [-0.438 0.899]] [ 8.000e-01 8.000e-01]] --- +---- Input: [[ 1.5 0. ] [ 0.8 0.8]] [[ 0.829 -0.559] * [[ 1.749 0. ] * [[ 0.967 0.256] = [[ 1.5 0. ] [ 0.559 0.829]] [ 0. 0.686]] [-0.256 0.967]] [ 0.8 0.8]] --- +---- Input: [[ 0.5 0. ] [ 0.6 1.1]] [[ 0.212 -0.977] * [[ 1.279 0. ] * [[ 0.541 0.841] = [[ 0.5 0. ] [ 0.977 0.212]] [ 0. 0.43 ]] [-0.841 0.541]] [ 0.6 1.1]] --- +---- Input: [[ 1. 0. ] [ 0.6 1.1]] [[ 0.534 -0.845] * [[ 1.396 0. ] * [[ 0.746 0.666] = [[ 1.000e+00 5.551e-17] [ 0.845 0.534]] [ 0. 0.788]] [-0.666 0.746]] [ 6.000e-01 1.100e+00]] --- +---- Input: [[ 1.5 0. ] [ 0.6 1.1]] [[ 0.823 -0.569] * [[ 1.695 0. ] * [[ 0.929 0.369] = [[ 1.500e+00 1.110e-16] [ 0.569 0.823]] [ 0. 0.974]] [-0.369 0.929]] [ 6.000e-01 1.100e+00]] --- +---- Input: [[ 0.5 0. ] [ 0.4 1.4]] [[ 0.105 -0.994] * [[ 1.463 0. ] * [[ 0.308 0.951] = [[ 0.5 0. ] [ 0.994 0.105]] [ 0. 0.478]] [-0.951 0.308]] [ 0.4 1.4]] --- +---- Input: [[ 1. 0. ] [ 0.4 1.4]] [[ 0.305 -0.952] * [[ 1.499 0. ] * [[ 0.458 0.889] = [[ 1. 0. ] [ 0.952 0.305]] [ 0. 0.934]] [-0.889 0.458]] [ 0.4 1.4]] --- +---- Input: [[ 1.5 0. ] [ 0.4 1.4]] [[ 0.744 -0.668] * [[ 1.67 0. ] * [[ 0.828 0.56 ] = [[ 1.500e+00 1.110e-16] [ 0.668 0.744]] [ 0. 1.258]] [-0.56 0.828]] [ 4.000e-01 1.400e+00]] --- +---- Input: [[ 0.5 0. ] [ 0.2 1.7]] [[ 0.037 -0.999] * [[ 1.713 0. ] * [[ 0.128 0.992] = [[ 0.5 0. ] [ 0.999 0.037]] [ 0. 0.496]] [-0.992 0.128]] [ 0.2 1.7]] --- +---- Input: [[ 1. 0. ] [ 0.2 1.7]] [[ 0.102 -0.995] * [[ 1.718 0. ] * [[ 0.175 0.985] = [[ 1.000e+00 -2.776e-17] [ 0.995 0.102]] [ 0. 0.99 ]] [-0.985 0.175]] [ 2.000e-01 1.700e+00]] --- +---- Input: [[ 1.5 0. ] [ 0.2 1.7]] [[ 0.354 -0.935] * [[ 1.745 0. ] * [[ 0.411 0.911] = [[ 1.500e+00 -1.110e-16] [ 0.935 0.354]] [ 0. 1.462]] [-0.911 0.411]] [ 2.000e-01 1.700e+00]] --- It seems like A' is always equal to A, so I don't think I have to worry about re combinations giving me permutations. It also seems like it is always the case that when abs(V[0,1]) > abs(V[0, 0]) that the x and y extents have been swapped in the S matrix. Is this always true? Can anyone give me an example of when it is not true? Thanks two both of the answers bellow I've have understood how to write a solution to my problem. Here is the code I wrote for any other wanderers who stumble upon this import cv2 import numpy as np from numpy import (array, sin, cos, sqrt) def svd(M): # V is actually Vt flags = cv2.SVD_FULL_UV S, U, Vt = cv2.SVDecomp(M, flags=flags) s = S.flatten() return U, s, Vt def get_UsVt_list(M_list): UsV_list = [svd(M) for M in M_list] return UsV_list def get_USVt_list(M_list): UsV_list = get_UsVt_list(M_list) USV_list = [(U, np.diag(s), V) for U, s, V in UsV_list] return USV_list def USVt_axis_extent(U, S, Vt): return sqrt(U.dot(S) ** 2).T.sum(0) A: the singular values proportional to the length of principal axes that may or may not be oriented along x, y. Check U to see how they are oriented. Its columns show the coordinate of those axes. The beauty of SVD is that it can be applied to any matrix A=USVT and its components have this meaning: VT - rotation matrix that rotates a circle (rotates its point vectors) to orient them properly for the next scaling operation. In other words circle remains a circle but data points slide along it (getting re-mapped) to orient them properly for the next operation. For example, if vector 1, 1 is to be squeezed it is better be aligned with 0, 1 S - scaling that always happens along x, y (this means x coordinates are scaled by sigmaX and y coordinates are scaled by sigmaY); thus it was important to pre-rotate data in case scaling is need to be done not at X, Y axis directions but at a different directions; it is like you know you are gonna get squeezed and you turn your side towards that force; note that after scaling the circle now turned into an ellipse with its axes oriented along x, y axis; For example, we may expand at x direction (coordinate) by factor 1.5 and squeeze at y direction by 0.9; U - We may want the ellipse to be oriented at angle to x, y axis and the last rotation matrix U does exactly that. It rotates the ellipse to get it a certain desired orientation. For example, its longest axis may be rotated 45 deg. to point in the direction 1, 1 instead of original 1, 0. To sum up SVD represents any matrix multiplication as 3 consecutive operations: remap, squeeze, orient. A nice color illustration of this process can be found here: Analyze1SVD.pdf (it is deep in the directory structure of the unpacked folder). A: The V matrix of the SVD decomposition A = U * S * V', where the ' symbol indicates transposition, encodes the permutation of the axes of A. You can think of it as the coordinate transform that maps the original (x, y, z, ...) coordinate axes to the principal directions of the transformation A.
doc_23532456
$http.get('http://localhost:3000/user').success(function(user) { console.log("user", user); $scope.user = user; $scope.currentUser = user.displayName; $scope.salary = user.salary; }); $scope.openMoneyEdit = function() { $scope.salary = $scope.user.salary; matchId = $scope.user._id; console.log(matchId); }; $scope.editMoney = function(user) { $http.put('/money/' + $scope.user._id, user) .success(function(response) { if (response === 'fail'){ alert('Fail to edit ', 'Make sure year format is correct', 'error'); } else { alert('Success', 'info updated.', 'success'); } }).catch(function(err) { console.log(err); }); };
doc_23532457
'AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 0' Not really sure why. This is my code: table = new JTable(); try { Connection MyConn = null; Statement statement = null; ResultSet rs = null; Class.forName("com.mysql.jdbc.Driver"); MyConn = DriverManager.getConnection("jdbc:mysql:" + "//localhost/eventbooking", "root", "Passw0rd"); statement = MyConn.createStatement(); rs = statement.executeQuery("SELECT * FROM `events` WHERE `Date Of Event` = '30/03/2014'"); int i=0; while (rs.next()) { Object a = rs.getString("Date Of Event"); Object b = rs.getString("Tickets Available"); Object c = rs.getString("Price Of Event"); Object d = rs.getString("Start Time"); table.setRowSorter(null); table.getModel().setValueAt(a, i, 0 ); table.getModel().setValueAt(b, i, 1); table.getModel().setValueAt(c, i, 2); table.getModel().setValueAt(d, i, 3); EventDiary.this.add(table); System.out.println(i); i++; } A: Problem is that you're creating a default JTable, which has a TableModel that consists of a Vector with no elements in it. Then you try to set the element at index 0 of said vector, which doesn't exist at this point and voilà: you face an issue. For example: JTable table = new JTable(); table.getModel().setValueAt("i", 0, 0); System.out.println(table); Results in: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 >= 0 at java.util.Vector.elementAt(Vector.java:470) at javax.swing.table.DefaultTableModel.setValueAt(DefaultTableModel.java:665) at com.stackoverflow.answer.JTableTest.main(JTableTest.java:9) While the following for instance: JTable table = new JTable(1, 1); table.getModel().setValueAt("i", 0, 0); System.out.println(table); Results in: javax.swing.JTable[,0,0,0x0,invalid,alignmentX=0.0,alignmentY=0.0,border=,flags=251658568,maximumSize=,minimumSize=,preferredSize=,autoCreateColumnsFromModel=true,autoResizeMode=AUTO_RESIZE_SUBSEQUENT_COLUMNS,cellSelectionEnabled=false,editingColumn=-1,editingRow=-1,gridColor=javax.swing.plaf.ColorUIResource[r=255,g=255,b=255],preferredViewportSize=java.awt.Dimension[width=450,height=400],rowHeight=16,rowMargin=1,rowSelectionAllowed=true,selectionBackground=com.apple.laf.AquaImageFactory$SystemColorProxy[r=44,g=93,b=205],selectionForeground=com.apple.laf.AquaImageFactory$SystemColorProxy[r=255,g=255,b=255],showHorizontalLines=true,showVerticalLines=true] Thus, if you want to persist with your way of doing things, you'd add in the rows and columns beforehand. Another way to do it would be: JTable table = new JTable(); DefaultTableModel model = (DefaultTableModel) table.getModel(); model.addColumn("id"); model.addColumn("name"); Object[] row = new Object[2]; row[0] = 1; row[1] = "John"; model.addRow(row); row = new Object[2]; row[0] = 2; row[1] = "Jack"; model.addRow(row); for (int i = 0; i < model.getRowCount(); i++) { for (int j = 0; j < model.getColumnCount(); j++) { System.out.println("column: " + model.getColumnName(j) + ", row #" + i + ", value: " + model.getValueAt(i, j)); } } Resulting in: column: id, row #0, value: 1 column: name, row #0, value: John column: id, row #1, value: 2 column: name, row #1, value: Jack
doc_23532458
int usersid; using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["AzureSql"].ToString())) using (SqlCommand command = new SqlCommand()) { connection.Open(); command.CommandText = @"Select UserId from [dbo].[User] where username= @username"; command.Parameters.Clear(); command.Parameters.AddWithValue("@username", currentUser.UserName); usersid = (int)command.ExecuteScalar(); command.CommandText = @"INSERT INTO [dbo].[ClientEmailConfirmation] ([JobNumber],[OrderNumber],[UserId]) VALUES (@JobNumber,@OrderNumber,@UserId)"; command.Parameters.Clear(); command.Parameters.AddWithValue("@JobNumber", JobNumberTextBox.Text); command.Parameters.AddWithValue("@OrderNumber", OrderNumberTextBox.Text); command.Parameters.AddWithValue("@UserId", usersid); command.ExecuteNonQuery(); } I would greatly appreciate of your help Thanks, A A: using (SqlCommand command = new SqlCommand()) { command.Connection = connection; ... A: Preface: I'm answering to combine the two previous answers and to also provide some best practices. Your original code sample was missing the piece that connected (pun-intended) the SqlConnection and the SqlCommand. You need the following snippet of code: using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["AzureSql"].ToString())) using (SqlCommand command = new SqlCommand()) { connection.Open(); command.Connection = connection; // Rest of code here. } I prefer to assign the connection in the constructor of the SqlCommand with an empty command text personally. It always ensures that connection is assigned to the SqlCommand. More reading can be found here on MSDN. using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["AzureSql"].ToString())) using (SqlCommand command = new SqlCommand("", connection)) { // Do note that you still have to open the connection here. connection.Open(); // Rest of code here. } Assuming that your UserId column is an integer type, then casting the result should be fine. usersid = (int)command.ExecuteScalar(); You should be instantiating your own instances of SqlParameter rather than using the AddWithValue() method off the SqlParameterCollection. In the off chance that you have conflicting data types, AddWithValue can infer the wrong type leading to a few difficult to diagnose problems. For further reading, check out this article or MSDN. command.Parameters.Add(new SqlParameter("@username", SqlDbType.VarChar) { Value = currentUser.UserName }); A: Convert the scalar results to Int: int userId = Convert.ToInt32(command.ExecuteScalar()));
doc_23532459
My problem is i have String array it's contain multiple mobile numbers to compare db table if available or not.if available return row values. I am using mysql 5.1.It's not supported for comparing array values in select query. I got error Mysql feature not supported exception.so i will change my code using String builder. I already asked. My question:[Mysql Stored procedure with java String Array So if any possible to compare array values using Store procedure. My select query is : SELECT USER_ID, USER_NAME, REGISTRATION_ID, IMEI_CODE, MOBILE_NUMBER FROM USER WHERE MOBILE_NUMBER IN (String_array); In this query return if `String_array = "one_string_values"; It return single rows.[Using java jdbc queryforObject] If string_array = "array_of_values"` It return nothing i got exception Mysql feature not supported exception Any possibilities available for using Stored procedure in my scenario. A: You basically want to pass multiple values to a Stored Procedure in MySQL. In SQL Server you can pass an XML chunk (as string) down to the SP, and then easily parse that XML extracting the multiple values from it in the SP body. In MySQL, I don't think this is easily possible. The best things you can do: 1) pass a comma-delimited string to the SP and parse that string it inside the SP; 2) generate the SQL dynamically: MySQL stored procedure that accepts string with multiple parameters 3) you can also look at the FIND_IN_SET function; 4) you can also check the XML functions: http://dev.mysql.com/doc/refman/5.1/en/xml-functions.html and ExtractValue in particular.
doc_23532460
transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) This leads to this error message: tensor.sub_(mean[:, None, None]).div_(std[:, None, None]) RuntimeError: The size of tensor a (2) must match the size of tensor b (3) at non-singleton dimension 0 A: As you can see, PyTorch complains about the Tensor size, since you lack a channel. Additionally, the "usual" mean and std values are computed on ImageNet dataset, and are useful if the statistics of your data match the ones of that dataset. As you work with two channels only, I assume that your domain might be fairly different from 3-channels natural images. In that case I would simply use 0.5 for both mean and std, such that the minimum value 0 will be converted to (0 - 0.5) / 0.5 = -1 and the maximum value of 1 to (1 - 0.5) / 0.5 = 1. transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize(mean=[0.5, 0.5], std=[0.5, 0.5]) ]) Edit: I would recommend zero-centering of the input. However, if for some reason you must have it in range [0, 1], calling only ToTensor() would suffice. In this case, a word of caution. I think ToTensor() assumes your input to lie in range [0, 255] prior to the transform, so it basically divides it by 255. If that is not the case in your domain (e.g. your input is always in range [1, 50] for some reason) I would simply create a custom transform to divide for the actual upper bound for your data.
doc_23532461
public String printTriangleType(int a, int b, int c) { if (a == b && b == c)  return equilateral; else if (a == b && b != c && a != c) return isosceles; else if (a == c && b != c && b != a)  return isosceles; else if (b == c && c != b && c != a)  return isosceles; else return scalene; } The program that is checking my code is telling me that it does not recognize the identifiers equilateral, isosceles, and scalene. Why is that? A: String literals in Java are denoted by quotes ("). Without them, Java attempts to interprets them as variable names and fails, as you did not define such variables: public String printTriangleType(int a, int b, int c) { if (a == b && b == c) return "equilateral"; else if (a == b && b != c && a != c) return "isosceles"; else if (a == c && b != c && b != a) return "isosceles"; else if (b == c && c != b && c != a) return "isosceles"; else return "scalene"; }
doc_23532462
from discord.ext import commands Bot = commands.Bot(command_prefix= '!') a=0 @Bot.event async def on_ready(): print('Bot online') @Bot.command() async def msg(ctx): global a a=a+1 await ctx.author.send(a) for i in range(5): msg() Bot.run('token') Unfortunately this doesn't work without manual entering the command in the channel (!msg). Moreover, it doesn't do it in a loop. How to invoke discord function as standard python function? A: You are using an async command without await for _ in range(5): await msg() But... I highly dout it would work at all because of the way you want to use the msg function better solution is a = 0 async def send_message_and_increment(ctx): global a a += 1 await ctx.send(a) # send to text_channel the user was in await ctx.author.send(a) # send to the user (DM) that invoke the command @Bot.command() async def msg(ctx): global a for _ in range(5): await send_message_and_increment(ctx)
doc_23532463
ColA | ColB 1 | 1 1 | 2 1 | 3 2 | 1 2 | 2 2 | 3 3 | 1 3 | 2 3 | 3 Using SQL Server 2008, how would I count an occurrence such that the combination (1,2) would be the same as (2,1) and therefore my results would be as follows: ColA | ColB | Count 1 | 1 | 1 1 | 2 | 2 1 | 3 | 2 2 | 2 | 1 2 | 3 | 2 3 | 3 | 1 Thanks! A: Try this: ;with cte as (select ColA, ColB, case when ColA < ColB then ColA else ColB end as ColC, case when ColA > ColB then ColA else ColB end as ColD from yourtable) select ColC as ColA, ColD as ColB, count(1) as Count from cte group by ColC, ColD order by ColC, ColD A: Before grouping, normalize the data by making Col1 = MIN(Col1, Col2) and Col2 = MAX(Col1, Col2). This converts each possible combination to a canonical one. Then, do the usual grouping. A: An Example has be posted just before mine but i though i would post anyhow. replace YourTable with the table you are going to query the data from and this below solution will work. it joins 2 sets of data together in the WITH clause and then selects the 2 columns and does the count. WITH data as ( select ColA ,ColB from YourTable union all select ColA ,ColB from YourTable where ColB <> ColA and ColA <> ColB ) select ColA ,ColB ,count(*) as [Count] from data GROUP BY ColA,ColB A: How about this: select (case when colA < colB then colA else colB end) as ColA, (case when colA < colB then colB else colA end) as ColB, count(*) from table t group by (case when colA < colB then colA else colB end), (case when colA < colB then colB else colA end); This would look simpler if SQL Server supported greatest() and least() as some other databases do. But the case statement works just as well.
doc_23532464
I'm using PHP and MySQL. Here is the HTML. <form method="post" action="index.php"> <fieldset> <ul> <li><label for="about-me">About Me: </label> <textarea rows="8" cols="60" name="about-me" id="about-me"></textarea></li> <li><label for="my-interests">My Interests: </label> <textarea rows="8" cols="60" name="interests" id="interests"></textarea></li> <li><input type="submit" name="submit" value="Save Changes" class="save-button" /> </ul> </fieldset> </form> A: If you are using the Php it's very easy <?php include_once(“fckeditor/fckeditor.php”) ; $sBasePath = $_SERVER[ 'PHP_SELF' ] ; $oFCKeditor = new FCKeditor('FCKeditor1') ; $oFCKeditor->BasePath = 'fckeditor/' ; $oFCKeditor->ToolbarSet = 'Basic'; $oFCKeditor->Height = 200; $oFCKeditor->Width = 400; $oFCKeditor->Value = '<p>Now the FCKeditor is available and ready to use. So, just insert the following code in your p</p>' ; $oFCKeditor->Create() ; ?> Put this code in your html. For more details go to an article in my blog: Basic FCKEditor Integration A: For example I do next action: First write on section that code <script type="text/javascript" src="ckeditor/ckeditor.js"></script> Second <textarea cols="80" id="FCKeditor1" name="FCKeditor1" rows="10"></textarea> <script type="text/javascript"> CKEDITOR.replace( 'FCKeditor1',{ toolbar : 'Full', skin:'kama' } ); </script> after that action I saw on my browser ckeditor. A: FCKeditor 2.x, Developers Guide, PHP is a good guide on integrated FCKeditor into PHP. You include the file, create an object, assign some parameters and you're good to go. It's pretty easy and useful. I hope this helps. A: CKEdit is just a JavaScript plugin. In order to use it with PHP and MySQL you don't really need to take any specific precautions. You can just follow the guide: FCKeditor 2.x, Developers Guide, JavaScript. Head: <script type="text/javascript" src="fckeditor/fckeditor.js"></script> Body: <script type="text/javascript"> var oFCKeditor = new FCKeditor('FCKeditor1'); oFCKeditor.BasePath = "/fckeditor/"; oFCKeditor.Create(); </script> Where you replace: "FCKeditor1" in the above example with "about-me", and again for your "interests" field.
doc_23532465
if (condition) { //some code here } A: Yes, but it's going to take you a pretty long and boring while... The auto completion is simply a collection of snippets. You can extract the package that contains them (PHP or JavaScript, I don't know) and then edit them, one by one. If you don't know what snippets are, I recommend you have a look at this video about them, you'll love them. (BTW, look every video of this playlist, it's pretty good)
doc_23532466
I want to create a chatbot that can answer the student's questions based on that FAQ. I have created a chatbot using DialogFlow, but I am having one issue. I have created different knowledge connectors for each university's FAQ data. So if I ask one question regarding "A" university, it gives me an answer from "B" university's knowledge base. I want my chatbot to answer queries from a particular university's data. I can initially ask the user from which university he wants data. then, based on that intent, I'll map from which FAQ data chatbot will answer the questions. I don't know if that is possible in Dialogflow or if I have to use any others One more thing let's say I have 10 universities all the questions in all those 10 universities might be same but the answers are different for all based on university. Can you please suggest a good tool to fulfill my use case?
doc_23532467
If I don't know which constructor will be called I am not sure how to declare "numbers"(as an int array or as a float array). Is there a good technique to get around this? or can I create an int array and a float array and somehow have a generic pointer to the array being used(is using a void pointer the best way to do this)? A: Looks like you want a templated class. template <class T> class Foo { public: Foo(T a, T b, T c) { numbers[0] = a; numbers[1] = b; numbers[2] = c; } private: T numbers[3]; }; A: Can't you use templates for that? example: template <class T> class Foo { public Foo(T a, T b, T c); }; // Foo<float> aaa(1.0f, 1.0f, 0.5f); Foo<int> bbb(1, 2, 3); A: Why not to make class Foo { public: Foo(double a, double b, double c) :_a(a), _b(b), _c(c) {} virtual double get_a() {return _a;} virtual double get_b() {return _b;} virtual double get_c() {return _c;} // more methods protected: double _a, _b, _c; }; works well for both ints and floats: Foo ifoo(1, 3, 5); Foo ffoo(2.0, 4.0, 6.0); and for mixing them: Foo mfoo(1, 4.0, 5); douable storage space is more than enouh for both int and float
doc_23532468
I'm trying to set up basic functionality to trigger an animation in TouchDesigner, based off whenever a Gmail account receives a new email. How and where would I make the following code request? ========================= request = { 'labelIds': ['INBOX'], 'topicName': 'projects/myproject/topics/mytopic' } gmail.users().watch(userId='me', body=request).execute() ======================== I've made a separate python file, and it keeps telling me that "name 'labelIDs' is not defined". Am I not importing the correct libraries? Or should there be more defining at the top of the file? I ca't find any examples/tutorials that explain how to best call the watch() function. Any help would be greatly appreciated
doc_23532469
ok, I have a case class called "ListNode", and below is the error I got: scala> case class ListNode[Int](vl: Int, nt: ListNode[Int] = null) { | def value: Int = vl | def next: ListNode[Int] = nt | } defined class ListNode scala> var a = ListNode(1) a: ListNode[Int] = ListNode(1,null) scala> var b = ListNode(2) b: ListNode[Int] = ListNode(2,null) scala> a.next = b <console>:11: error: value next_= is not a member of ListNode[Int] a.next = b ^ I've read this and this and this and this and this, but still not really understand what it means... Why cannot I just set the node next to be another node, just like in Java? Thank you very much. A: I see two problems (there may be more). 1 - Your type parameter should be a parameter not an Int specification. 2 - If you're going to reassign the value of next then it needs to be a var. case class ListNode[T](vl: T, nt: ListNode[T] = null) { val value: T = vl var next: ListNode[T] = nt } scala> val a = ListNode(1) a: ListNode[Int] = ListNode(1,null) scala> val b = ListNode(2) b: ListNode[Int] = ListNode(2,null) scala> a.next = b a.next: ListNode[Int] = ListNode(2,null) Of course, being a case class, it can be greatly simplified. // this is all you need case class ListNode[T](value: T, var next: ListNode[T] = null) A: That's because you're using def, which is a function. You might want to define the case class using vars. The below code will work, but you might want to reconsider the whole idea of mutable case classes. case class ListNode[Int](v1:Int, nt:ListNode[Int]=null) { var _nt = nt def value: Int = v1 def next: ListNode[Int] = _nt def next_=( newNext:ListNode[Int] ) = { _nt = newNext } } scala> val a = ListNode(1,null) a: ListNode[Int] = ListNode(1,null) scala> a.next = ListNode(2,null) a.next: ListNode[Int] = ListNode(2,null) Note that mutating case classes is ideally done via copy: scala> a.copy( v1=500 ) res0: ListNode[Int] = ListNode(500,null) Additionally, if something may be null you can consider wrapping it in an Option... but I assume this is a "kick-the-tires" code, not a production one :-). A: Case classes in Scala are immutable, which means you can't change their values. In this case, even if you weren't using a case class, next is a function (it is defined with def) so it does not make sense to attempt to assign a value to it. As an additional point, it is not good practice to use null in Scala. Better to use the Option class. There are several ways to you could alter your code to solve your problem. If you want to use mutable classes, consider the following: class ListNode[Int](value: Int, nt: Option[ListNode[Int]] = None) { var next = nt } object ListNode { def apply(value: Int, nt: Option[ListNode[Int]] = None) = new ListNode[Int](value, nt) } var a = ListNode(1) var b = ListNode(2) a.next = Some(b)
doc_23532470
<?php include("config.php"); $sql = "SELECT * FROM ".$USERS; $sql_result = mysqli_query($connection, $sql); if ($sql_result) { while ($result = mysql_fetch_assoc($sql_result)) { echo $result; } } else { die ('Could not execute SQL query '.$sql); } ?> but got this warning: Warning: mysql_fetch_assoc() expects parameter 1 to be resource, object given in C:\xampp\htdocs\newSDP\phpscript\users.php on line 6 How can I fix it? A: Change: mysql_fetch_assoc to mysqli_fetch_assoc
doc_23532471
(VK_RWIN or VK_LWIN + arrow) in a single application. To do this, I've decided to compelately block VK_RWIN and VK_LWIN virtual buttons in this app. I've used SetWindowsHookEx with LowLevelKeyboardProc callback. I'm checking if my application is activated via WM_ACTIVATEAPP message. Inside the callback, if the application is active, I'm checking virtual keys and return 1, when VK_RWIN or VK_LWIN is pressed. Works perfect, just as expected. Now, I just wonder if antiviruses may detect such usage as malware? A: Yes, definitely. A lot of AV software (maybe most) will flag your application as malware simply because it contains a call to SetWindowsHookEx. For example, I have some code that creates keyboard hooks and I have to exclude that directory from the AV scanner because otherwise it quarantines my app as soon as I build it. That has been true of all three AV products I've used in recent years. And since every AV product has its own way of whitelisting applications, it will be very difficult for you to figure out in advance what users will have to do to use your application. A: Digitally sign your application so that AV software doesn't get triggered on it.
doc_23532472
Please find below code: { process = new Process(); process.StartInfo.FileName = @"xyz.exe"; process.StartInfo.Arguments = "-parentHWND " + hWnd.ToInt32() + " " + Environment.CommandLine; process.StartInfo.UseShellExecute = true; process.StartInfo.CreateNoWindow = true; process.Start(); process.WaitForInputIdle(); }
doc_23532473
let’s have a look at what happens when we don’t have a hash function, and we try to use Person objects as keys in a dictionary: NSMutableDictionary* dictionary = [NSMutableDictionary dictionary]; NSDate* start = [NSDate date]; for (int i = 0; i < 50000; i++) { NSString* name = randomString(); Person* p = [[Person alloc] initWithName:name birthDate:[NSDate date] numberOfKids:i++]; [dictionary setObject:@"value" forKey:p]; } NSLog(@"%f", [[NSDate date] timeIntervalSinceDate:start]); This takes 29 seconds on my machine. In comparison, when we implement a basic hash function, the same code runs in 0.4 seconds. These are not proper benchmarks, but do give a very good indication of why it’s important to implement a proper hash function. I know it is wrong if we do not provide hash function for the custom object. But why it has so big performance problem? As I know, if we do not implement hash function, custom object will use pointer as its hash. pointer is unique, so it is perfect hash if only consider performance issue. Then I tried similar code on NSMutableSet instead of NSMutableDictionary and get opposite result. Use default hash function will run faster, why?
doc_23532474
A: ;WITH cte1 AS ( SELECT ROW_NUMBER() OVER(ORDER BY SALARY DESC) AS RN, * FROM Salaries ) SELECT * FROM cte1 WHERE RN = 5 <-- Nth highest A: Check out the row_number function. :) http://msdn.microsoft.com/en-us/library/ms186734.aspx
doc_23532475
* *git clone git@gitlab.com:my-project/test.git *git checkout -b superBranch *git push --set-upstream origin superBranch After these executions, I can change and push the files of the branch without merge request. jGit: Unfortunately jgit does not know the command "push -u" (Upstream). So I found some maybe solution. But all solutions does not work really. First in StackOverflow: // git clone done, than: git.branchCreate() .setName("superBranch") .setForce(true) .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK) .setStartPoint("origin/superBranch").call(); // <-- Ref not found RefSpec refSpec = new RefSpec().setSourceDestination("superBranch", "superBranch"); git.push() .setRefSpecs(refSpec) .setCredentialsProvider(provider).call(); git.checkout().setName("superBranch").call(); Exception: org.eclipse.jgit.api.errors.RefNotFoundException: Ref origin/superBranch cannot be resolved Another solution I found here Eclipse Forum: git.branchCreate().setName("superBranch").call(); git.push() .setRemote("origin") .setRefSpecs(new RefSpec("superBranch" + ":" + "superBranch")) //<-- Ref not found .setCredentialsProvider(provider).call(); git.branchCreate() .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.SET_UPSTREAM) .setStartPoint("origin/" + "superBranch") .setForce(true).call(); git.checkout().setName("superBranch").call(); Exception: org.eclipse.jgit.api.errors.InvalidRefNameException: Branch name <null> is not allowed Does anyone know how can I create a remote and local branch, without call an api or make a merge request like my git example on the top? A: Following code works for me: Git git = Git.cloneRepository() .setURI("https://gitlab.com/my-project/test.git") .setDirectory(new File("scratch/test")) .setCloneAllBranches(true) .setCredentialsProvider(provider).call(); git.checkout() .setCreateBranch(true) .setName(BRANCH).call(); git.push() .setRemote("origin") .setRefSpecs(new RefSpec(BRANCH + ":" + BRANCH)) .setCredentialsProvider(provider).call(); So I clone the repository, checkout the branch or create the branch if not exits, then I push the new branch to the remote repository. A: Finally, I tried this, that works for me. git.branchCreate().setName(localBranchName).call(); git.push().setRemote("origin") .setCredentialsProvider(createCredential(name, password)) .setRefSpecs(new RefSpec(localBranchName + ":" + localBranchName)).call(); //delete is necessary git.branchDelete().setBranchNames(localBranchName).call(); git.checkout().setCreateBranch(true).setName(localBranchName) .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK) .setStartPoint("origin/" + localBranchName) .call();
doc_23532476
int brk(void * end_data_segment ); The brk() system call sets the program break to the location specified by end_data_segment. Since virtual memory is allocated in units of pages, end_data_segment is effectively rounded up to the next page boundary. So for this demo: #include <stdio.h> #include <unistd.h> int main(int argc, char *argv[]) { long int page_size = sysconf(_SC_PAGESIZE); printf("My page size: %ld\n", page_size); void* c1 = sbrk(0); printf("program break address: %p\n", c1); printf("sizeof char: %lu\n", sizeof(char)); c1 = (void*) ((char*) c1 + 1); printf("c1: %p\n", c1); brk(c1); void* c2 = sbrk(0); printf("program break address: %p\n", c2); } output: My page size: 4096 program break address: 0x55b0bc104000 sizeof char: 1 c1: 0x55b0bc104001 program break address: 0x55b0bc104001 I expect the new program break address to be: 0x55b0bc104000 + 0x1000(4096 in HEX) == 0x55b0bc105000 Why didn't I get 0x55b0bc105000 but 0x55b0bc104001 instead? A: Think of it as 2 possibilities: * *align the end_data_segment to a page boundary; and ensure that the size of the underlying area of the virtual address space exactly matches the end_data_segment value *don't align the end_data_segment to a page boundary; and ensure that the size of the underlying area of the virtual address space is aligned (rounded up) to the page size For the first possibility, portable software (that has no idea what the page size will be) could (e.g.) increase the end_data_segment by 1/8th of a page and do that 8 separate times, and instead of ending up with one extra page (the result you'd naturally expect) it would end up with 8 extra pages (7 pages more than it wanted and 7 pages more than it expected). Worse; software could reduce the size of end_data_segment by less than a page and it would do nothing (would be rounded back up to what the original value); and this can also be done many times leading to a large area that software tried to get rid of but still exists. Of course these can be combined - software could increase end_data_segment by 1 byte and then reduce end_data_segment by one byte in the middle of a loop, causing an unexpected memory (space) leak that might quickly gobble up all available virtual address space when people expected it to waste nothing. Of course software could explicitly work around all the problems by adding (non-standard/unportable) fix-ups everywhere, but that would be horribly ugly. The second possibility (don't align the end_data_segment) is more intuitive, more convenient, and less error prone.
doc_23532477
As I read about the HtmlUnitDriver I found out that it is using the Rhino (https://developer.mozilla.org/en-US/docs/Rhino) JavaScript interpreter. It seems like it works in the interpreter rather than compile mode, causing this type of problems. Is it a way to tell HtmlUnitDriver to work with Rhino in compiled JavaScript mode? I would still like to use HtmlUnitDriver rather than GUI version like Firefox. Could it be done using some system properties, config files etc?
doc_23532478
When my sportsPaperRank is this format xxx-xx-xxxx and weight starts with 80,and search.sportsSwim === "hi" || search.sportsSwim === "hello", I need to ignore that value, but right now its ignoring both the items, but I need to display first item, because the value of weight starts with 55. Can you tell me how to fix it? Right now I did a regular expression check and match check, but nothing working. Can you tell me how to fix it? let data = [ { "weight": 555666111, "sportsBall": "wewewe", "sportsSwim": "hi", "sportsPaperRank": "xxx-xx-0000", "sportsHeight": "wew", "sportsRing": "yuyu", "sportsBat": "yuyu-ioioioio", "playing": "erioioerio" }, { "weight": 80035647, "sportsBall": "klklkl", "sportsSwim": "hello", "sportsPaperRank": "xxx-xx-0000", "sportsRing": "yuyu", "sportsBat": "yuyu-ioioioio", "playing": "erioioerio" }, { "weight": 80035649, "sportsBall": "klklkl", "sportsSwim": "hello", "sportsPaperRank": "22-2340000", "sportsRing": "yuyu", "sportsBat": "yuyu-ioioioio", "playing": "erioioerio" } ]; console.log( 'data.--->', data ); console.log( 'data[0]--->', data[0].sportsPaperRank ); let patternEIN = /^\d{2}\-?\d{7}$/; //let patternEIN = /^\d{3}-\d{2}-\d{4}$/; // let patternEIN = (/^\d{3}-?\d{2}-?\d{4}$/ | /^XXX-XX-XXXX$/); console.log('no dashpattern check--->', ('xxxxx0000' === patternEIN)); console.log('pattern check hard --->', ('xxx-xx-0000' === patternEIN)); console.log('pattern check s--->', (data[0].sportsPaperRank === patternEIN)); console.log('pattern check .toString()--->', (data[0].sportsPaperRank.toString() === patternEIN)); let resultSports = data.filter( search => { console.log("pattern matching ", search.sportsPaperRank.match(patternEIN)); (search.weight) && (search.weight.toString().startsWith('80')) && (search.sportsSwim === "hi" || search.sportsSwim === "hello") && (search.sportsPaperRank.match(/xxx/g)) } ); console.log(' resultSports--->', resultSports); A: You can do this with three regular expressions. To check that a string starts with 80: /^80/ * *^ asserts that the match is at the beginning of the string *80 matches the character literal string 80 exactly /^80/.test(8012381); // true /^80/.test(8800000); // false https://regex101.com/r/TvbQ3D/1 To check that a string has the format XXX-XX-XXXX where X is a numeric digit: /^\d{3}-\d{2}-\d{4}$/ * *^ asserts that the match is at the beginning of the string *\d{3} matches 2 numeric digits in a row *- matches the - character literal *\d{2} matches 3 numeric digits in a row *- matches the - character literal *\d{4} matches 4 numeric digits in a row *$ asserts that the match is at the end of the string /^\d{3}-\d{2}-\d{4}$/.test("123-45-6789"); // true /^\d{3}-\d{2}-\d{4}$/.test("00-000-000"); // false /^\d{3}-\d{2}-\d{4}$/.test("A00-00-0000"); // false Note: if you don't want to limit the X in this format to numeric digits, you could swap it out \d with \w which will match "word" characters (0-9, a-z, A-Z, and _): /^\w{3}-\w{2}-\w{4}$/ https://regex101.com/r/gGBc4z/4 To match that a string is exactly hi or hello: /^hi|hello$/ * *^ asserts that the match is at the beginning of the string *hi matches the character literal string hi exactly *| is an 'or' operator that will let you list multiple valid matches *hello matches the character literal string 'hello' exactly *$ asserts that the match is at the end of the string https://regex101.com/r/jhLMzi/1 /^hi|hello$/.test("hi"); // true /^hi|hello$/.test("hello"); // true /^hi|hello$/.test("something else); // false Note: the ^ and $ help ensure that you are matching a string of the exact length and format that you're specifying. Now, simply use those regular expressions to exclude any object with a "weight" field starting with 80, and a "sportsPaperRank" field matching XXX-XX-XXXX, and a "sportsSwim" field matching either "hi" or "hello": let resultSports = data.filter(ea => !( /^80/.test(ea.weight) && /^\d{3}-\d{2}-\d{4}$/.test(ea.sportsPaperRank) && /^hi|hello$/.test(ea.sportsSwim) )); A: You can get your result by using regex in if() condition. Here is your code snippet: var data1 = [ { "weight": 555666111, "sportsBall": "wewewe", "sportsSwim": "hi", "sportsPaperRank": "xxx-xx-0000", "sportsHeight": "wew", "sportsRing": "yuyu", "sportsBat": "yuyu-ioioioio", "playing": "erioioerio" }, { "weight": 80035647, "sportsBall": "klklkl", "sportsSwim": "hello", "sportsPaperRank": "xxx-xx-0000", "sportsRing": "yuyu", "sportsBat": "yuyu-ioioioio", "playing": "erioioerio" } ]; var resultSports = data1.filter(function(search){ if((!search.sportsPaperRank.match(/\w{4}-\w{2}-[0-9]{4}/gm)) && (!search.weight.toString().match(/^80/gm)) && ((search.sportsSwim === "hi") || (search.sportsSwim === "hello"))){ return search; } }); console.log(resultSports); Here, you will get the single object having weight:555666111 and "sportsPaperRank": "xxx-xx-0000". You can check my regex for sportsPaperRank:xxxx-xx-0000 in this link. You can check my regex for "weight": 555666111 in this link.
doc_23532479
These coordinates are stored in a MongoDB database, and when the user wants to display the map, my server (running under Node.js) computes a GeoJSON file with these coordinates and sends it to the client. The problem I have is that this file can be very big (~20 Mo) because these shapes are very detailed so there are a lot of coordinates, even for one state. Even when gzipped the file remains big (~3-5 Mo). I can't send such a big file, for bandwidth and Javascript memory considerations. So I'm looking for a scenario that would allow me to send all these coordinates with a reasonable bandwidth and browser memory usage. Any suggestions? Thanks
doc_23532480
class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 32, 3, 1) self.conv2 = nn.Conv2d(32, 64, 3, 1) self.fc1 = nn.Linear(9216, 128) self.fc2 = nn.Linear(128, 10) def forward(self, x): x = self.conv1(x) x = F.relu(x) x = self.conv2(x) x = F.relu(x) x = F.max_pool2d(x, 2) x = torch.flatten(x, 1) x = self.fc1(x) x = F.relu(x) x = self.fc2(x) output = F.log_softmax(x, dim=1) return output When feeding complex data to the model, output = model(data.complex()) it gives ret = torch.addmm(bias, input, weight.t()) RuntimeError: expected scalar type Float but found ComplexDouble (I didn't copy the entire stack trace, nor the entire training code, for question simplicity) doing self.complex() after the model's __init__, as I normally would do self.double(), doesn't work, with torch.nn.modules.module.ModuleAttributeError: 'Net' object has no attribute 'complex' * *How to allow model's weights to be complex? *How to allow complex input to a model? *Which built-in activation functions support this? *Is anything also supported for 1d operations? EDIT: In the meantime, I found this paper. Still reading it. A: As you normally did self.double(), I found self.type(dst_type) from https://pytorch.org/docs/stable/generated/torch.nn.Module.html In my case, self.type(torch.complex64) is working for me.
doc_23532481
every time I 'python manage.py migrate myapp ' , errors happened , it said that the table is already exists... Any help ? please... A: Maybe use python 'manage.py migrate myapp --fake' for all the migrations before the last one
doc_23532482
I have tried to use System Variable and the Java Ops variable with no success. what i have code wise: Application.properties: testing=${foo.bar} Application.java @SpringBootApplication @ComponentScan public class Application extends RepositoryRestMvcConfiguration { @Value("${testing:}") private String input; public static void main(final String args[]) { SpringApplication.run(Application.class, args); } @Bean public BatchDetails set() { System.out.println("input: " + input); return new BatchDetails("Test", "Test2"); } } IntelliJ VM Options: -Dspring.application.json='{"foo":{"bar":"spam"}}' IntelliJ Environment variables: SPRING_APPLICATION_JSON = '{"foo":{"bar":"spam"}}' on startup of the application i get the following stack trace: Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'foo.bar' in string value "${foo.bar}" at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:174) ~[spring-core-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:126) ~[spring-core-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:204) ~[spring-core-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:178) ~[spring-core-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.core.env.AbstractPropertyResolver.resolveNestedPlaceholders(AbstractPropertyResolver.java:195) ~[spring-core-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.core.env.PropertySourcesPropertyResolver.getProperty(PropertySourcesPropertyResolver.java:87) ~[spring-core-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.core.env.PropertySourcesPropertyResolver.getProperty(PropertySourcesPropertyResolver.java:60) ~[spring-core-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.core.env.AbstractEnvironment.getProperty(AbstractEnvironment.java:531) ~[spring-core-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.context.support.PropertySourcesPlaceholderConfigurer$1.getProperty(PropertySourcesPlaceholderConfigurer.java:132) ~[spring-context-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.context.support.PropertySourcesPlaceholderConfigurer$1.getProperty(PropertySourcesPlaceholderConfigurer.java:129) ~[spring-context-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.core.env.PropertySourcesPropertyResolver.getProperty(PropertySourcesPropertyResolver.java:84) ~[spring-core-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.core.env.PropertySourcesPropertyResolver.getPropertyAsRawString(PropertySourcesPropertyResolver.java:70) ~[spring-core-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.core.env.AbstractPropertyResolver$1.resolvePlaceholder(AbstractPropertyResolver.java:207) ~[spring-core-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:153) ~[spring-core-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:126) ~[spring-core-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:204) ~[spring-core-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:178) ~[spring-core-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.context.support.PropertySourcesPlaceholderConfigurer$2.resolveStringValue(PropertySourcesPlaceholderConfigurer.java:172) ~[spring-context-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.resolveEmbeddedValue(AbstractBeanFactory.java:808) ~[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1027) ~[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014) ~[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:545) ~[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE] ... 80 common frames omitted am i just putting the configuration in the wrong place for this to work? A: You cannot "expand" Spring's application.properties like that. Both all the values from there and the System-level spring.application.json are loaded into your Environment variable and you can access foo.bar from there. So, basically.. Spring takes testing from your application.properties expecting a fully-formed value, then it takes the JSON from your System variable, expecting a fully-formed value and merges them into Environment. Now you can do @Autowired private Environment env; env.getProperty("testing"); env.getProperty("foo.bar"); //OR @Value(${"foo.bar"}) private String valueFromFooBar A: I try to add -Dspring.application.json='{"foo":{"bar":"spam"}}' to my test,but it doesn't parse correctly. you can try --spring.application.json={\"foo\":\"bar\"} instead,it works well; actually,when spring is running, it parser the configure options into the enviroment,just like the picture .firstly ,parser the commandarguements into PropertySource name='commandLineArgs',then,after parsered by SpringApplicationJsonEnvironmentPostProcessor,split the value in spring.application.jsoninto a lonely PropertySource name spring.application.json. parsered bySpringApplicationJsonEnvironmentPostProcessor
doc_23532483
package wscalalearning00 import org.apache.spark._ import org.apache.spark.SparkContext._ import org.apache.log4j._ import org.apache.spark.util.StatCounter object wtry001 { def main(args: Array[String]) { Logger.getLogger("org").setLevel(Level.ERROR) class BballStatCounter extends Serializable { val stats: StatCounter = new StatCounter() var missing: Long = 0 def add(x: Double): BballStatCounter = { if (x.isNaN) { missing += 1 } else { stats.merge(x) } this } } object BballStatCounter extends Serializable { def apply(x: Double) = new BballStatCounter().add(x) } // Create a SparkContext using every core of the local machine val sc = new SparkContext(new SparkConf().setAppName("Spark Word Count").setMaster("local")) val testData = (1 to 10000).toArray.map(x=>x.toDouble) val stats1 = sc.parallelize(testData) val stat3 = stats1.map(b=>BballStatCounter(b)) stat3.foreach(println) } } Python version: import math import findspark findspark.init() from pyspark.sql import SparkSession from pyspark.statcounter import StatCounter class BballStatCounter(object): stats = StatCounter() missing=0 @staticmethod def add(x): print("add") if math.isnan(x): BballStatCounter.missing += x else: BballStatCounter.stats.merge(x) return BballStatCounter.stats conf = SparkConf().setAppName("SparkExampleRDD").setMaster("local") sc = SparkContext(conf=conf) testData =map(lambda x: float(x),range(0,10000)) stats1 = sc.parallelize(testData) print(stats1) stat3 = stats1.map(lambda b: BballStatCounter.add(b)) stat3.foreach(print) On executing the above Python code, it prints (count: 22, mean: 10.5, stdev: 6.34428877022, max: 21.0, min: 0.0) where as the Scala code prints something like this BballStatCounter$2@7a811dd5.I think that Scala code is returning instances of same class. Please let me know if my general approach and/or syntax are wrong. Thanks. A: try this class BballStatCounter: def __init__(self): self.stats = StatCounter() self.missing = 0 @staticmethod def add(x): stats = StatCounter() missing = 0 if math.isnan(x): BballStatCounter.missing += x else: BballStatCounter.stats.merge(x,stats,missing) def merge(other,stats,missing): # stats = BballStatCounter.StatCounter() #other = BballStatCounter() BballStatCounter.stats.merge(other.stats) BballStatCounter.missing = +other.missing return self then do stat3 = stats1.map(lambda b: BballStatCounter.add(b)) stat3.foreach(print) I may not give you the right code because I have very little understanding of what the functions are doing. just focus on how I am passing variables between functions.-- hope u find your answer.
doc_23532484
A: Method 1: Do it in Objective-C NSString *str = [NSString stringWithContentsOfURL:wkwebview.URL usedEncoding: NSUTF8StringEncoding error:nil]; NSRange range = [str rangeOfString:@"string to find"]; if (range.location != NSNotFound) { //found } Method 2: Do it in JQuery NSString *js = @"var htmlString = $('body').html().toString(); var index = htmlString.indexOf('string to find'); if (index != -1) {alert('found')}"; [wkWebView evaluateJavaScript:js completionHandler:nil];
doc_23532485
Persons Table: |ID |FirstName|LastName|PersianBirthDate| |1 |FName1 |LName1 |"1362/01/01" | |2 |FName2 |LName2 |"1359/05/01" | |3 |FName3 |LName3 |"1350/04/11" | |4 |FName4 |LName4 |"1355/02/10" | |5 |FName5 |LName1 |"1365/12/25" | When i want to get rows that their PersianDateBirthDate are less than "1362/01/01" like as below: |ID |FirstName|LastName|PersianBirthDate| |2 |FName2 |LName2 |"1359/05/01" | |3 |FName3 |LName3 |"1350/04/11" | |4 |FName4 |LName4 |"1355/02/10" | I use following code in EntityFramework (code-first): using (var db = new MyContext()) { return (db.Persons .Where(x=> PersianDateTime.Parse(x.PersianBirthDate).ToDateTime() < PersianDateTime.Parse("1362/01/01").ToDateTime()) .ToList(); } But the following exception occurs: LINQ to Entities does not recognize the method 'System.DateTime ToDateTime()' method, and this method cannot be translated into a store expression. I can't use db.persons.AsEnumerable(). Note: The datatype of PersianBirthDate is char(10) and PersianDateTime library convert Persian Date to Gregorian Date. A: According to @KristoferA comment, we can use code below: db.Persons .Where(x => x.PersianBirthDate.CompareTo("1362/01/01") < 0).ToList(); And then the following SQL is sent to DB: SELECT [Extent1].[ID] AS [ID], [Extent1].[FirstName] AS [FirstName], [Extent1].[LastName] AS [LastName], [Extent1].[PersianBirthDate] AS [PersianBirthDate] FROM [dbo].[Persons] AS [Extent1] WHERE [Extent1].[PersianBirthDate] < N'1362/01/01' But I think, We can improve this solution. A: This should work: p.Where(x => ((int)x.PersianBirthDate.Substring(0,4)) < year) || (((int)x.PersianBirthDate.Substring(0,4)) = year) && ((int)x.PersianBirthDate.Substring(5,2) < month)) || (((int)x.PersianBirthDate.Substring(0,4)) = year) && ((int)x.PersianBirthDate.Substring(5,2) = month) && ((int)x.PersianBirthDate.Substring(8,2) <= day)
doc_23532486
switch Cell { case "first": variable = "1" default: variable = "0" } Til here everything works fine, even the switch statement works, but it is not based on the content of the Cell. The switch itself is working because on my SecondViewController I always get "0" to see. So what arguments do I have to put behind Cell in the switch statement, to get the content of Cell involved? A: Implement the UITableViewDelegate function tableView:didSelectRowAtIndexPath:. This will be called when you select a cell, and the index of the cell will be found in indexPath.row. From there you can alter behavior based on which cell was selected.
doc_23532487
i need a way to display items in my website like this normally it is like this www.site.com/category/sub-category/article-title but i need it like this www.site.com/article-title normally the shop is like this www.site.com/shops/shop-name but i would need it like this www.site.com/shop-name OR shop-name.site.com an excerpt of my current route rule $route['category/(:any)'] = 'ads/cat/$1'; $route['category/(:any)/(:any)'] = 'ads/cat/$1/$2'; $route['shops/(:any)'] = 'shops/$1'; $route['shops/(:any)/(:any)'] = 'shops/$1/$2'; $route['(:any)/(:any)'] = 'site/$1/$2'; $route['(:any)'] = 'site/$1'; A: Take a look at URI routing. The drawback is that you'll have to add each route by hand. $route['article-title'] = 'category/sub-category/article-title' $route['article/(:any)'] = 'article/$1' You could also try remapping inside the controller with _remap(). This article explains things pretty thoroughly.
doc_23532488
Here is the controller: function PriceAnalyticsCtrl($scope, $filter, products, productService) { var vm = $scope; vm.title = "Price Analytics"; // Computed property for (var i = 0; i < products.length; i++) { products[i].marginPercent = function () { return productService.calculateMarginPercent(products[i].price, products[i].cost); }; products[i].marginAmount = function () { return productService.calculateMarginAmount(products[i].price, products[i].cost); }; }; var orderedProducts = $filter('orderBy')(products, 'marginPercent'); } I am first adding two computed properties. I am then ordering by one of them. Is there a way to order by a calculated property? Thanks! A: The filter parameter requires an angular expression. So currently it's looking for a property, and in this case, it is returning a function instead of the evaluation of the function. Try: var orderedProducts = $filter('orderBy')(products, 'marginPercent()');
doc_23532489
Now I understand in hibernate you need to set the parent object within the child like so. class Parent { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL) private List<Child> childs; //getters / setters } class Child { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; @ManyToOne(cascade = CascadeType.ALL) @JoinColumn(name="parent_id") private Parent parent; //getters / setters } method() { Child child = new Child(); child.setName("fred"); Parent parent = new Parent(); parent.setName("teddy"); child.setParent(parent); Set<Child> childs = new ArrayList<>(); childs.add(child); parent.setChilds(childs); session.save(parent) } However; what I'm looking for is to have ModelMapper handle setting the parent property automatically within the child class rather than manually having to set parent field. I have the following DTO. class ParentDTO { private Long id; private List<ChildDTO> childs; //getters / setters } class ChildDTO { private Long id; private String name; private ParentDTO parent; //getters / setters } using ModelMapper like so public ParentDTO post(@RequestBody ParentDTO parentDTO) { ModelMapper modelMapper = new ModelMapper(); Parent parent = modelMapper.map(parentDTO, Parent.class); parentRepository.save(parent) ..... } I'd also like to add I'm using SpringBoot and I'm populating my DTO object with JSON RequestBody like so { "name" : "teddy", "child": [ { "name": "fred", } ] } Results from save { "id" : 1 "name" : "teddy", "child": [ { "parent" null "name": "fred", } ] } Is there a simple way to set the parent value within the child object using ModelMapper?
doc_23532490
https://www.allmusic.com/search/songs/"hola" So I do results = requests.get(r'https://www.allmusic.com/search/songs/"hola"') followed by soup = BeautifulSoup(results.text, 'html.parser'). One can see that search results are listed with the class song, nevertheless when I use soup.find_all("li", class_="song") and empty list is returned. Any help? A: You need to pass a valid user agent to the request header to get back the page source successfully. Code:- import requests from bs4 import BeautifulSoup headers = {'User-Agent': 'Mozilla/5.0'} results = requests.get(r'https://www.allmusic.com/search/songs/"hola"',headers=headers) soup = BeautifulSoup(results.text, 'html.parser') names = soup.find_all("li", class_="song")
doc_23532491
In the first impression, we were following this to ensure that those classes were Parcelize or not. Therefore, those classes were parceled correctly and everything seems right. A: After many searches and investigations into our codes, I found that SafeArgs class exists in a sealed-class file. Considering to this point that we can't allocate the parceled annotation to the sealed classes, we've decided to move our class outside of that sealed .kt file. Although, I found the main reason for that runtime crash was this cause. Also, I've provided the wrong and correct cases below, We hope this will be helpful to others: We've moved the UserFavorite and its subclass, outside of the Response.kt file, sealed class Response { . . @Parcelize data class UserFavorite( @SerializedName("title") val title: String, @SerializedName("itemType") val itemType: String, @SerializedName("emptyIcon") val emptyIcon: String, @SerializedName("_texts") val texts: UserFavoriteTexts ) : Response(), Parcelable @Parcelize data class UserFavoriteTexts( @SerializedName("hintMessage") val hintMessage: String, @SerializedName("add") val add: String, @SerializedName("remove") val remove: String, @SerializedName("edit") val edit: String ): Parcelable . . } into an independent file for that: UserFavorite.kt @Parcelize data class UserFavorite( @SerializedName("title") val title: String, @SerializedName("itemType") val itemType: String, @SerializedName("emptyIcon") val emptyIcon: String, @SerializedName("_texts") val texts: UserFavoriteTexts ) : Response(), Parcelable @Parcelize data class UserFavoriteTexts( @SerializedName("hintMessage") val hintMessage: String, @SerializedName("add") val add: String, @SerializedName("remove") val remove: String, @SerializedName("edit") val edit: String ): Parcelable and, Respons.kt sealed class Response { . . . . }
doc_23532492
I have been using the Switch device as it most closely resembles my actual device (a garage door). But which trait should I be using that would let me trigger with something like "Hey google, open the garage door"? A: You can use the OpenClose trait to do these types of actions as of March 2019. Answer before March 2019 There's currently no trait for "Open" and "Close". Right now the best bet is to use the OnOff trait. You can use Shortcuts so that something like "open my door" maps to "turn on the door".
doc_23532493
So a user table has x, y, z columns that have a value of 1 (if interested) and 0 (if not interested) Once we get the user we need to get all the projects that have the atleast one of x, y, z value similar. So given: prj title | x | y | z | __________________________________________ prj1 | 1 | 0 | 1 | prj2 | 1 | 1 | 0 | prj3 | 0 | 0 | 1 | and the user table: user id | x | y | z | __________________________________________ user1 | 1 | 0 | 0 | user2 | 1 | 1 | 0 | user3 | 0 | 0 | 1 | Need to find a query that will give me a list of projects that a given user (user1) is interested in. Result should be (if user 1 is selected): prj1 and prj2 Result should be (if user 3 is selected): prj1 and prj3 any ideas on how this can be achieved? I am not sure where to start from. I am not sure if this can be done in just one simple query? A: There's one solution with just one query select p.title from prj as p left join user as u on ( ( (u.x = p.x) && (u.x=1) ) || ( (u.y = p.y) && (u.y=1.... and so on, well I hope you got the idea. A: Try this: SELECT p.prj_title FROM prj AS p JOIN users AS s ON ( (u.x=p.x AND u.x=1) OR (u.y=p.y AND u.y=1) OR (u.z=p.z AND u.z=1) ) WHERE u.user_id='user1';
doc_23532494
All I want to know is what is the best approach. The best way to do this. I have found several info but always using a form in the client side. I cannot use that. A: You can do it also without form. What about encoding it in base64? Look to this solution, by far the best I guess. A: The best way to do this is to simply PUT the file to the target URI. If you need to upload larger files, you might want to split it in parts and join them later, when finished.
doc_23532495
I find a way to launch from Maya substance painter with python command. My problem is that Maya stays freeze until I leave substance painter. I would like to use Maya while substance painter is open. the code: subprocess.call(['C:/Program Files/Allegorithmic/Substance Painter/substance painter.exe' ,'--mesh' , 'c:/temp/exported.fbx']) Thank in advance for your help.^^ A: subprocess.call() waits for the completion of the subprocess. You should try subprocess.Popen().
doc_23532496
Here 2 Searchcontainer with different list to display. I need to change page in first Searchcontainer and dont change page in second.(vice versa) <aui:form action="<%= renderURL.toString()%>" method="post" name="fm" showEmptyOption="<%= true%>"> <div> <% List list = ServiceOrderSearchUtil.simpleSearch(themeDisplay, keywords, serviceOrdersForUserExt); int count = ServiceOrderSearchUtil.searchCount(); %> <liferay-ui:panel-container extended="true" accordion="true" id="lfrpc1"> <liferay-ui:panel title='<%= LanguageUtil.get(pageContext, "MaisOrders") + " (" + count + ")"%>' collapsible="true" defaultState="open" id="lfrp1" > <liferay-ui:search-container iteratorURL="<%= iterURL%>" emptyResultsMessage="no-service-orders-were-found" delta="<%= delta%>"> <liferay-ui:search-container-results> <% results = list; total = count; results = ListUtil.subList(results, searchContainer.getStart(), searchContainer.getEnd()); pageContext.setAttribute("results", results); pageContext.setAttribute("total", total); %> </liferay-ui:search-container-results> <%@ include file="/jsp/dizo-chief-panel/serviceorder_columns.jspf"%> <liferay-ui:search-iterator searchContainer="<%= searchContainer%>" paginate="true" /> </liferay-ui:search-container> </liferay-ui:panel> </liferay-ui:panel-container> </div> <div> <% list = ServiceOrderSearchUtil.simpleSearchMV(themeDisplay, keywords, serviceOrdersExt); count = ServiceOrderSearchUtil.searchCount(); %> <liferay-ui:panel-container extended="true" accordion="true" id="lfrpc2"> <liferay-ui:panel title='<%= LanguageUtil.get(pageContext, "MVRequests") + " (" + count + ")"%>' collapsible="true" defaultState="close" id="lfrp2" > <liferay-ui:search-container iteratorURL="<%= iterURL%>" emptyResultsMessage="no-service-orders-were-found" delta="<%= delta%>"> <liferay-ui:search-container-results> <% results = list; total = count; results = ListUtil.subList(results, searchContainer.getStart(), searchContainer.getEnd()); pageContext.setAttribute("results", results); pageContext.setAttribute("total", total); %> </liferay-ui:search-container-results> <%@ include file="serviceorder_columns.jspf"%> <liferay-ui:search-iterator searchContainer="<%= searchContainer%>" paginate="false" /> </liferay-ui:search-container> </liferay-ui:panel> </liferay-ui:panel-container> </div> </aui:form> sorry for my English ;) A: You will need to use 2 Iterator Urls , one for each search container, then use the 'curParam' in each search:container for example : String table1Cur = ParamUtil.getString(renderRequest,"table1Cur"); PortletURL table1Url = renderResponse.createRenderURL(); table1Url.setParameter("table1Cur", table1Cur); <liferay-ui:search-container id="Table1Search" iteratorURL="<%= table1Url %>" curParam="table1Cur" >
doc_23532497
:class="showMenu === true ? 'bg-chevron' : 'bg-chevron-blue bg-contain', showDetail === true ? 'rotate-180' : ''" I use different colored icons according to showMenu and they should rotate according to showDetail. I seperate them with comma but only first condition works A: For multiple class bindings you need to use ternary conditions with in [] :class="[showMenu === true ? 'bg-chevron' : 'bg-chevron-blue bg-contain', showDetail === true ? 'rotate-180' : '']" <script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.x.x/dist/alpine.js"></script> <div x-data="{showMenu:true, showDetail: true}"> <label for="name" :class="[(showMenu === true ? 'bg-chevron' : 'bg-chevron-blue bg-contain'),(showDetail === true ? 'rotate-180' : '')]" >Name:</label> <input id="name" type="text" x-model="name" /> <p x-text="name"> </div>
doc_23532498
My curent thought is to utilize DsGetDcName, and use the GUID returned in the DOMAIN_CONTROLLER_INFO structure and compare it to a hard coded constant. It seems to reason that a domain GUID would only change if the domain is recreated, so this would provide functionality that I desire with limited overhead. My only concern is that I can't find any documentation on MSDN confirming my assumption. type EAccessDenied = Exception; EInvalidOwner = Exception; EInsufficientBuffer = Exception; ELibraryNotFound = Exception; NET_API_STATUS = Integer; TDomainControllerInfoA = record DomainControllerName: LPSTR; DomainControllerAddress: LPSTR; DomainControllerAddressType: ULONG; DomainGuid: TGUID; DomainName: LPSTR; DnsForestName: LPSTR; Flags: ULONG; DcSiteName: LPSTR; ClientSiteName: LPSTR; end; PDomainControllerInfoA = ^TDomainControllerInfoA; const NERR_Success = 0; procedure NetCheck(ErrCode: NET_API_STATUS); begin if ErrCode <> NERR_Success then begin case ErrCode of ERROR_ACCESS_DENIED: raise EAccessDenied.Create('Access is Denied'); ERROR_INVALID_OWNER: raise EInvalidOwner.Create('Cannot assign the owner of this object.'); ERROR_INSUFFICIENT_BUFFER: raise EInsufficientBuffer.Create('Buffer passed was too small'); else raise Exception.Create('Error Code: ' + IntToStr(ErrCode) + #13 + SysErrorMessage(ErrCode)); end; end; end; function IsInternalDomain: Boolean; var NTNetDsGetDcName: function(ComputerName, DomainName: PChar; DomainGuid: PGUID; SiteName: PChar; Flags: ULONG; var DomainControllerInfo: PDomainControllerInfoA): NET_API_STATUS; stdcall; NTNetApiBufferFree: function (lpBuffer: Pointer): NET_API_STATUS; stdcall; LibHandle: THandle; DomainControllerInfo: PDomainControllerInfoA; ErrMode: Word; const NTlib = 'NETAPI32.DLL'; DS_IS_FLAT_NAME = $00010000; DS_RETURN_DNS_NAME = $40000000; INTERNAL_DOMAIN_GUID: TGUID = '{????????-????-????-????-????????????}'; begin if Win32Platform = VER_PLATFORM_WIN32_NT then begin ErrMode := SetErrorMode(SEM_NOOPENFILEERRORBOX); LibHandle := LoadLibrary(NTlib); SetErrorMode(ErrMode); if LibHandle = 0 then raise ELibraryNotFound.Create('Unable to map library: ' + NTlib); try @NTNetDsGetDcName := GetProcAddress(Libhandle, 'DsGetDcNameA'); @NTNetApiBufferFree := GetProcAddress(Libhandle,'NetApiBufferFree'); try NetCheck(NTNetDsGetDcName(nil, nil, nil, nil, DS_IS_FLAT_NAME or DS_RETURN_DNS_NAME, DomainControllerInfo)); Result := (DomainControllerInfo.DomainName = 'foo.com') and (CompareMem(@DomainControllerInfo.DomainGuid,@INTERNAL_DOMAIN_GUID, SizeOf(TGuid)));//WideCharToString(pDomain); finally NetCheck(NTNetApiBufferFree(DomainControllerInfo)); end; finally FreeLibrary(LibHandle); end; end else Result := False; end; Added a related question on ServerFault as suggested. Found another interesting read on Technet which also seems to hint at me being right, but isn't specifically scoped at domain SID's. A: Create a service account on the domain; Get the GUID of the service account and encrypt it and save it somewhere (registry) maybe as part of enterprise install process to validate a license agreement. On startup of the client app query for the Domain Service Account GUID and validate it with the saved GUID. Or create your own enterprise 'key' server. Doing an LDAP query is easier than doing all the domain controller crap. A: If I correct understand your requirement the best API in your case is GetUserNameEx. You can choose the value of NameFormat parameter of the type EXTENDED_NAME_FORMAT which you can better verify. Another function GetComputerNameEx is helpful if you want additionally verify the information about the computer where the program is running. A: I have the need to restrict specific functions of an application based on the location of the currently logged in user If you are trying to find out the location of the currently logged in user, you shouldn't be using DsGetDcName. Your computer can be joined to domainA. Your logon user can be from domainB. Calling DsGetDcName on your computer doesn't give you domainB GUID but it will give you domainA GUID Therefore, I think you should use LookupAccountName instead. The LookupAccountName gives you the currently logged in user's SID. Then, you can extract the domain SID from the user SID. That domain SID is really the domain where this user coming from. For the details of how to extract a domain SID from a user SID, please check here Regarding to your original question about the uniqueness of the domain GUID, I am sorry that I don't have answer on it. AFAIK, there is no tool available allowing you to change the domain SID nor the GUID. I am not sure how hard to hack into it and change it.
doc_23532499
Problem: CQL resembles SQL, but it has some notable differences. The main one I am running up against right now is that it does not expect table names to be attached to column references in the queries and fails when they are. In SQL these prefixes are optional, unless they are being used to disambiguate complex queries. So, how can I make ActiveRecord stop prepending the table names to column references? I'm not sure if this needs to happen in ActiveRecord or possibly in ActiveRelation, which is part of my issue with being unable to resolve this issue. Example: SQL from ActiveRecord: SELECT positions.* FROM positions WHERE positions.sku = 'LM_180114' LIMIT 1 Desired CQL: SELECT * FROM positions WHERE sku = 'LM_180114' LIMIT 1