text
stringlengths 15
59.8k
| meta
dict |
|---|---|
Q: Does service still run in foreground after "show notifications" is un-checked? I know that to run as a foreground service, you need to show a notification. My app runs a service as a foreground service, and it shows a notification.
However, if the user goes into Settings -> Apps- > My app -> and un-checks "show notifications", will the service continue to run as a foreground service?
I assumed that yes, it will continue to run as a foreground service.
However, I recently noticed my service was killed by the system, and saw this in the logcat:
Killing 2647:com.myapp.myapp:Service/u0a122 (adj 15): kill background
The service was killed, and it did not restart itself. This is on Android 4.4.2. Worst of all, onDestroy was not called, so I couldn't even release some wake-locks.
A: Yes; the service still runs in foreground when "Show notifications" is unticked.
Run adb shell dumpsys activity services and check the value of the isForeground flag for your service.
* ServiceRecord{e66dea9 u0 com.example.foregroundservice/.ForegroundService}
intent={cmp=com.example.foregroundservice/.ForegroundService}
packageName=com.example.foregroundservice
processName=com.example.foregroundservice:backgroundproc
baseDir=/data/app/com.example.foregroundservice-2/base.apk
dataDir=/data/user/0/com.example.foregroundservice
app=ProcessRecord{254dd51 14363:com.example.foregroundservice:backgroundproc/u0a65}
isForeground=true foregroundId=101 foregroundNoti=Notification(pri=0 contentView=null vibrate=null sound=null tick defaults=0x0 flags=0x40 color=0x00000000 vis=PRIVATE)
createTime=-55s70ms startingBgTimeout=--
lastActivity=-55s70ms restartTime=-55s70ms createdFromFg=true
startRequested=true delayedStop=false stopIfKilled=false callStart=true lastStartId=1
Compatibility (using official Android emulators)
Not working:
*
*4.0.2 (the "Show notifications" setting isn't available)
Working:
*
*4.1.2
*4.2.2
*4.3.1
*4.4.2
*5.0.2
*5.1.1
*6.0
*7.0
*7.1
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23615970",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Referral lost after redirect I have a website (www.accent.jobs) which contains a language selection tool on the www. subdomain.
When choosing a language, a cookie is set, so the user only sees the language selection page once, and automatically get redirected the right way next time.
What I notice in Analytics, is that traffic from the www to a subdomain (be.accent.jobs for instance) is seen as referral traffic.
What I do on the www. subdomain:
*
*User clicks a link.
*Javascript does an AJAX request to a PHP file which sets the cookie.
*The user gets redirected through JavaScript using window.location.
When the user goes back to the www. subdomain, the redirect is done through PHP using a 302, without a page rendering.
Any ideas on how I could get the traffic from www. to a subdomain not to be handled as referral traffic in Analytics? I would like to keep the original referrer (the site that referred to www.accent.jobs) as the referrer in Analytics.
This is the tracking code on both the www and the be. subdomain:
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-xxxxxx-xx']);
_gaq.push(['_trackPageview']);
_gaq.push(['_setDomainName', 'accent.jobs']);
_gaq.push(['_addIgnoredRef', 'accent.jobs']);
_gaq.push(['_addIgnoredRef', 'be.accent.jobs']);
_gaq.push(['_addIgnoredRef', 'nl.accent.jobs']);
_gaq.push(['_addIgnoredRef', 'ro.accent.jobs']);
_gaq.push(['b._setAccount', 'UA-xxxxxx-x']);
_gaq.push(['b._trackPageview']);
_gaq.push(['b._setDomainName', 'accent.jobs']);
_gaq.push(['b._addIgnoredRef', 'accent.jobs']);
_gaq.push(['b._addIgnoredRef', 'be.accent.jobs']);
_gaq.push(['b._addIgnoredRef', 'nl.accent.jobs']);
_gaq.push(['b._addIgnoredRef', 'ro.accent.jobs']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
PS: I'm tracking on multiple UA accounts to keep the data in an older account as well, hence the 'double' tracking code.
Tries
*
*Tried replacing the JavaScript redirect by server-side 302 header redirects in PHP, no luck.
*Also tried using only JavaScript redirects, still no luck.
A: Your _setDomainName usage is correct and sufficient.
But its value is never send to Analytics : you must use it BEFORE _trackPageview.
Then _addIgnoredRef is not useful anymore.
A: Move the _trackPageview calls after the _setDomainName and _addIgnoredRef calls.
_setDomainName sets the domain for the GA cookies, which get set during _trackPageview. By having _setDomainName after _trackPageview, the default cookie domain is used, resulting in two different sets of cookies, and the data not transferring between domain/subdomain.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13579577",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: COM component not activated due to privilege issue We have developed an office add-in. Its working fine with every other system except one. In that particular system when we try to load the app, it fails with a generic error (This app could not be started. Close this dialog to ignore the problem or click "Restart" to try again.). Event viewer has the following details
The machine-default permission settings do not grant Local Activation permission for the COM Server application with CLSID
{9BA05972-F6A8-11CF-A442-00A0C90A8F39}
and APPID
{9BA05972-F6A8-11CF-A442-00A0C90A8F39}
to the user STC\inmchandr SID (S-1-5-21-2779513660-4158667818-3257731910-104078) from address LocalHost (Using LRPC) running in the application container Unavailable SID (Unavailable). This security permission can be modified using the Component Services administrative tool.
The specified CLSID points to ShellWindows component, which is running with "Interactive User" account. I am unable to change the other security permissions like launching permissions for that component in DCom config. I tried to change the permission for the corresponding registry entry (as suggested in this link) But, nothing worked out.
The winword.exe is running as the same user who logged in. This system and the other systems (where it is working) are in the same network and I tried running gpupdate as well.
(In that problematic system) The same app is loading when we tried to run Word as administrator. The URL used for that taskpane app is launching without any issues from browsers
OS: Windows 8.1
Processor: 64 bit
Office: 2013
Could anyone help us out to resolve the issue?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32964191",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: React Native - How to build expo react native app so that it does not require Expo android app to open i have Developed a React Native app using expo. I build it using expo amd downloaded and installed apk file but still using Expo app to open app in the android phone. But i want that it can be installed and run without expo app so that i can share it with my friends. I think I have to use Android studio for that , right?? But I'm a newbie and I don't know how to use Android Studio. I have ejected App from expo and i have Android folder with me. Please guide what to do next to make my app sharable and publishable.
A: Check out the distribution section of the Expo documentation: https://docs.expo.io/distribution/introduction/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63440871",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Why does gitlab show more tabs than the one in the sublime editor? I write code in sublime with tab width:4. When I push my code to gitlab, it shows with 1 more tab in the indentation. What's wrong here ? How should I setup my sublime to prevent this ?
A: The underlying issue you're having here is that you're using physical tab characters and not spaces for indentation. While a space character has a very definite width (one character), a tab character has no intrinsic width. It's a single character that means "insert a level of indent here".
How big that indent displays as is entirely controlled by whatever it is that's displaying the text. The general idea of using a physical tab in this manner is that each individual person can set the display size of the tab to whatever they like, and as a result the text of the file doesn't change, but it's display does. In contrast, using spaces for indent causes the physical file to look the same for everyone that views it, regardless of their settings.
While you have set tab_size to 4 in Sublime, that is of no consequence to GitLab (or any other editor or display mechanism for your file) because all the file contains is a single tab character with no defined width. It so happens that GitLab has a default tab size of 8 characters instead of 4.
Hence, it appears as if there is one extra tab everywhere, but in reality if you use your mouse to select your text a character at a time you'll see that the tab is actually 8 characters wide.
For GitLab, there's a setting that controls this:
*
*Click on your profile picture in the top right and select Settings
*In the menu along the left hand side of the settings page, select Preferences
*In the section labeled behaviour, there's a setting for Tab Size; set that to your desired tab width and click Save Changes at the bottom of the window.
This particular setting is currently per-user and not per-project, so what you set here applies to everything across GitLab.
GitHub also has a default tab width of 8; however there you can append ?ts=4 to a URL displaying a file to alter the tab size on the fly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65073971",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What does this regexp mean - "\p{Lu}"? I stumble across this regular expression in c# I would like to port to javascript, and I do not understand the following:
[-.\p{Lu}\p{Ll}0-9]+
The part I have a hard time with is of course \p{Lu}. All regexp websites I visited never mention this modifier.
Any idea?
A: These are considered Unicode properties.
The Unicode property \p{L} — shorthand for \p{Letter} will match any kind of letter from any language. Therefore, \p{Lu} will match an uppercase letter that has a lowercase variant. And, the opposite \p{Ll} will match a lowercase letter that has an uppercase variant.
Concisely, this would match any lowercase/uppercase that has a variant from any language:
AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25977309",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "30"
}
|
Q: Define a Class Function Operator How can I define in PHP a class Foo that allows to do something like:
$foo = new Foo();
$foo->bar;
$foo();
A: You're asking about invokable objects, or treating objects as functions. To be able to do that, you need to implement __invoke() method, like this:
class Foo {
public function __invoke()
{
echo 'invoke!';
}
}
Read more: http://php.net/manual/en/language.oop5.magic.php#object.invoke
Also, you can call $foo->bar; as many times as you want, just as you can write: $a = 5; $a; - but it will have no effect. It's just a field. If it's a callable, you'll have to add parentheses to call it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39333129",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: jQuery not stopping POST after executing I'm using ASP.Net MVC 4, and in one of my views I'm going to be using jQuery. The jQuery is written on the create page. It is as follows:
\View:
<table>
<tr>
<td><h2>Strategy Types</h2></td>
</tr>
<tr class ="strategyType">
@{
int count = 0;
List<LearningEnterprises.ViewModel.AssignedStrategyType> strategytypes = ViewBag.StrategyType;
foreach (var strategytype in strategytypes)
{
if (count++ % 3 == 0)
{
@:</tr><tr>
}
@:<td>
<input type="checkbox"
name="selectedStrategyTypes"
value="@strategytype.StrategyTypeID"
/>
@strategytype.StrategyTypeID @: @strategytype.Title
@:</td>
}
@:</tr>
}
<tr>
<td class="strategyTypeVal">
</td>
</tr>
</table>
<p>
<input id="createButton" type="submit" value="Create" />
</p>
</fieldset>
\jQuery
<script>
if ($(".strategyType td input:checked").length == 0 && $(".strategyTypeVal").empty()) {
$(".strategyTypeVal").append("Please select at least one strategy type.").css("font-weight", "Bold").css('color', 'red');
}
else { $(".strategyTypeVal").empty(); }
Now the code displays the error message properly, but the post still goes through, it doesn't stop the website from creating an article.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22238009",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is there a tool that can convert common image formats (.bmp, jpg,..) to .emf files? I'm using the GoDiagrams suite which seems to recommend .emf files for node images since they scale better on resizing. Bitmaps get all blurry.
Google doesn't show up any good tools that seem to do this... So to reiterate I'm looking for a image converter (preferably free) that converts an image (in one of the common formats like Bitmaps or JPEGs or GIFs) to an .EMF File.
Update: I dont need to do it via code. Simple batch-conversion of images will do.
A: Inkscape works well, it was recommended to me here.
A: Irfanview (http://www.irfanview.com) supports many image formats (including .emf). It's also small, fast, and very full-featured. It is free for non-commercial and educational use. I use it for all my image-conversion needs as it will work on batches of files and can rename them as it saves.
A: Image Magick contains a tool called convert, that will convert from just about anything to EMF files. You can either use this as a separate application, or interface to it using an API that is available in several different languages.
A: XnView (http://www.xnview.com). Very good viewer and converter.
A: Try ImageConverter Plus
A: Try http://autotrace.sourceforge.net/. It is opensource and it has good results. Download from here: http://sourceforge.net/project/showfiles.php?group_id=11789
A: Really funny one Microsoft. Now this might seem outlandish but it works... (I have Visio2007). Just found this out from a colleague
You can drop a JPEG into Microsoft Visio (no less), Do a 'Save As' to .emf and voila! nice quality of a picture too.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53941",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: jQuery UI Sortable update database Hey I'm working on a CMS for a website I'm building and in the CMS I have all my fields with the data and I'm using jQuery UI Sortable so I can sort them, what I'm wondering is what is the best way to update the order field in my database when I drop my element? Would I use Ajax? If so what should I search to do this function (I've never used Ajax). Thanks in advance for any help!
A: Ajax is a great alternative to do just that.
jQuery has built-in support for Ajax. I would start out with simple examples from the API Docs and work up from there.
You can use the change event of Sortable to know when you need to save the sort order again:
http://api.jqueryui.com/sortable/#event-change
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15540188",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Inheritence vs Composition - An OOP Architectural Consideration I'm having trouble figuring out a clean way to implement my layering.
Here are the layers I have (lower layers support upper layers, either through inheritence
or composition):
Business Logic Layer (BLL)
Datastore Layer (DSL)
Database Layer (DBL), Web-Service Buffer (WSB)
When a BLL object makes a get request, getRecords(), it in turn asks the DSL to fulfill it.
The DSL then decides on weather to use the local DBL, or to use the WSB (which communicates with a remote web-service front end to a "master" DB).
Option 1 - Composition (BLL has-a DSL, DSL has-a DBL)
My problem is that since the DSL and DBL objects are composed within the BLL, they know nothing of the containing BLL, and so how are they supposed to make specific DB querys that include the BLL fields ?
Option 2 - Inheritence (BLL : DSL, DSL : DBL)
Even if the lower layers now have access to a BLL through public/protected inheritence, the question still remains as to how DSL and DBL are to know exactly which specific query strings to generate. I suppose that the BLL could keep a set of static strings, but then that creates a two-way dependency, which I assume is a really flawed design with horrific consequences.
Note: Each BLL has a corresponding table that it is serialized to / deserialized from.
Note: I do not want to use reflection, and would like to limit the use of generics (unless there is absolutely no other way. I'm using genreics for my WSB, which is working out fine, though my prime concern is with generating the BLL-specific query strings within the DSL and DBL layers).
Note: There are going to be many diverse BLL objects that will be using the DSL and DBL layers, not just one (otherwise this would be trivial).
public class BL1
{
private DSL _dsLayer;
public getRecords()
{
// ...
_dsLayer.getRecords();
// ...
}
}
public class DSL
{
private DBL _dbLayer;
private WSB _wsBuffer;
public getRecords()
{
if(_dbLayer.getRecords() != null)
{
return records;
}
else
{
return _wsBuffer.getRecords();
}
}
}
public class DBL
{
private string _db = "file.db3";
public getRecords()
{
select ????? - how to know what fields to grab
}
}
Thank you for taking some time in answering this, it is greatly appreciated.
A: You should go with Composition. I don't think Inheritance makes sense because these are completely different type of entities and really one cannot inherit from the other. What fields will they inherit? And who inherits from whom?
The BLL will need to pass the list of 'fields' to get to the DSL. Either as parameters to the DSL methods or in some other way. The DSL methods just receive some list of fields as parameters and work with them. I think that is a feasible solution.
Also, you should create Interfaces at each Layer and program against them instead of using the type itself. So for e.g, in the sample code that you wrote, change DBL and WSB to IDBL and IWSB. This will help you test better and allow for loose coupling in the code.
public class DSL
{
private IDBL _dbLayer;
private IWSB _wsBuffer;
....
}
A: In general, inheritance should be used when you have an 'Is-A' relationship. Since you cannot say BLL 'Is-A' DSL or DSL 'Is-A' DBL, then I would be looking at composition over inheritance. This has the side effect of making testing each logical layer easier because you can stub or mock each dependency.
Typically, in any exposed API, the server side (so DSL in terms of BLL -> DSL), would need to expose objects to do its work. You are right in pointing out that DSL should not know about BLL objects. So the challenge is to write a clean API for the DSL that is exposed to BLL for querying data.
I would suggest looking at both the Repository and Specification patterns from DDD. These help to solve some of the issues that you are bringing up.
A: Composition.
Because of everything that dtryon and desigeek have said and also
because in your case Inheritance looks unnatural + it will make all your
layers tightly coupled and will hardly limit making of any amends to source code.
I believe it could be helpful to take a look at prefer-composition-over-inheritance SO-topic.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11525364",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: concurrency problems in interceptor tracking MDC I have the following interceptor that tracks request/response based on saving and restoring some vars stored in MDC context for every request.
public class LoggingInterceptor implements DeferredResultProcessingInterceptor {
private final HelloSeeYouLogger helloSeeYouLogger;
private static final String X_UOW = "X-UOW";
private static final String X_REQUEST_ID = "X-RequestId";
private Map<String, String> context;
public LoggingInterceptor(HelloSeeYouLogger helloSeeYouLogger) {
this.helloSeeYouLogger = helloSeeYouLogger;
}
@Override
public <T> void beforeConcurrentHandling(NativeWebRequest request, DeferredResult<T> deferredResult) {
addUowAndRequestIdToMDC(request.getHeader(X_UOW), request.getHeader(X_REQUEST_ID));
final String uri = getUri((HttpServletRequest) request.getNativeRequest());
helloSeeYouLogger.logHelloThere(uri);
context = MDC.getCopyOfContextMap();
}
@Override
public <T> void afterCompletion(NativeWebRequest request, DeferredResult<T> deferredResult) {
if (context != null) {
MDC.setContextMap(context);
}
final String uri = getUri((HttpServletRequest) request.getNativeRequest());
String body = getBody((HttpServletRequest) request.getNativeRequest());
if (!StringUtils.isEmpty(body)) {
body = replaceMoreThanOneSpacesWithOneSpace(hideCreditCardNumber(body));
}
helloSeeYouLogger.logSeeYou(uri, body);
clearUowAndRequestIdFromMDC();
}
public static void addUowAndRequestIdToMDC(final String uow, final String requestId) {
//This NewRelic stuff shouldn't be here as it is used for distributed tracing and not logging.
// However it helps to levarage requests tracking from a metric service such as new relic to a log aggregation service
//such as ELK.
NewRelic.addCustomParameter(UOW, uow);
NewRelic.addCustomParameter(REQUEST_ID, requestId);
MDC.put(UOW, uow);
MDC.put(REQUEST_ID, requestId);
}
public static void clearUowAndRequestIdFromMDC() {
if (MDC.get(UOW) != null) {
MDC.remove(UOW);
}
if (MDC.get(REQUEST_ID) != null) {
MDC.remove(REQUEST_ID);
}
}
I think i mn going to have concurrency problems as context is an instance variable and when running multiple concurrent thread saving and restoring MDC context will result in wrong results. Also using synchronize keyword will add performance problems.
I was wondering if there is a better approach to track MDC context when a spring controller returns a DeferredResult.
Thanks
A: You can use try using HandlerInterceptorAdapter instead
Check: https://www.logicbig.com/how-to/code-snippets/jcode-spring-mvc-deferredresultprocessinginterceptor.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51848695",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is anybody happily using Google Analytics with big websites? (million+ pages, million+ monthly visitors) I was a happy customer of Google Analytics starting from the Urchin times. But something strange happened a few months ago and GA started showing a fake URL called "(other)" that is credited between 5% and 45% of all site traffic. I've tried filtering out some URL parameters to reduce the number of pages. Currently GA shows only 150,000 pages on my site, which is well below the half million limit that some people are talking about. Still, the page "(other)" is showing as the most popular page on my site.
Is anybody else struggling with this issue? I am wondering whether this could be a scalability issue. My site has been growing over the years, and currently doing 1.25 million unique monthly visitors and over 10 million pageviews. The site itself has around half a million pages. If you are successfully using GA with a bigger website than mine, please share your story. Are you using the Sampling feature of their tracking script?
Thanks!
A: For a huge website like and I would not use a Free Analytics. I would use something like Web trends or some other paid analytics. We cannot blame GA for this after all its a free service ;-)
GA has page view limits too. (5 Million page views)
Just curious. How long did you take to add the analytics code to your pages? ;-)
A: In Advanced Web Metrics with Google Analytics Brian Clifton writes that above a certain number of page views, Google Analytics is no more able to list all the seperate page views and starts aggregating the small amount ones under „(other)” entry.
By default, Google Analytics collects
pageview data for every visitor. For
very high traffic sites, the amount
of data can be overwhelming, leading
to large parts of the “long tail” of
information to be missing from your
reports, simply because they are too
far down in the report tables. You can
diminish this issue by creating
separate profiles of visitor
segments—for example, /blog, /forum,
/support, etc. However, another option
is to sample your visitors.
A: I get about 3.5 million hits a month on one of my sites using GA. I don't see (other) listed anywhere. Specifically what report are you viewing? Is (other) the title or URL of the page?
A: You can get a loooonnnngggg way on Google Analytics. I had a site doing about 25mm uniques/mo. and it was working for us just fine. The "other" bucket fills up when you hit a certain limit of pageviews/etc. The way around this is to create different filters on the data.
A: For a huge website (millions of page views per day), you should try out SnowPlow:
https://github.com/snowplow/snowplow
This will give you granular data down to the individual page URLs (unlike Google Analytics at that volume) and, because it is based on Hadoop/Hive/Infobright, it will happily scale up to billions of page views.
A: Its more to do with a daily limit of unique values for a metric they will report on. if your site uses querystring parameters, all those unique values and parameter variations are seen as separate pages and cause the report to go over the limit of 50,000 unique values in a day for a metric. To eliminate, you should add all the big culprits querystring names to be ignored, making sure however to not add any search querystring names if search is on.
On the Profile Settings, add them to the Exclude URL Query Parameters textbox field, delimited by commas. Once I did this, the (other) went away from the reports. It takes affect at the point they are added, previous days will still have (other) displaying.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/927113",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: how to join two tables in database Laravel I'm trying to join two tables (products table and Images table), so in products table each product has multiple images(stored in a row named image) so I want to display images of each product in images table. In images table I have a foreign key named product_id references(id) on products table, The problem is it can't store images in images table,(it keeps storing images in the row(image) in products table). How do I solve this?
Codes
Product.php
public function images()
{
return $this->hasMany('App\Image', 'product_id');
}
Image.php
public function product()
{
return $this->belongsTo('App\Product','product_id');
}
Controller
public function store(Request $request)
{
$Input=$request->all();
$image=array();
if($files=$request->file('image')){
foreach($files as $file){
$name=$file->getClientOriginalName();
$file->move('images',$name);
$image[]=$name;
}
}
product::create(array_merge($Input,
[
'image' => json_encode($image),
]));
return redirect()->back();
}
Any help will be appriciated.
A: If you are trying to save the image to the images table, and you are instead 'it keeps storing images in the row(image) in products table' - you are saving the wrong item. You appear to have the correct structure - with one to many in your models. Just need to save the Image rather than the Product
Something like this will fix this issue:
Image::create(['whateverYouNeedToSave',
'product_id'=>$product_id, <-- Connect the product here, within the image
'etc']);
It is actually possible to do this by creating the Product and then saving the Images as a relation, but this might not be the cleanest / easiest way to architect this - suggest you start with saving the Image, as you will have many of them, vs. just one Product at a time. Then, after this works, and is clear / comfortable, you can try it the more 'advanced' way if you need to.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/56821633",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Numeric type as DependencyProperty How to register custom property which based on numeric type?
public class NumberBox : TextBox
{
public static readonly DependencyProperty FormatProperty = DependencyProperty.Register("FormatValue", typeof(Type), typeof(NumberBox), new UIPropertyMetadata(default(Double)));
public Type FormatValue
{
get
{
return (Type)GetValue(FormatProperty);
}
set
{
SetValue(FormatProperty, value);
}
}
}
XAML
<nb:NumberBox FormatValue="{System:Int32}"/>
I am sure, that is not perfect, but I really don't know how it make workable.
UPDATE:
Basically, me need to have a way to set the type of my number box. For example, if I need to use Double NumberBox I just set FormatValue="Double"
A: First issue is default metadata provided in last parameter of DP identifier is incorrect.
Instead of
new UIPropertyMetadata(default(Double)),
it should be
new UIPropertyMetadata(typeof(Double))
Second issue in XAML. Use x:Type to pass type.
<nb:NumberBox xmlns:sys="clr-namespace:System;assembly=mscorlib"
FormatValue="{x:Type sys:Int32}"/>
A: From here http://msdn.microsoft.com/en-us/library/ee792002%28v=vs.110%29.aspx, the types are x:Int32, x:Double, ...
So you want to use:
<nb:NumberBox FormatValue="{x:Type x:Int32}"/>
In the general sense, you would have to include the namespace in the XAML:
<Window ...
xmlns:ns="clr-namespace:MyNamepsace;assembly=MyAssembly"
>
<nb:NumberBox FormatValue="{x:Type ns:MyType}"/>
</Window>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24060270",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I get the window width in angularJS on resize from a controller? Ho can I get the window width in angularJS on resize from a controller? I want to be able to get it so I can display some div with <div ng-if="windowWidth > 320">
I can get the windowWidth on the initial page load but not on resize...
'use strict';
var app = angular.module('app', []);
app.controller('mainController', ['$window', '$scope', function($window, $scope){
var mainCtrl = this;
mainCtrl.test = 'testing mainController';
// Method suggested in @Baconbeastnz's answer
$(window).resize(function() {
$scope.$apply(function() {
$scope.windowWidth = $( window ).width();
});
});
/* this produces the following error
/* Uncaught TypeError: mainCtrl.$digest is not a function(…)
angular.element($window).bind('resize', function(){
mainCtrl.windowWidth = $window.innerWidth;
// manuall $digest required as resize event
// is outside of angular
mainCtrl.$digest();
});
*/
}]);
// Trying Directive method as suggested in @Yaser Adel Mehraban answer.
/*app.directive('myDirective', ['$window', function ($window) {
return {
link: link,
restrict: 'E'
};
function link(scope, element, attrs){
angular.element($window).bind('resize', function(){
scope.windowWidth = $window.innerWidth;
});
}
}]);*/
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"></script>
<body ng-app="app" ng-controller="mainController as mainCtrl">
<p>{{mainCtrl.test}}</p>
<hr />
<p ng-if="windowWidth > 600">The window width is {{windowWidth}}</p>
<div my-directive ng-if="windowWidth > 320">It works!</div>
</body>
I see in this answer they explain how you can get it from within a directive but how can you get it to work from within a controller?
A: Finnally got it working with the below. Took most of the code from https://stackoverflow.com/a/23078185/1814446.
The only difference was for the ng-if to work the directive had to be put on a parent html element.
'use strict';
var app = angular.module('app', []);
app.controller('mainController', ['$window', '$scope', function($window, $scope){
var mainCtrl = this;
mainCtrl.test = 'testing mainController';
}]);
app.directive('windowSize', function ($window) {
return function (scope, element) {
var w = angular.element($window);
scope.getWindowDimensions = function () {
return {
'h': w.height(),
'w': w.width()
};
};
scope.$watch(scope.getWindowDimensions, function (newValue, oldValue) {
scope.windowHeight = newValue.h;
scope.windowWidth = newValue.w;
scope.style = function () {
return {
'height': (newValue.h - 100) + 'px',
'width': (newValue.w - 100) + 'px'
};
};
}, true);
w.bind('resize', function () {
scope.$apply();
});
}
})
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"></script>
<body window-size my-directive ng-app="app" ng-controller="mainController as mainCtrl">
<p>{{mainCtrl.test}}</p>
<hr />
<div ng-if="windowWidth > 500">
<h4 style="margin:5px 0">It works!</h4>
<p style="margin:0">window.height: {{windowHeight}}</p> <p style="margin:0">window.width: {{windowWidth}}</p> <p style="margin:0">{{mainCtrl.test}}</p>
</div>
</body>
A: Getting the window width on resize isn't anything specific to Angular JS. in fact Angular doesn't provide any capability to do it. It's native javascript, the native window object fires a resize event that you can access. jQuery provides a handy wrapper for this. By using a simple callback in your controller and then updating your double bound windowWidth property on the $scope object you can get the functionality you need without using a directive.
$(window).resize(function() {
$scope.windowWidth = $( window ).width();
});
A: Just include this code in your controller and you will get the new window width every time.
$scope.windowWidth = $window.innerWidth;
angular.element($window).bind('resize', function(){
$scope.windowWidth = $window.innerWidth;
$scope.$apply();
});
A: The best way is to use a directive and watch for resize event of the window:
'use strict';
var app = angular.module('plunker', []);
app.directive('myDirective', ['$window', function ($window) {
return {
link: link,
restrict: 'A'
};
function link(scope, element, attrs){
angular.element($window).bind('resize', function(){
scope.windowWidth = $window.innerWidth;
});
}
}]);
And use it on your div:
<div my-directive ng-if="windowWidth > 320">
Here is a working plunker.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41175143",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
}
|
Q: Reset variables inside a 'foreach' loop As I have really many variables inside my foreach loop, it would be great if I could reset them all at once instead of:
$variable_one = ''; // Reset to: It is blank for each loop
$variable_two = '';
...
$variable_hundred = '';
A: If I were you and had these number of variables which should be set to some value in a loop, I would use an array instead:
$arr = ['first value', 'second value','hundred value'];
Then you can access what you want by index in your loop, so instead of using:
$variable_one
You will use:
$arr[0]
And now you want to reset them all, so you can use array_map() like this:
$arr = array_map(function($val){ return '';}, $arr);
A: If you have such a high number of variables in your loop, you probably should refactor it to make it simpler. If you are sure that having 100 variables inside a loop is a way to go, you can use the following expression:
$variable_one = $variable_two = $variable_hundred = '';
This will set each variable to '' in one very long line.
Another option is to unset() all these variables in a single function call:
unset($variable_one, $variable_two, $variable_hundred);
But this will not set their value to '', but unset the variable itself.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41659108",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: JavaScript: escape vs. unescape I saw some sites were using the JavaScript escape() and unescape() functions interchangeably.
Some used:
document.write('<img height="1" width="1" style="border-style:none;" alt="" src="..."/>');
whereas, this was also pretty common (note: they first "escape" the string, then "unescape" it):
document.write(unescape('%3Cimg%20height%3D%221%22%20width%3D%221%22%20style%3D%22border-style%3Anone%3B%22%20alt%3D%22%22%20src%3D%22...%22/%3E'));
The latter seems to achieve the same as the former, only using a longer way. Any differences in these two methods?
A: It isn't clear in this example. But you can not have inline scripts containing <script> or </script> inside of a string, or the browser will try and process it like a script tag.
Escaping and unescaping html avoids this problem. A better solution is to put the script in a separate file from the html document.
A: For xhtml compliance you cannot have any HTML tag (<div></div> or <img />) inside a script block so either you use unescape or concatenation '<' + 'div...' or you add //<![CDATA[ ... //]]> inside the script block to pass validation.
A: Line breaks and similar quotes to the JavaScript's break the parser.
var test = "This "string", for example.";
Backslash escapes are built-in, so this works:
var test = "This \"string\", for example.";
But then you'd have to find a function to escape ", ', \n, \r, and from the other answers, < and > as well.
escape() already encodes strings to remove most non-alphanumeric characters, and unescape() undoes escape().
escape("It's > 20% less complicated this way.")
"It%27s%20%3E%2020%25%20less%20complicated%20this%20way."
If the escaped spaces bother you, try:
escape("It's > 20% less complicated this way.").replace(/%20/g, " ")
"It%27s %3E 20%25 less complicated this way."
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4891992",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Pass ID of row to Detail Page with PDO I'm trying to update a master/detail setup from mysql to PDO in order to be compatible with PHP7. I have got the master page working exactly as it should - it produces a table that lists audio files and when you click on a title the idea is that you are taken to a detail page where the audio player is displayed. I am having trouble coding the detail page so that the ID from the master page is passed to the detail page and displays title and author together with the HTML5 audio player.
Here is the code for the master page:
<?php
$doc->addScript(JURI::root(true).'/templates/nfhop/js/sorttable.js' )
?>
<?php
require_once JPATH_SITE.'/includes/dbAudio.php'; ?>
<?php $query = $handler->query('SELECT * from audio ORDER BY subject ASC'); ?>
<article class="left">
<div class="formwrap">
<table class="members-audiolist table-striped sortable" border="0" align="left">
<thead>
<tr class="audio_header">
<td><p class="house-red">Subject</p></td>
<td><p class="house-red">Title</p></td>
<td><p class="house-red">Author</p></td>
</tr>
</thead>
<?php
while($r = $query->fetch(PDO::FETCH_OBJ)) { ?>
<tbody>
<tr>
<td width="25%"><?php echo $r->subject; ?></td>
<td><a href="index.php/audioplayer-pdo?recordID=<?php echo $r->id; ?>"> <?php echo $r->title; ?></a></td>
<td><?php echo $r->author; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
<div class="clearfix"></div>
</div>
<div style="margin-left:18px">
<p style="margin-top: 8px; font-size: 1em">To listen: click on title</p>
<p style="font-size: 1em">To download: right click on title and select save link as...</p>
<p style="font-size: 1em">You can sort by subject, title or author, just click on heading at top of column</p>
</div>
</article>
And this is my attempt at code for the detail page:
<?php
require_once JPATH_SITE.'/includes/dbAudio.php';
$query = $handler->query('SELECT * FROM audio WHERE id = ?'); ?>
?>
<hr class="divider" />
<h2><?php echo $r->title; ?> </h2>
<p>Speaker: <?php echo $r->author; ?> </p>
<p><?php echo $r->date; ?> </p>
<p><span style="font-style: italic">Category: <?php echo $r->subject; ?> </p><br />
<audio controls>
<source src="http://media.nfhop.org/<?php echo $r->audio_location; ?>" type="audio/mp3">
</audio>
<p class="margin-T10"><a href="http://www.nfhop.org/<?php echo $r->notes_location; ?>"> <img src="http://www.nfhop.org/<?php echo $r->image; ?>"></a></p>
<p><a href="/index.php/resources/audio">return to audio list</a>
Would be grateful for any assistance in getting this to work!
A: If $handler is an instance of PDO you could do it like this:
<?php
require_once JPATH_SITE.'/includes/dbAudio.php';
// Audio id is stored in `$_GET['recordID']`
$stmt = $handler->prepare('SELECT * FROM audio WHERE id = ?');
$stmt->bindParam(1, $_GET['recordID']);
$stmt->execute();
$r = $stmt->fetch(PDO::FETCH_OBJ);
print_r($r);?>
According to what properties are there in $r you can output them.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45403663",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to populate listview with a lot of information without blocking? I am creating an array of ListViewItems on a background thread and then i populate my listview with it on the ui thread. The problem is that if the array is too big the ui blocks while the listview is updated.
Is there a way to populate the listview with a small impact on the ui?
A: If you have a lot of data going into it you might want to use it in virtual mode, by setting the VirtualMode property of the ListView control to true. That means that the ListView will not be populated in the traditional sense, but you will hook up event handlers where you deliver the information to the list view in small chunks as the items are being displayed.
Very simple example:
private List<string> _listViewData = new List<string>();
private void toolStripButton1_Click(object sender, EventArgs e)
{
_listViewData = GetData(); // fetch the data that will show in the list view
listView1.VirtualListSize = _listViewData.Count; // set the list size
}
// event handler for the RetrieveVirtualItem event
private void listView_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
{
if (e.ItemIndex >= 0 && e.ItemIndex < _listViewData.Count)
{
e.Item = new ListViewItem(_listViewData[e.ItemIndex]);
}
}
You should also look into using the CacheVirtualItems event.
A: You can also use BeginUpdate and EndUPdate methods
listView1.BeginUpdate();
//Add Values
listView1.EndUpdate();
A: My comments got quite long, so I decided to make this a separate post.
First, +1 for Fredrik Mörk, using VirtualMode is the way to go. However, you do lose some functionality, e.g. column autosize, and sorting is easier handled on your own.
If that is a problem, populating from a worker thread may sound sounds tempting. However, the population will still take place in the thread that owns the list control (i.e. virtually always the main thread) - .NET makes that visible by enforcing you to use (Begin)Invoke. Additionally, the context switches will notably increase the total time you need to fill all items if you fill one by one, so you want to fill in chunks (say 50 items at a time, or even better fill as many as you can in 20 milliseconds). Add to that the additional synchronization required when contents changes, you have a quite complex solution for a not-so-stellar result.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1052475",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Merge two files by one column - awk I have two different scripts to merge files by one matching column.
file1.tsv - 4 columns separated by tab
1 LAK c.66H>T p.Ros49Kos
2 OLD c.11A+1>R p.Ill1639Los
3 SRP c.96V-T>X p.Zub%D23
4 HRP c.1S>T p.Lou33aa
file2.tsv - 14 columns, separated by tab
LAK "empty_column" c.66H>T ......
SRP "empty_column" c.96-T>X ......
Ouptut.tsv - all columns from file2.tsv and behind 1st column of file1 if match.
LAK "empty_column" c.66H>T ......1
SRP "empty_column" c.96-T>X ......3
I am using these two scripts, but doesn´t work:
awk -v FILE_A="file1.tsv" -v OFS="\t" 'BEGIN { while ( ( getline <
FILE_A ) > 0 ) { VAL = $0 ; sub( /^[^ ]+ /, "", VAL ) ; DICT[ $3 ] =
VAL } } { print $0, DICT[ $3 ] }' file2.tsv
or
awk 'NR==FNR{h[$3] = $1; next} {print h[$3]}' file1.tsv file2.tsv
Thanks for help.
A: You might want to use the join command to join column 2 of the first file with column 1 of the second:
join --nocheck-order -1 2 -2 1 file1.tsv file2.tsv
A few notes
*
*This is the first step, after this, you still have the task of cutting out unwanted columns, or rearrange them. I suggest to look into the cut command, or use awk this time.
*The join command expects the text on both files are in the same order (alphabetical or otherwise)
*Alternatively, import them into a temporary sqlite3 database and perform a join there.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52057225",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PyQt Segmentation fault in addItems for a combox When I run the following code it generates a segmentation fault:
from PyQt4 import QtGui
import sys
app=QtGui.QApplication(sys.argv)
methodNameComboBox=QtGui.QComboBox()
methodNameComboBox.addItems(['a','b'])
methodNameComboBox.show()
sys.exit(app.exec_())
but changing it to this works just fine
from PyQt4 import QtGui
import sys
app=QtGui.QApplication(sys.argv)
methodNameComboBox=QtGui.QComboBox()
methodNameComboBox.addItem('a' )
methodNameComboBox.addItem('b' )
methodNameComboBox.show()
sys.exit(app.exec_())
so the fault is generated by the method addItems .
gdb gives me the following result:
Program received signal SIGSEGV, Segmentation fault.
0x000000b400000229 in ?? ()
using python 3.3.0 qt 4.7.1 and pyqt 4.9.6 is there something wrong with any of the installations?
EDIT:
this is the same as another statement I was trying to use.
See: Fatal Python error: Segmentation fault for PyQt ui
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27797236",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Java compiler error variable is already defined I am new to programming and am having difficulty figuring this error out:
C:....>javac Power.java
Power.java:12: error: variable i is already defined in method main(String[])
`for(int **i** = 0; i < upper_limit + 1; i++)`
Here is the entire program. I'm sure the answer is super simple but for the life of me I can't figure it out.
import java.util.Scanner;
public class Power {
public static void main( String args[] ) {
Scanner input_scanner = new Scanner(System.in);
System.out.print("Powers of 2 up to? ");
int upper_limit = input_scanner.nextInt();
int i = 0;
for (int i = 0; i < upper_limit + 1; i++) {
System.out.println(i + " - " + Math.pow(2, i));
}
}
}
A: The i variable is already defined as part of the for loop. Just remove the following line:
int i = 0;
A: int i = 0;
for(int i = 0; i < upper_limit + 1 ; i++ )
{
remove the int inside the for loop or the remove the line above the for loop. now you define int i twice
A: you define the variable i twice in your code. It should only be defined on time. I have highlighted the two times below.
Scanner input_scanner = new Scanner( System.in );
System.out.print( "Powers of 2 up to? " );
int upper_limit = input_scanner.nextInt();
int i = 0; //First time i is defined
for(int i = 0; i < upper_limit + 1 ; i++ ) //second time i is defined
{
System.out.println( i + " - " + Math.pow( 2, i));
}
To fix this either remove one of the int i = 0 lines. Both options shown below:
int upper_limit = input_scanner.nextInt();
//First definition removed
for(int i = 0; i < upper_limit + 1 ; i++ ) //second time i is defined
{
System.out.println( i + " - " + Math.pow( 2, i));
}
second solution
int upper_limit = input_scanner.nextInt();
int i = 0; //First time i is defined
for(; i < upper_limit + 1 ; i++ ) //second definition removed
{
System.out.println( i + " - " + Math.pow( 2, i));
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29371118",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: back press on fragment finishing activity I have an activity with fragments that it navigates too. When you hit back on the fragment it should return back to the activity. But when you hit back at the moment the app closes.
Now thats not totally undesired behaviour as I would like the app to close when you hit back on the main activity.
Code on main activity that does this:
@Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
this.finishAffinity();
}
}
There is no onBackPressed method on the fragment
How can I make this so that when you hit back on the fragment the main activity shows but when you hit back on the activity the app closes
A: Use it something like this
for API level 5 and greater
@Override
public void onBackPressed() {
super.onBackPressed()
if (keycode == KeyEvent.KEYCODE_BACK) {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
finish();
}
}
older than API 5
public boolean onKeyDown(int keycode, KeyEvent event) {
if (keycode == KeyEvent.KEYCODE_BACK) {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
finish();
}
}
return super.onKeyDown(keycode, event);
}
Let me know if it works for you
A: Remove this.finishAffinity(); from onBackPressed()
SAMPLE CODE
@Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
finish();
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50872638",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Emacs project management for Scala I would like to ask if any of you have any experience {and,or} could point me to a project management extension for Emacs that works well with {Scala,Ensime,SBT}. It would also be amazing if it didn't require too much hacking. I did some scheme in the past but I have little experience with the Emacs platform.
Basically, by project management I mean mainly the ability to 'tie files into project' and then search among them (and only among them).
Thanks for taking the time to read this and answer!
A:
I really hate that you can't setup projects out of the box, though.
Just set up the project with sbt or maven and import it with ensime.
Essentially, what i would want is to be able to flex-find files in the project
"flex-find" is not English, so I don't really know what you mean. But what is wrong with find (the command line tool)?
A: With ensime you can load your project and then search for a type or method by name. The key sequence is C-c C-v v. This allows you to, for example, jump directly to a class definition.
A: The package projectile has a bunch of generic project-level features, such as running commands in the project root folder, grepping, creating TAGS files etc.
I'm a relatively new user of it, so I can't say exactly how big a difference it makes, but it seems like a worthwhile addition to your tool belt.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7541762",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Microsoft azure cannot access data from sencha 2 mobile application I have configured my Azure back end to only allow actions from authenticated users. I can authenticate my self using my Google account, but after authenticating I still cannot access any data on that table. I have my Ext.azure.Authentication.login('google'); method in a button tap listener and it gets called properly and after that I ask azure if I'm authenticated. I always get authenticated successfully, but still cannot access the data.
Console complains that Azure back end says I'm trying to do unauthorized stuff, even though everything else tells me I'm authorized properly.
A: When using authentication you should remember to add useHeaderAuthentication : true to your proxies to know that they should include authentication data to their headers.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24134291",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Name Broken Horizontal Bar Chart Plotly JS I am trying to create a nice horizontal bar with plotlyjs but the lines name are been broken.
Horizontal Bar Chart Example
The last line is impossible to put a full name. How can i break in 2 lines?
A: Found it!!!
As it is used on Vertical Barchart,
https://plotly.com/javascript/bar-charts/
It can be done on horizontal, also.
What i've done is:
name.replace(" ", "<br>")
HorizontalBar Better
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64164013",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Netbeans - Oracle DB - AWS " amazon RDB " - java 8 I want to connect my java file to amazon oracle database.
DataSource.java
public class DataSource {
private static String dbName = System.getenv("PUBLIC");
private static String userName = System.getenv("root");
private static String password = System.getenv("3deemala7sas");
private static String hostname = System.getenv("oracleinstance.ctnrs4kazdmm.ap-south-1.rds.amazonaws.com");
private static String port = System.getenv("1521");
public static final String JDBC_DRIVER = "oracle.jdbc.OracleDriver";
public static final String DB_URL = "jdbc:oracle:thin://" + hostname + ":" + port + "/" + dbName + "?user=" + userName + "&password=" + password;
public static boolean checkDomain()
{
if (System.getenv("oracleinstance.ctnrs4kazdmm.ap-south-1.rds.amazonaws.com") != null) {
return true;
}
return false;
}
DbConnection.java
public static Connection getConnection( )
{
try {
Class.forName(DataSource.JDBC_DRIVER);
connection = DriverManager.getConnection(DataSource.DB_URL);
//connection = (Connection) DriverManager.getConnection(DataSource.DB_URL);
System.out.println("Connected ....");
return connection;
}
catch (SQLException ex) {
System.out.println("Error syntax");
System.out.println(ex.toString());
ex.printStackTrace();
}catch (ClassNotFoundException ex) {
System.out.println("Class not found error ...");
}
return null;
}
App01.java
public class App01 {
public static void main(String[] args) throws SQLException {
Connection connection = null ;
System.out.println(DataSource.checkDomain());
connection = DbConnection.getConnection();
}}
Exception
java.sql.SQLRecoverableException: IO Error: The Network Adapter could not establish the connection
Note: I have connected successfully using dbvisualizer, also tried to use neatbeas database services and it is not connecting too
Netbeans error : Cannot establish a connection to jdbc:oracle:thin:@oracleinstance.ctnrs4kazdmm.ap-south-1.rds.amazonaws.com:1521:XE using oracle.jdbc.OracleDriver (Listener refused the connection with the following error:
ORA-12505, TNS:listener does not currently know of SID given in connect descriptor
)
A: Thanks for answering my question.
I have figure it out. The mistake was in the URL to connect to db as u mentioned. So, what found is that the url should be like this :-
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@"+hostname+":1521:orcl", "username", "password");
ORCL is the defualt db name for AWS ( AMAZON cloud )
Thanks
A: Based on your error message ORA-12505, TNS:listener does not currently know of SID given in connect descriptor, I think you have an error in your connection string. Specifically, you are likely using the wrong SID.
oracleinstance.ctnrs4kazdmm.ap-south-1.rds.amazonaws.com:1521:XE
Try the following connection string, oracleinstance.ctnrs4kazdmm.ap-south-1.rds.amazonaws.com:1521:orcl. Normally, when you create an Oracle instance in RDS the default SID is orcl.
You can also use the AWS CLI to determine the SID.
$ aws rds describe-db-instances
{
"DBInstances": [
...
{
"DBInstanceStatus": "available",
"DBInstanceIdentifier": "MYORACLEDB",
"MasterUsername": "USERWITHSYSDBA",
"EngineVersion": "11.2.0.4.v1",
...
"Endpoint": {
"Port": 1521,
"Address": "MYORACLEDB.blahblahblach.us-west-2.rds.amazonaws.c om"
},
"PendingModifiedValues": {},
...
"DBName": "ORCL",
...
Where the DBName is the SID (in this case ORCL).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47570926",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Ansible Jinja error while using int|abs {% set shutdown_port = (tomcat_services[current_app_name]["service_port"] +5)|int|abs %}
I am using the above in tomcat contect.xml to get the shutdown port +5 of service port.
when i run the playbook "AttributeError: 'int' object has no attribute 'startswith'"
can some body help me with this error
A: i tried the syntax .... | int | abs on ansible 2.5 and got the same error, while on ansible 2.4 it works.
i think you are affected by this bug
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50068805",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to capture the output of a command without it displaying in stdout How can I capture the output of a command and check for what it says without the command displaying in stdout? For example:
def update!
`git pull origin master`
if $?.exitstatus > 0
puts 'Failed to update'
elsif $?.success?
puts 'Upgraded successfully'
else
puts 'Already up to date'
end
end
How can I capture the output of this in order to check whether the command says up-to date, an error occurs, or successfully updates? Is there a way to write the output to a file instead of to the console?
Update for answer:
def update!
update_status = `git pull origin master 2>&1`
if $?.exitstatus > 0
puts 'error'
elsif update_status =~ /Already up-to date/
puts 'same version as origin master'
else
puts 'updated'
end
end
The output for this will always be:
[06:44:29 INFO] Updating to newest version..
updated
Even if the version is the same as the origin. What I would like to do, if possible, is save the stdout of the command to a file and read from that file to discover if the program was updated or not. I think that would be the easiest way to go about doing this.
A: You can assign the output of the command to a string.
Use 2>&1 to redirect stderr to stdout and thus capture all the output.
str = `git pull origin master 2>&1`
if $?.exitstatus > 0
...
elsif str =~ /up-to-date/
...
else
...
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41274671",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: google.script.run breaks $(document).ready or $(':checkbox').change(evaluateCheckbox); When I run google.script.run.withSuccessHandler(buildCheckboxes).withFailureHandler(fail).getNumber(); it breaks $(document).ready or $(':checkbox').change(evaluateCheckbox); (not sure which is not working). But if I directly access run buildCheckboxes() the $(document).ready & .change continues to work as expected.
$(document).ready(function(){
//buildCheckboxes();
google.script.run.withSuccessHandler(buildCheckboxes).withFailureHandler(fail).getNumber();
$(':checkbox').change(evaluateCheckbox);
});
function buildCheckboxes(num){
if (!num){ var num=3;}
$("#checkboxes").empty();
for (var i=0;i<3;i++){
$("#checkboxes").append('<input type="checkbox" name="cb_'+i+'" value="v2" >Checkbox '+i+'<br><input type="button" id="cb_'+i+'" value="Button"><br>');
$(":button").hide();
}
}
function evaluateCheckbox(){
if (this.checked) {
$("#"+this.name).show();
} else {
$("#"+this.name).hide();
}
}
A: Ok I got it figured out. I had to move $(':checkbox').change(evaluateCheckbox); from the document.ready to the function that gets ran after the script returns from the .cs file.
$(document).ready(function(){
//buildCheckboxes();
google.script.run.withSuccessHandler(buildCheckboxes).withFailureHandler(fail).getNumber();
});
function buildCheckboxes(num){
if (!num){ var num=3;}
$("#checkboxes").empty();
for (var i=0;i<3;i++){
$("#checkboxes").append('<input type="checkbox" name="cb_'+i+'" value="v2" >Checkbox '+i+'<br><input type="button" id="cb_'+i+'" value="Button"><br>');
$(":button").hide();
}
$(':checkbox').change(evaluateCheckbox); //Move this here to make it work.
}
function evaluateCheckbox(){
if (this.checked) {
$("#"+this.name).show();
} else {
$("#"+this.name).hide();
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26879396",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to pass a spread operator to a functions parameter Using spread operator I can get the maximum value of two arrays using Math.max(...firstArr, ...secondArr), and get's the right value, I am trying not to add a spread operator MANUALLY, I am trying to add automatically by creating function, I am trying to add or pass a spread operator before the argument. example
var firstArr = [1,2,3,4,5];
var secondArr = [6,7,8,9];
function myFun() {
for(var i = 0; i <= arguments.length; i++) {
var resl = Math.max(...arguments[i]);
document.write("The maximum value is " + resl);
}
}
myFun(firstArr, secondArr);
It displays two result values:
The first result will be: "The maximum value is 5"
The second result will be: "The maximum value is 9"
It is not comparing two arrays at a time, Please help me. Thanks.
A: You seem to be saying that you want your function to take a variable number of separate arrays as arguments, and then find the maximum number within any of those arrays.
If so, you can say [].concat(...arguments) to create a single new array with all of the values from the individual arrays that were arguments, then use the spread operator to pass that new array to Math.max(). (You don't need a loop.)
var firstArr = [1,2,3,4,5];
var secondArr = [6,7,8,9];
function myFun() {
var resl = Math.max(...[].concat(...arguments));
console.log("The maximum value is " + resl);
}
myFun(firstArr, secondArr);
A: It sounds like what you are trying to do is
function myFun(...arrays) {
const allValues = [].concat(...arrays);
return Math.max(...allValues);
}
console.log("The maximum value is " + myFun([1,2,3,4,5], [6,7,8,9]));
However I would recommend to avoid spread syntax with potentially large data, and go for
function myFun(...arrays) {
return Math.max(...arrays.map(arr => Math.max(...arr)));
}
or even better
function myFun(...arrays) {
return arrays.map(arr => arr.reduce(Math.max)).reduce(Math.max);
}
A: You can use rest element at function declaration, pass an array of arrays each preceded by spread element to function parameters and spread element within function
function myFun(...arr) {
return Math.max.apply(Math, ...arr)
}
myFun([...firstArr, ...secondArr /*, ...nArr*/ ]);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42288098",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to control image size that is in a ASP file? I have this form that works fine, however, in my Logo.aspx file, I have 3 logos on the head of the form.
However, the Logos in the asp file pushes the third image to the right.
Is their a way to control the size of the logos in the front end?
This issue only occurs in IE10. But all other version of IE and Chrome, it works fine
Below is what I have tried and it does not work:
<table style="width: 100%">
<tbody>
<tr>
<td align="left" width="10%"><!-- #INCLUDE FILE="scripts\Logo2_C.aspx" --></td>
<td align="right" width="90%"><img src="/images/logos/logo.png" /></td></tr></tbody>
A: you can use 'inline-block' instead of a table:
<div style="display:inline-block;width:10%;"><!-- #INCLUDE FILE="scripts\Logo2_C.aspx" --></div>
<div style="display:inline-block;width:90%;"><img src="/images/logos/logo.png" /></div>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39301537",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is there any way query the node's status before submitting one job? Before submitting one job, could I query one node's status, if the node is free, then submit it into the node; if not ,then submit the job into another free node.
I want the job to run on the total node, not sharing with other jobs. Is there any way?
A: Since you've tagged this sungridengine I'll assume that's what you are using. Explicitly requesting by name a node that is currently empty doesn't guarantee that nobody will submit a job later that will be assigned to the same host.
To achieve this the admin needs to create an exclusive resource and associate it with each execution host. You can then request said resource to get the whole node.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19603754",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Invalid Bundle - Invalid Asset Catalog. One of the files named Assets.car is not a valid Asset Catalog file I have build a react-native app which I want to submit to Testflight.
I have tried a lot but keep getting this message:
Invalid Bundle - Invalid Asset Catalog. One of the files named Assets.car is not a valid Asset Catalog file.
It's very vague I don't know how to fix this.
Im running Xcode 8.3.3 (8E3004b) and macOS Sierra 10.12.6 (16G29).
Full message from Apple after submitting to the App store.
Dear developer,
We have discovered one or more issues with your recent delivery for "Time". To process your delivery, the following issues must be corrected:
Invalid Bundle - Invalid Asset Catalog. One of the files named Assets.car is not a valid Asset Catalog file
Once these issues have been corrected, you can then redeliver the corrected binary.
Regards,
The App Store team
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45820323",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Whats the difference between Cookie SESSION= and session_id in database for spring session I am using spring session with JDBC postgres for session management. Whenever a new session gets created spring creates it and send the sessionid back to the browser in the cookie parameter SESSION and browser sends it back for every subsequent requests and things work fine. But the value in session_id in the postgres table spring_session is different form the SESSION sent back initially in cookie. Is this the expected behavior ?
A: Yes, this is expected.
Starting with Spring Session 2.0, DefaultCookieSerializer uses Base64 encoding by default. So what you're actually seeing as session cookie value is the Base64 encoded session id.
If you wish to restore the previous (Spring Session 1.x) default, you can explicitly configure DefaultCookieSerializer bean with useBase64Encoding property set to false.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51517246",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to get the value of a CSS property in SASS? I'd like to store the current value of a property for later use. It's already been solved for jQuery.
The issue is that I'm using a @mixin to apply a CSS hack in several places (Justified Block List) and I'd like to restore the font-size property in .block-list * (currently all text in sub-elements is just collapsed).
Unsatisfactory workarounds:
*
*Save the global default font size in a separate file and pass it to the @mixin on @import. This is of course in the general case not the same font size as the objects which the mixin is applied to.
*Save the font size whenever you change it, and pass that. This tangles up the files involved, since it's not very elegant to @include the typography stylesheet in several otherwise unrelated files.
*Use more jQuery.
Possibly satisfactory workarounds:
*
*Override the font size with a stronger rule on the first ancestor which changes it. This could be tricky to determine.
A: If you have a mixin which is doing something "hacky" with the font size, then you will probably need to reset the font size as you have noticed. I suggest the following:
*
*Create a Sass partial to record your projects config variables. I suggest _config.sass.
*Define your base font-size in _config.sass:
$base-font-size: 16px
*Add @import _config.sass at the top of your main sass file(s).
*Update the mixin to reset the font-size to your $base-font-size:
@mixin foo
nav
font-size: 0 // this is the hacky part
> li
font-size: $base-font-size // reset font-size
Note: If you are using the SCSS syntax, you'll need to update the examples here.
A: There's no way to tell the computed value of a property until the styles are actually applied to a document (that's what jQuery examines). In the stylesheet languages, there's no "current" value except the initial value or the value you specify.
Save the font size whenever you change it, and pass that seems best, and @BeauSmith has given a good example. This variant lets you pass a size or fallback to a defined global:
=block-list($font-size: $base-font-size)
font-size: 0
> li
font-size: $font-size
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9394514",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: Compare Javascript Ajax Response with String I'm trying to compare the result from from ajax call with a string. My result is returning the correct result but i can't get the if statement to compare this with my string, any ideas?
$.ajax({
type: "POST",
url: "sessionCheck.php",
data: {id:mwdata},
success: function(html) {
if (html == "open"){
alert ("yes it's open");
}else if(html == "closed"){
alert ("no it's closed");
}
}
});
A: So the answer was to trim the result var result = $.trim(html);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54291662",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Regex to get a word in a pattern I don't know how best to word this. I have a set of patterns:
Usa-Texas
Usa-Chicago
USa-Washinton
.
.
Usa-{some USA state}
Now, I need a regex(java) to extract only the USA. I am just wondering why this didn't work : "(//busa//b)" It wasn't extracting the USA..
A: use this to fix the problem.
Pattern p = Pattern.compile("\\bthis\\b");
Matcher m = p.matcher("Print this");
m.find();
System.out.println(m.group());
Output:
this
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33766354",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Importing a joomla plugin I have trouble importing my own plugin. I have tried numerous methods (e.g. JLoader and differnt variations of names to be imported), all of them failed.
This is the plugin's php content:
http://pastebin.com/mw7p52pV
This is its XML definition:
http://pastebin.com/mzcB0ejp
This is how I call it:
$res = JPluginHelper::importPlugin('Mycategory');
var_dump($res);
$results = $dispatcher->trigger( 'testMaxSizer', '');
var_dump($results);
Both var_dumps return either NULL or false.
What am I doing wrong?
A: There's nothing wrong with your code, so be sure you have properly installed the plugin and enabled it, else the trigger won't work
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23181408",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Python PEP 302 and __name__ attribute Currently i am creating a custom import hook, which seems to work pretty well (still under development). When i read the PEP 302 i came accross the __name__ attribute, which is descriped like this:
The __name__ attribute must be set. If one uses imp.new_module() then the attribute is set automatically.
But i don't get, whether name should contains the full path of the module/package or just it's name. For example when executing import A.B should __name__ only contains B or the full path A.B?
Thank you very much!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34949477",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: jQuery UI & document.ready in Chrome I have a very large and complex jQuery UI application that is designed to work with Chrome (the other browsers do not matter at this stage). I have noted the following
*
*The time required to process all of my customization code under $(document).ready is less than 2s.
*Once doc.ready has been executed the document should be ready for use right? Not what I observe. The Chrome tab containing the application continues to show the spinning "doc loading" animation for a good 7s after doc.ready has finished execution. For good measure I exited doc.ready without doing any application customization. It made no difference - the 7s spin stays put. In the mean time the application is completely unresponsive.
I'd be much obliged to anybody who could shed some light on what is going on under the covers that stops the application from being ready. The script base for the application is large - is the delay I am experiencing down to the time that Chrome/V8 requires to compile the script?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22472906",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Does Encrypted data contain White spaces? When we encrypt any Magnetic strip data. Does that encrypted data contain spaces?
I am referring to this document http://sagan.gae.ucm.es/~padilla/extrawork/magexam1.html
Where the card data converts into SHINTRACK1, SHINTRACK2, TRACK1 and TRACK2.
So similarly card photo will also get encrypted.
Just want to know if the encrypted data contains any white spaces.
Any supporting documents will be more helpful
A: The result of the most common encryption algorithms (i.e. AES and RSA) are seemingly random binary values. It means that there is a 50% chance that a single bit is either 0 or 1. This is true for all bits of the ciphertext. 8 bits usually make up a byte.
Binary data cannot be represented as text by default, but you can still open the ciphertext in a text editor which might handle it as ASCII and see that some bytes are not printed. Others might be printed and there might even be characters in there that classify as whitespace.
A: Your link doesn't match your question. Your link references specifically magnetic stripe data. Magnetic stripes can encode any 7-bit ASCII, which includes whitespace (and explicitly does, for example, for the cardholder's name). The encrypted format does not, because it is hex-encoded, so each character will be '0'-'F'. But the byte 0x20 (SPACE) can certainly exist in encrypted data. It probably won't, since the kind of data that's encrypted on magnetic stripes typically does not include spaces, but it certainly can.
But all of this is pointing to a fundamental problem. If you care about whitespace, you are mishandling the data. You need to follow the spec closely when decoding a magnetic stripe, and if you're worrying about whitespace, you're on the wrong road. The link you gave includes some of the ISO standards involved. What precise encoding is performed depends on which track you're reading, and thus which standard applies.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63811112",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Best way to trigger a Page activation workflow I have a requirement where I have around 800 pages under a path in /content hierarchy. Now, the content in some of those pages will get updated on a nightly basis though some automated process. I have a requirement to trigger a page activation workflow for all the pages that are updated. This has to happen instantaneously after the page content got updated. I actually thought of writing a custom code to manually call the page activation workflow once a page is updated. But, on reading some documentation, I thought a workflow launcher might be more suitable in this scenario.
However, I have some queries related to workflow Launcher:
*
*Does it activate all the pages under the path that I mention in the path property while setting up the launcher or will it activate only those pages which are modified?
*I we are logged in as admin, do we get a notification in the inbox for approval of this workflow?
Also, I wanted to know whether using the workflow launcher in this scenario is the best solution for my requirement. I'm relatively new to Workflows, so please help
A: I actually implemented this requirement with the help of a launcher. The below were the settings that I have done. Its activates only those pages which are modified under the mentioned path.
A: *
*You can define the workflow launcher to listen to a specific property. So if your nightly update updates a specific property, the easiest is to have a launcher that checks for modification of this property:
http://docs.adobe.com/docs/en/cq/current/workflows/wf-using.html#Starting Workflows When Nodes Change
*Usually you should only log in as admin if you need to access system settings (/system/console) and not for daily work. I suggest you create an administrator user which is part of the group that would get the workflow notification. You can give this user full access to the CRX, but still I would really check if this is needed for daily tasks.
A: Depending on your concrete requirements, if you want to activate the pages without starting a workflow first you can make use of the com.day.cq.replication package. If you obtain a reference to a Replicator object you can trigger replication of a node simply via a call to the replicate method.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28020082",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: money.js convert currency from one value to other and backwards I have to input field one with $ and other with ¥, what I'm trying to achieve is: when input number in $ it will show how much it will be in ¥ and when input in ¥ it will show in $
Html:
<div class="input-group">
<input id="bid_jpy" class="form-control" type="text" name="user_bid" placeholder="Your bid in JPY ¥">
<hr>
<input id="bid_nzd" class="form-control input-sm" type="text" name="user_bid" placeholder="Your bid in NZD $">
</div>
And JS:
$(document).ready(function(){
fx.base = "JPY";
fx.settings = {
from : "NZD"
};
$.getJSON(
'http://api.fixer.io/latest',
function(data) {
// Check money.js has finished loading:
if ( typeof fx !== "undefined" && fx.rates ) {
fx.rates = data.rates;
fx.base = data.base;
} else {
// If not, apply to fxSetup global:
var fxSetup = {
rates : data.rates,
base : data.base
}
}
$('#bid_nzd').keyup(function(){
var jpy = fx.convert(this.value, {to: "JPY"});
$('#bid_jpy').val(accounting.formatNumber(jpy, {
precision : 0,
thousand : ""
}));
});
$('#bid_jpy').keyup(function(){
var nzd = fx.convert(this.value, {to: "NZD"});
$('#bid_nzd').val(accounting.formatNumber(nzd, {
precision : 0,
thousand : ""
}));
});
}
);
});
It works fine when I input $ and it shows the correct amount in ¥ but when I type ¥ in $ it will not convert anything.
I read documents and tried to create two different files but didn't hellped
A: This is frequently a problem with beginners when they fail to validate the JS written. Whatever editor you use, try using a JS validator to validate whether JS has been written correctly.
In this case, I believe you forgot to use a bracket after completing your getJSON function.
$.getJSON(
'http://api.fixer.io/latest',
function(data) {
// Check money.js has finished loading:
if ( typeof fx !== "undefined" && fx.rates ) {
fx.rates = data.rates;
fx.base = data.base;
} else {
// If not, apply to fxSetup global:
var fxSetup = {
rates : data.rates,
base : data.base
}
}
); //This bracket is missing in your code
For JS validation, use http://www.jslint.com/
A: I finally find the answer and it was very simple:
I didn't specify what currency I wanted to convert in NZD:
$('#bid_jpy').keyup(function(){
var nzd = fx.convert(this.value, {from: "JPY", to: "NZD"});
$('#bid_nzd').val(accounting.formatNumber(nzd, {
precision : 0,
thousand : ""
}));
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46677055",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Can`t remove a new line I have a model, wich has a unique token, to be changed every time the model is saved.
i`m using before_filter to change the token, and it is working, the problem is:
class Confirmation < ActiveRecord::Base
attr_accessible :item_id, :item_type
before_save :define_token
def to_param
token
end
private
def define_token
str = ActiveSupport::SecureRandom.base64(32).gsub("/","_").gsub(/=+$/,"")
self.token = Util.secure_hash("#{str} - #{Time.now.utc.to_s} - #{item_id}")
end
end
when i look the token generated it gives me a random string with a \n at the end.
i`ve tried to add this line:
def define_token
str = ActiveSupport::SecureRandom.base64(32).gsub("/","_").gsub(/=+$/,"")
str = Util.secure_hash("#{str} - #{Time.now.utc.to_s} - #{item_id}")
self.token = str.gsub("\n", "n")
end
but still don`t work, how can i remove the new line at the end?
A: Firstly, assuming the newline is 100% spurious, I would figure out where it is coming from, and remove it there. But if for some reason that's not an option, the following gsub would work:
self.token = str.gsub(/\n$/, "")
That will only remove a newline if it's the last entry in the string. To remove all newlines, use:
self.token = str.gsub(/\n/, "")
Even easier, the rstrip method will remove trailing whitespace from a string:
self.token = str.rstrip
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7166183",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: bind together sparse model matrices by row names I am trying to construct a large sparse matrix with a split-apply-combine approach by separately calling sparse.model.matrix() from the package Matrix on subsets of columns of a dataframe and then binding them together into a full matrix. I have to do this because of memory limitations (I can't call sparse.model.matrix on the whole df at once). This process works fine, and I get a list of sparse matrices, but these have different dimensions and when I try to bind them together, I can't.
ex:
data(iris)
set.seed(100)
iris$v6 <- sample(c("a","b","c",NA), 150, replace=TRUE)
iris$v7 <- sample(c("x","y",NA), 150, replace = TRUE)
sparse_m1 <- sparse.model.matrix(~., iris[,1:5])
sparse_m2 <- sparse.model.matrix(~.-1, iris[, 6:7])
dim(sparse_m1)
[1] 150 7
dim(sparse_m2)
[1] 71 4
cbind2(sparse_m1, sparse_m2)
Error: Matrices must have same number of rows in cbind2(sparse_m1, sparse_m2)
cbind(sparse_m1, sparse_m2)
Error: Matrices must have same number of rows in cbind2(..1, r)
The matrices have the same row names, just some rows have been omitted from sparse_m2 because they had missing values in both columns. Is there any way to combine them?
I also tried using rbind.fill.matrix() from the plyr package, by first transposing and then calling it and then re-transposing, but then I lose column names since row names are ignored in rbind.fill.matrix.
Any ideas?
A: An old question still in need of an answer...
One approach is to create an empty Matrix of the required dimensions and then populate it:
m12.dimnames<-list(union(rownames(sparse_m1),rownames(sparse_m2)),c(colnames(sparse_m1),colnames(sparse_m2)))
m12<- Matrix(0,nrow=length(m12.dimnames[[1]]),ncol=length(m12.dimnames[[2]]),dimnames=m12.dimnames)
m12[rownames(sparse_m2),colnames(sparse_m2)]<-sparse_m1
m12[rownames(sparse_m2),colnames(sparse_m2)]<-sparse_m2
A: recently bumped in the same issue, and nowadays you can
install.packages("Matrix.utils")
library(Matrix.utils)
sparse_filled <- rBind.fill(sparse_m1, sparse_m2)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33205666",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: OGRFeature setting multiple fields Hi all to start off with:
Using Gdal compiled with Xerces
Coding in C++ with the QT Creator version 5.4.1
So my problem is im trying to use Gdal to create my own Esri shapefile, I get a strange runtime error when trying to add multiple fields
Example:
// Create a ogr feeature
OGRFeature* ogr_feature;
// Set a bunch of fields
ogr_feature->SetField("Blah","Blah");
ogr_feature->SetField("Foo","Foo");
ogr_feature->SetField("Bar","Bar");
ogr_feature->SetField("Test","Test");
When I run the program once it hits this part it gives out this error message:
Error :1 Invalid Index -1
I'm not too sure what's causing this. I've tried taking out all but 1 and thats fine doesnt give me any errors. But more than 1 it throws that error.
Anyone know how to fix this/ why its doing it?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31320656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Hashing function and keys While going through Kathy Sierra's book I stumbled across this code fragment:
m.put("k1", new Dog("aiko")); // add some key/value pairs
m.put("k2", Pets.DOG);
m.put(Pets.CAT, "CAT key");
Dog d1 = new Dog("clover");
m.put(d1, "Dog key");
m.put(new Cat(), "Cat key");
Maps are used to store stuff in the keys and values format. Would someone tell me what is actually stored in key when we enter "k1" or new Cat() as a key? Are references to these objects are stored or the value of hashcode? I am totally confused with this. Please advice.
And it would be appreciated if you could point me towards further reading material.
A: The map is an array of N buckets.
The put() method starts by calling hashCode() on your key. From this hash code, it uses a modulo to get the index of the bucket in the map.
Then, it iterates through the entries stored in the linked list associated with the found bucket, and compares each entry key with your key, using the equals() method.
If one entry has a key equal to your key, its value is replaced by the new value. Else, a new entry is created with the new key and the new value, and stored in the linked list associated with the bucket.
Since Cat instances and String instances are never equal, a value associated with a String key will never be modified by putting a value associated with a Cat key.
A: It will be defined by your object.
You have to create a hashCode() and a equals() method so it can be stored in your hashtable.
As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)
See the javadoc at java.lang.Object http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Object.html#hashCode()
or you can read this for an explanation
http://www.javaworld.com/javaworld/javaqa/2002-06/01-qa-0621-hashtable.html
I hope it helps
A: Storing the value to HashMap depends on the hashcode() and equals() method.Please find the more reference from here.
HashMap - hashcode() Example
More information of HashMap get() retrieval of values.Here
A: When a HashMap is used, the keys in it are unique. This uniqueness of the keys is checked in Java from the definition of the equals() and hashCode() methods that the class of the objects under consideration provides.
This is done by comparing using the equals() method first and if it returns equal then comparing using hashCode().Also, you must be knowing that each reference pointing to an object has a bit pattern which may be different for multiple references referring to the same object.
Hence, once the equals() test passes, the object won't be inserted into the map since the map should have unique keys. So, each hashCode value for objects which are keys in the map will form different buckets for a range of hashCode values and the object will be grouped accordingly.
EDIT to provide an example:
For example, let us consider that two objects have a String attribute with values "hello" and "hlleo" and suppose the hashCode() function is programmed such that the hash code of an object is the sum of the ASCII values of the characters in the String attribute and the equals() method returns true if the values of the String attribute are equal.
So, in the above case, equals() return false as the strings are not equal but the hashCode will be same. So the two objects will be placed in the same hash code bucket.
Hope that helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10189326",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: implementing time based queue for hashmap I am working on an application where i need to have a fixed length for a HashMap. Initially the hashmap was restricted based on size so i used removeEldestEntry method of LinkedHashMap to achieve that.
Code:
public class FixedLengthHashMap<K,V> extends LinkedHashMap<K,V> {
long max_length;
public FixedLengthHashMap(long max_length){
this.max_length = max_length;
}
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return this.size() > max_length;
}
}
But now I need to store entries on that HashMap based on time. Example if hashmap size is two weeks, the hashmap should have entries inserted for first 14 days and when a new entry is being inserted on 15th day, it should remove entries of 1st day. And on 16th day, all entries of 2nd say should be deleted and so on.
I tried removeEldestEntry method again like below:
public class FixedTimeHashMap<K,V> extends LinkedHashMap<K,V> {
LocalDateTime start;
public FixedTimeHashMap(){
this.start = LocalDateTime.now();
}
protected boolean removeEldestEntry(Map.Entry<K, V> eldest)
{
LocalDateTime current= LocalDateTime.now();
Long diff = ChronoUnit.SECONDS.between(start, current);
if(diff>60*60*24*14)
return true;
else
return false;
}
}
But this will only delete one entry for each insertion after the 14th day. I have to delete all entries of 1st day when new entry is inserted on the 15th day.
If you can give some advice or suggestions it will be very helpful. Thanks in advance.
A: A LinkedHashMap would be a nice starting point, as it maintains the order of insertion. The value needs to have a date, so maybe wrap the original value in some class with a date, or require an interface.
static class Dated<V> {
public final LocalDate date = LocalDate.now();
public final V value;
public Dated(V value) {
this.value = value;
}
}
Map<K, Dated<V>> map = new LinkedHashMap<>();
void insert(K key, V value) {
Dated<V> datedValue = new Dated<>(value);
LocalDate earliest = datedValue.date.minusDays(14);
Iterator<Map.Entry<K, Dated<V>> it = map.entries().iterator();
while (it.hasNext() && it.next().getValue().date.isBefore(earliest)) {
it.remove();
}
map.remove(key); // So at the end of the linked list.
map.put(key, datedValue);
}
The remove ensures that the latest addition is added at the end of the linked list, even if the key already existed.
Hence the iteration starts with the oldest elements, and deletes those.
Note: The question asked for a removeEldestOnes, based on the current time. That means when nothing is inserted, one could still remove old entries of more than 14 days in the past.
My code could be used for that too, but first doing map.remove on insert is essential, hence the integrated insert.
Making a custom collection class I leave to the OP.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50690691",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Regular Expression for Job Status (Autosys) I have an output like below:
Name1 12/26/2013 12:05:04 12/26/2013 12:05:08 SU 34066553/1 0
Name2 12/26/2013 12:05:10 12/26/2013 12:05:14 SU 34066553/1 0
Name3 12/26/2013 12:05:04 12/26/2013 12:11:13 FA 34066553/1 5
Name4 ----- 12/26/2013 11:06:06 AC 34066553/0
then I need to parse a status (i.e SU, FA, AC and so on).
Below fragment shows only first record.
\b[A-Z]{2}\b
How can I get all inputs here to check and validate it. I'm using http://gskinner.com/RegExr/
Thanks.
A: I think it will work
try this :
\b([A-Z]){2}
result
SU, SU, FA, AC
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20855852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Objective-C / Xcode project : Where to put structs? I always try to keep my Xcode projects very well organized but I recently asked myself where to put struct data types.
Normal I use a lot of classes even when a struct would do. Since classes are always separate files there are much easier to organize and easier to find.
Where do you put your structs?
A: I try to follow the patterns employed by the system as much as possible. In particular, look to the definitions of NSRect, NSPoint, and other structures.
In other words, group together structures that are related into a single header file. For many projects, that would lead to exactly one header full of structure declarations.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1782430",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can I schedule my computer to shutdown at a certain time? I run a program which has a lot of computation that takes a lot of time for outputs. I thought that it might be a good idea if I could turn off the PC after the output has been received. so I used the code below (which works fine by the way):
def shutdown():
import os
os.system("shutdown /s /t 90")
if __name__ == "__main__":
main()
shutdown()
But now I have another program (IDM) running simultaneously which works from 2 AM until 7 AM.
My question is that how can I design a simple program that shut down the PC only if the PC time has passed over 7 AM.
Can anyone help me with that ?
A: You can check the current time, and loop until it passes the specified hour before shutting down, e.g.:
import os
import time
def shutdown(threshold=7):
while time.gmtime().tm_hour < threshold:
time.sleep(300) # wait 5 minutes
os.system("shutdown /s /t 90")
and call it as you call it now.
The threshold sets the hour after which to proceed with the shutdown, by default its set to 7. Keep in mind, tho, that it uses your system clock (most probably UTC) so you have to account for the difference when specifying your threshold.
Of course, if you don't want to shutdown the system at all, even when the time passes, if the script was called before the threshold, you can use:
def shutdown(threshold=7):
if time.gmtime().tm_hour >= threshold:
os.system("shutdown /s /t 90")
instead.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44077422",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why "**" does not bind more tightly than negation in OCaml? after this question, I don't know what to think.
In OCaml, if you do something like -1.0**2.0 (because of the typing you need to have float), you obtain 1.00. According to the standard order of operations, the result should be -1 (as in python).
I wasn't able to find the reason or a clear definition of the operator precedence in OCaml...
Is this because of the type system ? or the fact that there's a binding underneath with pow ?
A: As the very page you quote says, "The order in which the unary operator − (usually read "minus") acts is often problematical." -- it quotes Excel and bc as having the same priority for it as O'CAML, but also says "In written or printed mathematics" it works as in Python. So, essentially, there's no universal consensus on this specific issue.
A: Operator precedence is syntax-directed in OCaml, which means that the first character of the function identifier (and whether it's unary or binary) determines the operator precedence according to a fixed sequence. Contrast this with languages like Haskell, where the operator precedence can be specified at function definition regardless of which characters are used to form the function identifier.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/937497",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Checking if a string begins with integer after line breaks I'm using Apache POI to read in from a .doc file, as a result, I have an arraylist of strings containing large amounts of line breaks, and tabs, from the original document formatting
I need to check if a string, from this, contains an integer as it's first character. However strings often come out like the following:
Now the first string, at location [3] is fine, even though it contains an integer later on, however the string at position [4] which starts with \n\r\n5.2
and therefore starts with an integer, is not acceptable and should be disregarded.
However, I cannot seem to find a way of checking if one of these strings starts with an integer. I have attempted to replace all \n and \r within the strings using java's
theString.replaceAll("\\\\n","");
theString.replaceAll("\\\\r","");
Yet this seemed to fail, I've attempted to use regex to determine using a substring if the string itself begins with an integer to no avail, as the number of tabs and line breaks varies.
Does anyone have a why by which I can determine if the string (after all line breaks and tabs) begins with an integer?
Second Example:
Code in use :
tempLineBreakRemoval = listoflines.get(x);
tempLineBreakRemoval = tempLineBreakRemoval.replaceAll("\\\n", "");
//Selection Statement to only add to "tempCommentString" if does not start with integer
tempCommentString += listoflines.get(x);
x++;
A: For once the \\\\n is \\n after resolving the special characters. Therefore you have to use \\n if you want it to be \n which would be the character \ and the letter n. This would be correct for replaceAll. For replace which takes a character you would even have to use '\n' directly. Same for \rand \t.
However i would prefer a single regex for this. This call should do it: theString.matches("\\s*\\d.*");. \s stands for any whitespace character \d for any digit and . for any other trailing character.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30288192",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to get event of changing current keyboard layout in Unix? I searched simple solution, but could not find.
I need getting event of changing system keyboard layout for setting this in my application.
QApplication::keyboardInputLocale() is not suitable, because I need to catch system layout, not the application.
Xkblib also is not suitable, because I use Qt project and this library can lead to crashes (QEvent, QTimer).
A: X sends a MapNotifyEvent (not to be confused with KeymapNotify) when the key mapping is changed (tested with xmodmap, but should work for other methods as well). I don't know if you can get at raw X events under Qt, but if you can, I think that's the event to look for.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7978891",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Error "No overload for method 'EndExecuteNonQuery' takes 0 arguments" While executing the following code :
private void button1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(global::DataBase.Properties.Settings.Default.Database1ConnectionString);
try
{
string sql = "INSERT INTO student (stdid,stdname) values("+tid.Text+",N'"+tname.Text+"')";
SqlCommand exeSql=new SqlCommand(sql,cn);
cn.Open();
exeSql.EndExecuteNonQuery(); // <-- Error occurs here
MessageBox.Show("Add new Record Done||","Message",MessageBoxButtons.OK,MessageBoxIcon.Information);
this.studentTableAdapter.Fill(this.database1DataSet.student);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message,"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
finally
{
cn.Close();
}
}
private void button2_Click(object sender, EventArgs e)
{
this.studentTableAdapter.Fill(this.database1DataSet.student);
}
}}
I got a "No overload for method 'EndExecuteNonQuery' takes 0 arguments" error.
How can I fix this error ?
A: Try using ExecuteNonQuery() instead.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29428992",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can not load GIF from GeoNames link with Glide 1 GeoNames
Glide.with(this)
.load("https://www.geonames.org/flags/x/ad.gif")
.into(imageViewFlag_info);
2 Giphy
Glide.with(this)
.load("https://media.giphy.com/media/98uBZTzlXMhkk/giphy.gif")
.into(imageViewFlag_info);
1 and 2 are different
2nd example works with Giphy but Glide can't load image from GeoNames link.
A: Specify an appropriate User-Agent by using GlideUrl:
GlideUrl glideUrl = new GlideUrl("https://www.geonames.org/flags/x/ad.gif", new LazyHeaders.Builder()
.addHeader("User-Agent", "Mozilla/5.0")
.build());
Glide.with(this)
.load(glideUrl)
.into(imageViewFlag_info);
A: Try this tutorial to setup GlideApp: https://futurestud.io/tutorials/glide-getting-started
Then write this line of code and it should work on your use case
GlideApp.with(imageView).asGif().load("URL").into(imageView);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67046584",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can I print unsigned char as ascii I'm trying to convert unsigned char to ascii text. How can I do it?
I have tried this, but it is wrong:
typedef struct mtmheader
{
unsigned char objName[20];
unsigned char msgType[2];
}mtmheader;
mtmheader h;
processMTMHeader(datap,&h, endmmsgp );
printf("Name, type: %s %c\n",(char *) &h.objName,(char *) &h.msgType);
EDIT
I read stream of unsigned bytes and want to know what how can i print is as ascii text. In printf is only pseudo code, which is wrong.
A: printf("Name, type: %s %c\n", h.objName, h.msgType[0]);
should print the whole string objName and the first character from msgType.
For the first to work you'd have to be sure that objName is really null terminated.
Also unsigned char is not the correct type to use for strings use plain char without unsigned.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21675497",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Setting permissions of uploaded file to allow reading in ASP.NET I have an ASP.NET web application in which I am trying to open a text file located within a subdirectory of my webroot. The text file was uploaded through the same web application using SAFileUp. I am using the FileInfo object as such to read the text file ...
Response.TransmitFile(fileInfo.FullName)
The puzzling thing is I get an exception thrown when I execute this line of code.
Access to the path 'C:\webroot\xxxx\uploads\filename.txt' is denied
I have given the uploads folder, where the text file was uploaded, read/write/execute permissions to both the IUSR and IIS_IUSRS account and the permissions have inherited to the sub folders below. The interesting thing is the actual text document I am trying to load has NO permissions set for IIS_IUSRS while IUSR does have read/write/execute. As soon as I add the "read" permission to IIS_IUSRS I am able to read the file.
What confuses me is I would have thought the file would have inherited the permissions from the parent folders, but apparently not. How do I set the permissions of the uploaded file during the upload process so I can open it later for reading?
A: Well .. I found the answer. Basically, the upload component SAFileUp, uses the "Temp" directory where the uploaded file is cached to set the permissions of the uploaded file. In my case this directory was C:\Windows\temp. All I did was give the account IIS_IUSRS READ access to the C:\Windows\temp directory and I was able to access the uploaded file without issue.
Here is an article on SoftArtisans's website that clued me in and helped me find the directory the uploaded file was cached to.
http://support.softartisans.com/kbview_776.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5709184",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: promisePool is ignoring concurrency limit and running all promises at once all.
I am trying to implement a PromisePool from es6-promise-pool
. However, when I run my code, all of the promises are executing at once instead of obeying the concurrency limit.
relevent code:
// individual promise
var writeGpsProjection = function(sensor, i){
return new Promise(function(resolve, reject){
lgmsg = "running: sensor: " + sensor + " iterator: " + i
console.log(lgmsg)
setTimeout(function () {
resolvMsg = "done: sensor: " + sensor + " iterator: " + i
console.log(resolvMsg);
resolve(resolvMsg);
}, 2000)
})
}
// promise producer
var collectForThread = function () {
var sensorKeys = Object.keys(sensorUpdates);
i = 0;
sensorKeys.forEach(function(sensor){
if (i < sensorKeys.length){
i++;
command = writeGpsProjection(sensor, i)
return command
} else {
return null;
}
});
}
concurrency = 3
async function gpsEngine(){
while (true) {
console.log(" ------ Running Thread ------ " +
Object.keys(sensorUpdates).length + " sensors to process:");
var pool = new PromisePool(collectForThread, concurrency);
pool.start()
.then(function () {
console.log('Complete')
})
.then(function () {
console.log('All promises fulfilled')
}, function (error) {
console.log('Some promise rejected: ' + error.message)
})
await timeMachines.sleep(8);
}
}
gpsEngine();
If there is a more simple solution, I would love to hear that also. My objective is, given a list of objects, run a process on each but limit the number running consecutively to a certain number because the real process will involve pulling records from a database, and various other resource intensive jobs. I am afraid that if I try to do all of them at once async-wise, it will lock me up. The while loop is because this is a process that will need to periodically run to process data in our lab server.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52545491",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Android WebView doesn't show unity builded web pages properly I have developed an application in unity then I export it to WebGl then I have created a web page. When I preview the page on Android's Chrome browser there is no any problem, It shows the page in high quality however when I open the page in android WebView quality of graphics dramatically decreases. I have tested the same application on Android 7,8 and 9 but there is no difference between versions. I have tried hardwareAccelerated but the problem is already present. Is it possible to get same quality in WebView like it is in Chrome?
A: You can give a try to Chrome custom tabs. They are far more performant than a webview and they give to users a seamless in-app user experience.
Unfortunately webview lacks a lot of features of the common browsers and it's not the best choice to display complex web pages.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57974095",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Bitwise operation positive number to negative Performance and optimisation debates aside.
I'm looking for a way in Javascript to take a number let it be 5 and using bitwise operations change it to -5.
The problem with flipping the bits is that 0 becomes 1 ergo ~5 becomes -6.
Is there a way to do this purely through bitwise ops? I feel that adding the 1 back on would negate the minor improvement that I may or may not gain.
A: The negative number as an integer is the two's complement. To flip the sign using two's complement you do like this:
"To get the two's complement of a binary number, the bits are
inverted, or "flipped", by using the bitwise NOT operation; the value
of 1 is then added to the resulting value, ignoring the overflow which
occurs when taking the two's complement of 0."
In JavaScript that would be:
n = ~n + 1;
If you are looking for performance, that is not likely to be the fastest way. That would most likely be to use the operator specifically designed for that:
n = -n;
A: It's not soo much faster. It does not make sense. When you need to negate the number noone can do it better than your CPU. http://jsperf.com/minus-vs-not
A: In case anyone is wondering how you would go back and forth between a negative & positive number (n) without using the + or - signs ...
n = ~n
add = 1
while add:
diff = add^n
carry = (add&n)<<1
add = carry
n = diff
print(n)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32379524",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I make UIAlertController appear over the top of anything and everything? I am developing an app using Visual Studio 2022 that uses ZXing.Net.Mobile,Forms to scan barcodes, everything is working as expected except I am unable to display the UIAlertController message over the top of everything. My code is:
btnScan.TouchUpInside += (object sender, EventArgs e) =>
{
// First we must get permission to use the camera
AVAuthorizationStatus authStatus = AVCaptureDevice.GetAuthorizationStatus(AVAuthorizationMediaType.Video);
if (authStatus == AVAuthorizationStatus.Authorized)
{
scan();
}
else if (authStatus == AVAuthorizationStatus.NotDetermined)
{
Utils.ShowMessage(this,"Camera access not determined. Ask for permission.", "Error");
AVCaptureDevice.RequestAccessForMediaType(AVAuthorizationMediaType.Video, (granted) =>
{
if (granted)
{
scan();
}
else
{
camDenied();
}
});
}
else if (authStatus == AVAuthorizationStatus.Restricted)
{
Utils.ShowMessage(this, "This device doesn't have the camera feature", "Error");
}
else
{
// Denied
camDenied();
}
};
}
void HandleScanResult(ZXing.Result result)
{
var msg = "";
if (result != null && !string.IsNullOrEmpty(result.Text))
msg = "Found Barcode: " + result.Text;
else
msg = "Scanning Canceled!";
// I need this alert to appear over the top of everything
InvokeOnMainThread(() =>
{
Utils.ShowMessage(this, msg, "Scan Success");
});
}
void camDenied()
{
UIAlertController alert = UIAlertController.Create("Warning", "It looks like your privacy settings are preventing us from accessing your camera. You can fix this by doing the following...", UIAlertControllerStyle.Alert);
UIAlertAction goAction = UIAlertAction.Create("Go", UIAlertActionStyle.Default, (action) =>
{
// Open Settings
UIApplication.SharedApplication.OpenUrl(new NSUrl(UIApplication.OpenSettingsUrlString));
});
alert.AddAction(goAction);
PresentViewController(alert, true, null);
}
void scan ()
{
InvokeOnMainThread(() => {
scanner = new MobileBarcodeScanner(this.NavigationController);
scanner.UseCustomOverlay = false;
var opt = new MobileBarcodeScanningOptions() { DelayBetweenContinuousScans = 3000 };
scanner.TopText = "Hold camera up to barcode to scan";
scanner.BottomText = "Barcode will automatically scan";
//Start scanning
scanner.ScanContinuously(opt, false, HandleScanResult);
});
}
The UIAlertController code executes without an error but no alert appears. Is there a way to force the alert to appear over the top of everything?
A: I was able to figure it out. I changed my Utils.ShowMessage function as follows:
public static void ShowMessage(UIViewController myview, string message, string messagetype)
{
var window = UIApplication.SharedApplication.KeyWindow;
var vc = window.RootViewController;
while (vc.PresentedViewController != null)
{
vc = vc.PresentedViewController;
}
var okAlertController = UIAlertController.Create(message, messagetype, UIAlertControllerStyle.Alert);
okAlertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
vc.PresentViewController(okAlertController, true, null);
}
One needs to get the root view controller and display the alert from that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71324514",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is there mistake in passing parameters to push_relabel_max_flow()? So this is my code to get max flow though network using push_relabel_max_flow function in Boost C++ lib.
#include <string>
#include <boost/graph/adjacency_list.hpp>
#include <iostream>
#include <boost/graph/push_relabel_max_flow.hpp>
typedef boost::adjacency_list_traits<boost::vecS, boost::vecS, boost::directedS> Traits;
struct VertexProps {
std::string name;
};
struct EdgeProps {
long capacity;
long residual_capacity;
Traits::edge_descriptor reverse;
};
typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, boost::no_property, EdgeProps > DirectedGraph;
int main() {
DirectedGraph g;
Traits::vertex_descriptor s, t;
s = boost::add_vertex(g);
t = boost::add_vertex(g);
boost::add_vertex(g);
boost::add_edge(s, 2, { 33, 0 }, g);
boost::add_edge(2, t, { 33, 0 }, g);
auto capacity = boost::get(&EdgeProps::capacity, g);
auto reverse = boost::get(&EdgeProps::reverse, g);
auto residcap = boost::get(&EdgeProps::residual_capacity, g);
auto indexmap = boost::get(boost::vertex_index, g);
std::vector<DirectedGraph::vertex_descriptor> vertices;
int flow = boost::push_relabel_max_flow(g, s, t,capacity,residcap ,reverse,indexmap);
std::cout << flow;
return 0;
}
after running this code, it gives as error
Exception thrown at 0x008D2551 in ConsoleApplication4.exe: 0xC0000005: Access violation reading location 0x00000004.
Is there something I am missing? What is the problem here?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43438735",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why is Request.ContentType always empty on my requests? I have a base controller class that attempts to look at Request.ContentType to see if its a json request or a regular HTML request. The base controller then sets a simple enum on the base class and the appropriate controller returns the correct type. However, Request.ContentType is always an empty string. why is that?
my base controller:
namespace PAW.Controllers
{
public class BaseController : Controller
{
public ResponseFormat ResponseFormat { get; private set; }
public User CurrentUser { get; private set; }
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
Culture.SetCulture();
if (this.Request.ContentType.ToLower() == "application/json")
this.ResponseFormat = ResponseFormat.Json;
else
this.ResponseFormat = ResponseFormat.Html;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
//setup user object
this.CurrentUser = WebUser.CurrentUser;
ViewData["CurrentUser"] = WebUser.CurrentUser;
}
}
public enum ResponseFormat
{
Html,
Json,
Xml
}
}
my jquery:
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "/Vendor/Details/" + newid,
data: "{}",
dataType: "json",
success: function(data) { ShowVendor(data); },
error: function(req, status, err) { ShowError("Sorry, an error occured (Vendor callback failed). Please try agian later."); }
});
A: It looks like you're trying to use the ContentType header to determine which type of response to return. That's not what it's for. You should be using the Accepts header instead, which tells the server which content types you accept.
A: Try using
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "/Vendor/Details/" + newid,
beforeSend: function(xhr) {
xhr.setRequestHeader("Content-type",
"application/json; charset=utf-8");
},
data: "{}",
dataType: "json",
success: function(data) { alert(data); },
error: function(req, status, err) { ShowError("Sorry, an error occured (Vendor callback failed). Please try agian later."); }
});
a la -
http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/
A: The "content-type" header doesn't do anything when your method is "GET".
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1625707",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Attempt at "Longest Substring Without Repeating Characters" in Java I am attempting to do the longest substring without repeating characters problem in Java. I am trying to do two nested loop, and use a counter to keep track of how many characters are not repeated. When it finds a repeated character, it will reset the counter and break the loop. As of now, it is outputing 2 for this test case "abcabcbb", but I am not sure why.
class Solution {
public int lengthOfLongestSubstring(String s) {
if (s.length() == 0) return 0;
if (s.length() == 1) return 1;
int max = 1;
// if (s.charAt(0) != s.charAt(1)) max = 2;
int counter = 1;
String a = "" + s.charAt(0);
Character b;
Character c;
for (int i = 1;i<s.length()-1;i++){
b = s.charAt(i);
for (int j = 0; j< s.length()-i; j++){
c = a.charAt(j);
if (b.equals(c)){
counter = 1;
a = "" + s.charAt(i);
break;
}
else{
counter++;
a = a + s.charAt(i);
if (max < counter) max = counter;
}
}
}
return max;
}
}
A: As Jimmy points out, you do indeed miss even long runs of the same character as long as the run isn't of the character that starts the sequence you are testing. Here's a solution that I believe works in all cases:
public static int lengthOfLongestSubstring(String s) {
if (s.length() == 0) return 0;
if (s.length() == 1) return 1;
int max = 0;
for (int i = 0;i<s.length();i++){
Set<Character> chars = new HashSet<>();
chars.add(s.charAt(i));
for (int j = i+1; j< s.length(); j++){
Character b = s.charAt(j);
if (chars.contains(b))
break;
chars.add(b);
}
if (chars.size() > max)
max = chars.size();
}
return max;
}
A: The reason you are not getting the right answer here I believe is an algorithmic flaw. Your nested loops check to see if any character in a string is different from the first character. This does not check to see if there are any repeating characters in a substring. For example, in the example "abcabcbb," starting at the second 'a' there are no more 'a's, so your program will count the entire rest of the string. You will need to make some algorithmic modifications to solve your problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64584635",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: laravel filter return all the records im trying to search using three inputs, in the first scenario when i search using all the inputs it return the result, in the second scenrio when i search by using only one field it return all the records what im trying to do is when i search with one field it return a specsific result,
public function multiSearch(Request $request){
$search = $request->input('search');
$search_1 = $request->input('search_1');
$search_2 = $request->input('search_2');
$cars = Car::query()
->where('price', 'LIKE', "%{$search}%")
->orWhere('model', 'LIKE', "%{$search_1}%")
->orWhere('transmission', 'LIKE', "%{$search_2}%")
->get();
return view('car.car-multisearch', ['cars'=>$cars]);
}
this is my blade code
<form type="get" action="{{url('/search-car')}}">
@csrf
<div class="row">
<div class="col-md-4">
<p>
<input type="text" name="search" placeholder="Price" />
</p>
</div>
<div class="col-md-4">
<p>
<input type="text" name="search_1" placeholder="Model Year" />
</p>
</div>
<div class="col-md-4">
<p>
<select name="search_2">
<option data-display="Transmission">Transmission</option>
<option value="Automatic">Automatic</option>
<option value="Manual">Manual</option>
</select>
</p>
</div>
<button type="submit" class="gauto-theme-btn">Find Car</button>
</div>
</form>
A: You can dynamically add where statements to your query depending on values presence in the request and if they are not empty. Example:
public function multiSearch(Request $request){
$cars = Car::query();
if ( $request->filled('search') ) {
$cars->where('price', 'LIKE', "%{$request->input('search')}%");
}
if ( $request->filled('search_1') ) {
$cars->orWhere('model', 'LIKE', "%{$request->input('search_1')}%");
}
if ( $request->filled('search_2') ) {
$cars->orWhere('transmission', 'LIKE', "%{$request->input('search_2')}%");
}
return view('car.car-multisearch', ['cars'=> $cars->get() ]);
}
This solution do the job, but looks not good because you will need to add more if statements for each filter.)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69875726",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: In kotlin android tailrec function returns 0 I tried to use this tutorial youtube tutorial. I have a function as follows:
fun fact(x:Int):Int{
tailrec fun factTail(y:Int, z:Int):Int{
return if(y == 0) {
z
} else {
factTail(y - 1, y * z)
}
}
return factTail(x,1)
}
and this function is called in oncreate as:
var abc = fact(5)
Log.i(TAG, "5! = $abc")
When the app outputs log it shows like this:
I/MainActivity: 5! = 0
Can anyone point out what is wrong here.
A: You code is right and you definitely get 0 for multiple result more than MAX_SIZE of Int value. You can get Int max size with:
Int.MAX_VALUE
So if this y * x cross Int.MAX_VALUE = 2147483647, fun will return 0 to you.
For number bigger than 16 func will return minus number and for greater than 33 it will return 0. you can check this by:
for(x in 5..50){
log.i("$x! : ${fact(x)}")
}
So you can handle this by changing variable from Int to Long
fun fact(x : Long) : Long {
fun factTail(y : Long , z :Long):Long {
return if (y == 0L) z
else return factTail(y-1 ,y*z)
}
return factTail(x ,1)
}
But Long also have its limitation. Hope you get the point.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46763795",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Time Comparisons PHP Nightmare I'm having an issue with time comparisons with PHP - I think I must be doing something stupid but I've been trying different things for hours now and I'm just hitting a brick wall.
I'm pulling data from EVE's API and then doing a check for whither there is still subscription there and whither there is a skill in training - with both of these there is a particular time frame (1 week for subscription and 12 hours for skills) that I'd like to flag up a warning - however I can't seem to get it working at all. The output of all the dates and times seems to be the right format I just can't get the comparison to work.
I'm wondering if anyone can point what's most likely my stupid mistake and give me a push in the right direction.
thanks for taking a look,
<?php
// ---- For Skill Queue
$apiSection = "char/SkillQueue";
$urlChar = "https://api.eveonline.com/$apiSection.xml.aspx?keyID=$keyID&vCode=$vCode&characterID=$charID";
$data = file_get_contents($urlChar);
$xml = new SimpleXMLElement($data);
foreach ($xml->result->rowset->row as $row){
$charQueueEndTemp = $row{'endTime'};
}
$charQueueEnd = date("d-m-Y H:m", strtotime($charQueueEndTemp));
//echo "Skill Test" . $charQueueEnd;
// --- Account API
$apiSection = "account/AccountStatus";
$urlAccount = "https://api.eveonline.com/$apiSection.xml.aspx?keyID=$keyID&vCode=$vCode";
$data = file_get_contents($urlAccount);
$xml = new SimpleXMLElement($data);
$accSubsTemp = $xml->result->{'paidUntil'}->{0};
$accSubs = date("d-m-Y H:m", strtotime($accSubsTemp));
date_default_timezone_set('Europe/Paris');
$currentDate = date("d-m-Y H:m");
$lessWeek = date("d-m-Y H:m", strtotime("-1 week"));
$plusWeek = date("d-m-Y H:m", strtotime("+1 week"));
$plus12Hour = date("d-m-Y H:m", strtotime("+12 hour"));
//Date Tests
//echo "</br> Curent Date: ".$currentDate;
//echo "</br> Plus Week: ".$plusWeek;
//echo "</br>Acc Subs: ".$accSubs;
//echo "</br>Acc +12: ".$plus12Hour;
// -- Account Subscribed Check
if($currentDate > $accSubs){
echo "Account is not Subscribed";
}
elseif($plusWeek > $accSubs){
echo "Account has less than 1 week Subscription";
}
else{
echo "Account is Subscribed";
}
// -- Skill Training Check
if($charQueueEnd = null){
echo "Skill Queue Ended";
}
elseif($plus12Hour > $charQueueEnd){
echo "Skill Queue ending in less than 12 Hours";
}
else{
echo "Skill Queue Active";
}
?>
A: Start using DateTime class for date/time manipulation/compare :
If you change your code to this :
$currentDate = new DateTime();
$lessWeek = new DateTime("-1 week");
$plusWeek = new DateTime("+1 week");
$plus12Hour = new DateTime("+12 hour");
... then your IF statements will start to work.
A: You are doing the date comparisons completely WRONG. You're comparing date STRINGS, e.g. using some dates formatted the same way you're doing:
$plusWeek = '26-08-2013 8:30'; Aug 26th, 2013
$accSubs = '9-08-2013 10:45'; Aug 9th, 2013
Since these are strings, string comparison rules apply. That means the strings are compared character by character, and (string)26 is actually LESS than string(9), because 2 is smaller than 9.
You need to keep things as the raw timestamps, e.g. the strtotime() output:
$plusWeek = strtotime('2013-08-26 08:30'); // 1377527400
$accSubs = strtotime('2013-08-09 10:45').; // 1376066700
Comparing these integer values will work as you want.
The main problem is also that you're not formatted your data strings in "most significant data" order. If they were formatted with the year first, e.g.
yyyy-mm-dd hh:mm:ss
then a string comparison WOULD work as a side effect.
A: If you want to compare dates you have to compare arguments returned by strtotime() function, for example:
elseif(strtotime($plus12Hour) > strtotime($charQueueEnd)){
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18468259",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Access violation in release without debugger I'm having a problem with my project where it operates fine when compiled in debug mode, and works fine in release mode while the debugger is attached in Visual Studio, but if I run it in release with no debugger, I get an access violation deep within bullet physics.
The access violation seems to happen at btVoronoiSimplexSolver::updateClosestVectorAndPoints(void) C++, I only now this because Windows gives me the option to debug after the crash. I have the same problem when it's compiled with GCC on Linux, however.
My question is: what changes between having the debugger attached and not attached that could cause this problem? Why doesn't this crash occur when the debugger is attached, and is there any way for me to set the debugger to catch this sort of problem?
A: In case this can help anybody in the future - this issue was caused by me performing a placement-new in a block of memory that wasn't big enough to hold the object, no doubt overwriting some memory belonging to bullet physics.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27950598",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Representing closeness among elements of a double vector I have a double vector:
r = -50 + (50+50)*rand(10,1)
Now i want to ideally have all the numbers in the vector equal upto a tolerance of say 1e-4. I want to represent each r with a scalar say s(r) such that its value gives an idea of the quality of the vector. The vector is high quality if all elements in the vector are equal-like. I can easily run a for loop like
for i=1:10
for j=i+1:10
check equality upto the tolerance
end
end
But even then i cannot figure what computation to do inside the nested for loops to assign a scalar representing the quality . Is there a better way such that given any vector r length n, i can quickly calculate a scalar representing the quality of the vector.
A: Your double-loop algorithm is somewhat slow, of order O(n**2) where n is the number of dimensions of the vector. Here is a quick way to find the closeness of the vector elements, which can be done in order O(n), just one pass through the elements.
Find the maximum and the minimum of the vector elements. Just use two variables to store the maximum and minimum so far and run once through all the elements. The difference between the maximum and the minimum is called the range of the values, a commonly accepted measure of dispersion of the values. If the values are exactly equal, the range is zero which shows perfect quality. If the range is below 1e-4 then the vector is of acceptable quality. The bigger the range, the worse the equality.
The code is obvious for just about any given language, so I'll leave that to you. If the fact that the range only really considers the two extreme values of the vector bothers you, you could use other measures of variation such as the interquartile range, variance, or standard deviation. But the range seems to best fit what you request.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41916750",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Replacing part of string with a HTML Element I'm using plain Javascript to replace part of a string with an HTML Element.
I'm using the following script to do what I need, consider var data to be an array of objects where data[objectAtIndex].text has the following example string {0} is the right answer, but it can also contain Something {0} fishy. The {0} part of the string can change place at any time.
var select = document.createElement("select"),
textDiv = document.createElement("div");
textDiv.innerHTML = data[i].text.replace(pattern, select);
The regular expression I use looks like var pattern = /\{0\}/i;
Now, this halfway works, only it converts the select element to string, which yields [object HTMLSelectElement] instead of the actual element itself.
I want the actual element, and not the string representation of this, and I can't really find any answers which doesn't utilize jQuery.
A: Wrap your element(s) in a temp <div> and then get its .innerHTML.
var select = document.createElement("select"),
textDiv = document.createElement("div"),
tempDiv = document.createElement("div");
tempDiv.appendChild(select);
textDiv.innerHTML = data[i].text.replace(pattern, tempDiv.innerHTML);
A: By using innerHTML, you're using markup. So one option is, just use markup (but more options follow):
var textDiv = document.createElement("div");
textDiv.innerHTML = data[i].text.replace(pattern, "<select></select>");
Live example:
var data = {
0: {
text: "This is a <strong>test</strong> {0} Testing <em>1 2 3</em>"
}
};
var i = 0;
var pattern = /\{0\}/i;
var textDiv = document.createElement("div");
textDiv.innerHTML = data[i].text.replace(pattern, "<select></select>");
document.body.appendChild(textDiv);
If you don't want to use markup, you can append the part of the string before the {0}, then the element, then the part of the string after the {0}:
var select = document.createElement("select"),
textDiv = document.createElement("div"),
text = data[i].text,
index = text.indexOf("{0}"); // No need for case-insensitivity
if (index === -1) {
index = text.length;
}
textDiv.innerHTML = text.substring(0, index);
textDiv.appendChild(select);
if (index < text.length) {
textDiv.insertAdjacentHTML("beforeend", text.substring(index + 3));
}
var data = {
0: {
text: "This is a <strong>test</strong> {0} Testing <em>1 2 3</em>"
}
};
var i = 0;
var select = document.createElement("select"),
textDiv = document.createElement("div"),
text = data[i].text,
index = text.indexOf("{0}"); // No need for case-insensitivity
if (index === -1) {
index = text.length;
}
textDiv.innerHTML = text.substring(0, index);
textDiv.appendChild(select);
if (index < text.length) {
textDiv.insertAdjacentHTML("beforeend", text.substring(index + 3));
}
document.body.appendChild(textDiv);
Or if the pattern has to be a regex:
var select = document.createElement("select"),
textDiv = document.createElement("div"),
text = data[i].text,
match = pattern.exec(text),
index = match ? match.index : text.length;
textDiv.innerHTML = text.substring(0, index);
textDiv.appendChild(select);
if (match) {
textDiv.insertAdjacentHTML("beforeend", text.substring(index + match[0].length));
}
var data = {
0: {
text: "This is a <strong>test</strong> {0} Testing <em>1 2 3</em>"
}
};
var i = 0;
var pattern = /\{0\}/i;
var select = document.createElement("select"),
textDiv = document.createElement("div"),
text = data[i].text,
match = pattern.exec(text),
index = match ? match.index : text.length;
textDiv.innerHTML = text.substring(0, index);
textDiv.appendChild(select);
if (match) {
textDiv.insertAdjacentHTML("beforeend", text.substring(index + match[0].length));
}
document.body.appendChild(textDiv);
A: Here's the simplest solution. Use select.outerHTML
var select = document.createElement("select"),
textDiv = document.createElement("div");
textDiv.innerHTML = data[i].text.replace(pattern, select.outerHTML);
and widely supported.
Live example:
var text = "This is a <strong>test</strong> {0} Testing <em>1 2 3</em>"
var pattern = /\{0\}/i;
var select = document.createElement("select"),
textDiv = document.createElement("div");
textDiv.innerHTML = text
document.body.appendChild(textDiv);
setTimeout(function(){
textDiv.innerHTML = text.replace(pattern, select.outerHTML);
}, 1000)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29261960",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: check if SQL field has UNIQUE constraint via ADODB VBA I am writing vba code to update SQLSERVER tables.
I want to check all values for a new record are ok, before actually trying to update them.
How can I check if a field has UNIQUE constrain?
I have tried listing all properties and attributes, but the propertie ISUNIQUE does not show anything, although it is set as such and it produces error when tring to create a new record with duplicate enty in this field
Properties
BASECATALOGNAME = TEBUS_Templates
BASECOLUMNNAME = Nombre del Armario
BASESCHEMANAME =
BASETABLENAME = TBL_FAKOM_ARMARIOS
CLSID =
COLLATINGSEQUENCE =
COMPUTEMODE =
DATETIMEPRECISION =
DEFAULTVALUE =
DOMAINCATALOG =
DOMAINSCHEMA =
DOMAINNAME =
HASDEFAULT =
ISAUTOINCREMENT = Falso
ISCASESENSITIVE = Falso
ISSEARCHABLE = 4
ISUNIQUE =
OCTETLENGTH = 200
KEYCOLUMN = Falso
OPTIMIZE = Falso
Attributes
adFldUnknownUpdatable
FWIW this is the procedure I put together to get the list above:
'2017-05-22 / B.Agullo /
Public Sub showFieldAtributesAndProperties(ByVal f As Field)
'description of sub
Dim p As Variant
Debug.Print f.Name
Debug.Print "Properties"
For Each p In f.Properties
Debug.Print p.Name & " = " & p.Value
Next
Debug.Print Chr(10) & "Attributes"
If ((adFldCacheDeferred And f.Attributes) = adFldCacheDeferred) Then Debug.Print "adFldCacheDeferred"
If ((adFldFixed And f.Attributes) = adFldFixed) Then Debug.Print "adFldFixed"
If ((adFldIsChapter And f.Attributes) = adFldIsChapter) Then Debug.Print "adFldIsChapter"
If ((adFldIsCollection And f.Attributes) = adFldIsCollection) Then Debug.Print "adFldIsCollection"
If ((adFldIsDefaultStream And f.Attributes) = adFldIsDefaultStream) Then Debug.Print "adFldIsDefaultStream"
If ((adFldIsNullable And f.Attributes) = adFldIsNullable) Then Debug.Print "adFldIsNullable"
If ((adFldIsRowURL And f.Attributes) = adFldIsRowURL) Then Debug.Print "adFldIsRowURL"
If ((adFldLong And f.Attributes) = adFldLong) Then Debug.Print "adFldLong"
If ((adFldMayBeNull And f.Attributes) = adFldMayBeNull) Then Debug.Print "adFldMayBeNull"
If ((adFldMayDefer And f.Attributes) = adFldMayDefer) Then Debug.Print "adFldMayDefer"
If ((adFldNegativeScale And f.Attributes) = adFldNegativeScale) Then Debug.Print "adFldNegativeScale"
If ((adFldRowID And f.Attributes) = adFldRowID) Then Debug.Print "adFldRowID"
If ((adFldRowVersion And f.Attributes) = adFldRowVersion) Then Debug.Print "adFldRowVersion"
If ((adFldUnknownUpdatable And f.Attributes) = adFldUnknownUpdatable) Then Debug.Print "adFldUnknownUpdatable"
If ((adFldUnspecified And f.Attributes) = adFldUnspecified) Then Debug.Print "adFldUnspecified"
If ((adFldUpdatable And f.Attributes) = adFldUpdatable) Then Debug.Print "adFldUpdatable"
release:
End Sub
also, for your reference, this is the SQL command to create the table
CREATE TABLE TBL_FAKOM_ARMARIOS(
"ArmarioID" int IDENTITY(1,1) PRIMARY KEY NOT NULL
, "Nombre del Armario" nvarchar(100) UNIQUE NOT NULL
, "Fecha de Alta" dateTime NOT NULL
, "Fecha de Baja" dateTime
, "Usuario de Alta" nvarchar(50) NOT NULL
, "Usuario de Baja" nvarchar(50)
)
A: You can use the database schema, something like so
Function IX_UNIQUE(strTableName As String, strFieldName As String) as Boolean
Dim c As ADODB.Connection
Dim r As ADODB.Recordset
Set c = New ADODB.Connection
c.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & "C:\TESTsb.accdb" & ";" & _
"Persist Security Info=False;"
c.Open
Set r = New ADODB.Recordset
Set r = c.OpenSchema(adSchemaIndexes, Array(Empty, Empty, strFieldName , Empty, strTableName))
If Not r.EOF Then
IX_UNIQUE = r.Fields("UNIQUE").value
Else
IX_UNIQUE = False
End If
End Function
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44108049",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I link/join/relate the types of two function parameters in TypeScript? Based on the similar question about linking class fields, how do I get TypeScript to recognize that the value of one parameter to a function (whose value is determined at runtime) restricts the type of another?
Example code (playground):
class Cat { purr() {/*...*/} }
class Dog { bark() {/*...*/} }
interface TypeMap {
cat: Cat;
dog: Dog;
}
const makeSound = function<C extends keyof TypeMap>(
commonName: C,
animal: TypeMap[C],
) {
if(commonName === 'cat') {
//Error: this.animal is of type 'Cat | Dog',
//not narrowed to Cat as hoped.
return animal.purr();
} else if (commonName === 'dog') {
//Error: this.animal is of type 'Cat | Dog',
//not narrowed to Dog as hoped.
return animal.bark();
}
}
//The intended type-checking is being done in calling contexts:
const caller = function(cat: Cat, dog: Dog) {
//Error on next line as expected:
//Argument of type '"dog"' is not assignable
//to parameter of type '"cat"'.ts(2345)
makeSound<'cat'>('dog', dog);
makeSound<'cat'>('cat', dog); //similar error, as expected
makeSound<'cat'>('cat', cat); //works
makeSound('cat', cat); //desired style; cat vs. dog not hard-codable
}
The TS documentation states 'You can declare a type parameter that is constrained by another type parameter.' but the example given is very simple and seems fragile in terms of ability to generalize to a slightly more complex example like this one.
A: You are manually checking commonName against individual cases, and TypeScript really doesn't have good support for type checking the body of makeSound() if it is generic. Even though commonName is of the generic type C, checking commonName only narrows the type of commonName itself, it does not further constrain C. So unfortunately, even if the compiler knows that commonName is "cat", it does not know that C is "cat". It can still be "cat" | "dog", and thus worries about the (admittedly unlikely) possibility of a call like
makeSound(
Math.random() < 0.99 ? "cat" : "dog",
Math.random() < 0.99 ? dog : cat
); // no error?!
We have failed to actually make the link we intended to make, and even though it's usually good enough (I mean, really, who passes cross-correlated unions into functions like that?), the compiler is unwilling to type check the body.
There are various feature requests asking for an improvement here. For example, microsoft/TypeScript#27808 wants to make it possible to say something C extends oneof keyof TypeMap so that the full union type keyof TypeMap would be rejected. For now though nothing is implemented, and if we want to write your code we will need to refactor (or else pepper your code with type assertions to suppress the error... but let's investigate refactoring.)
Because the return type of makeSound() does not depend on C, you can refactor your call signature to a non-generic version that enforces the actual constraint you have. Essentially the parameter tuple, [commonName, animal] forms a discriminated union where the property at index 0 is the discriminant, and checking it will narrow the type of the property at index 1. You can compute this union type like this:
type MakeSoundParam = { [K in keyof TypeMap]:
[commonName: K, animal: TypeMap[K]]
}[keyof TypeMap];
/* type MakeSoundParam =
[commonName: "cat", animal: Cat] |
[commonName: "dog", animal: Dog] */
TypeScript supports control flow analysis for destructured discriminated unions, which means you can rewrite your function as:
const makeSound = function (...[commonName, animal]: MakeSoundParam) {
if (commonName === 'cat') {
return animal.purr(); // okay
} else if (commonName === 'dog') {
return animal.bark(); // okay
}
}
That compiles without error. And just to be sure that makeSound() still behaves properly from the caller's side:
const caller = function (cat: Cat, dog: Dog) {
makeSound('cat', cat); // ok
makeSound('dog', dog); // ok
makeSound('cat', dog); // error
makeSound('dog', cat); // error
makeSound(
Math.random() < 0.99 ? "cat" : "dog",
Math.random() < 0.99 ? dog : cat
); // error
}
Looks good, and even the cross-correlated call is rejected.
Playground link to code
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72890232",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to create new arrays from object array based on user_id? I'm having trouble looping through an object array and displaying data from it under certain conditions.
I want the webpage to display the following:
<p>John Doe</p> <p>William Green</p> <p>Jane Smith</p>
I know how to do this by defining $user[0]->first_name . $user[0]->last_name specifically, but what I need is a way for the code to loop through and display the names dynamically using the user_id property as a unique identifier.
For all objects in the array with user_id 1, return "these values." For all the objects in the array with user_id 2, return "these values." And so on...looping through each unique user_id.
Here is a var_dump of the object array:
array(4)
{ [0]=> object(stdClass)#4336 (4)
{
["umeta_id"]=> string(1) "1"
["user_id"]=> string(1) "1"
["meta_key"]=> string(10) "first_name"
["meta_value"]=> string(4) "John"
}
[1]=> object(stdClass)#4333 (4)
{
["umeta_id"]=> string(1) "2"
["user_id"]=> string(1) "1"
["meta_key"]=> string(9) "last_name"
["meta_value"]=> string(3) "Doe"
}
[2]=> object(stdClass)#4334 (4)
{
["umeta_id"]=> string(1) "3"
["user_id"]=> string(1) "2"
["meta_key"]=> string(10) "first_name"
["meta_value"]=> string(4) "Jane"
}
[3]=> object(stdClass)#4334 (4)
{
["umeta_id"]=> string(1) "4"
["user_id"]=> string(1) "2"
["meta_key"]=> string(9) "last_name"
["meta_value"]=> string(5) "Smith"
}
[4]=> object(stdClass)#4334 (4)
{
["umeta_id"]=> string(1) "5"
["user_id"]=> string(1) "3"
["meta_key"]=> string(10) "first_name"
["meta_value"]=> string(7) "William"
}
[5]=> object(stdClass)#4334 (4)
{
["umeta_id"]=> string(1) "6"
["user_id"]=> string(1) "3"
["meta_key"]=> string(9) "last_name"
["meta_value"]=> string(5) "Green"
}
}
When I output the information on the webpage, I want it to look like this:
<p>John Doe</p> <p>William Green</p> <p>Jane Smith</p>
Maybe I need to loop through objects and build new arrays based on user_ids? Please do not provide code with echo or print_r. Only "return" can be used for this project.
A: So $your_object is already sorted by umeta_id and user_id fields?
If not, you can use usort:
function cmp1($a, $b)
{
return strcmp($a->umeta_id, $b->umeta_id);
}
function cmp2($a, $b)
{
return strcmp($a->user_id, $b->user_id);
}
usort($your_object, "cmp1");
usort($your_object, "cmp2");
Then simply:
$str = '';
for($i=0;$i<count($your_object);$i+=2){
$str .= "<p>".$your_object[$i]->meta_value." "$your_object[$i+1]->meta_value."</p> ";
}
return $str; // this var contain all your data in string
Hope this helps!
A: This will generate the first-name and last-name pairs :
$user_group = array();
ksort($user_group, SORT_NUMERIC);
foreach ($users as $key => $item) {
$name_meta = get_object_vars($item);
foreach ($name_meta as $meta_in => $names) {
if ($names == 'first_name') {
$user_group[$item->user_id]['first_name'] = $name_meta['meta_value'];
}
if ($names == 'last_name') {
$user_group[$item->user_id]['last_name'] = $name_meta['meta_value'];
}
}
}
Output :
array(3) {
[1]=>
array(2) {
["first_name"]=>
string(4) "John"
["last_name"]=>
string(3) "Doe"
}
[2]=>
array(2) {
["first_name"]=>
string(4) "Jane"
["last_name"]=>
string(5) "Smith"
}
[3]=>
array(2) {
["first_name"]=>
string(7) "William"
["last_name"]=>
string(5) "Green"
}
}
And to print the user name pairs :
foreach ($user_group as $name) {
echo "<p>" . $name['first_name'] . " " . $name['last_name'] . "</p>";
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/56943724",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: My footer doesn't show all the content when the screen size gets shorter My footer's last part(the "address" part disappear when the screen's height is shorter than some certain points, around 938), I wonder why?
The HTML looks like this:
<div className="container-fluid footer">
<div className="container contact-block">
<h3> Contact </h3>
<p>Telephone: </p>
<p>Address: </p>
</div>
</div>
So my footer's CSS looks like this:
.footer{
height: 12%;
background-color: rgb(54, 58, 57);
margin-top: 2%;
color: antiquewhite;
position: fixed;
bottom: 0;
padding-bottom: 8%;
}
...
.contact-block{
padding: 1%;
font-family: Georgia, 'Times New Roman', Times, serif;
}
BTW, I use react-bootstrap for styling too
A: It's because of the height: 12%; after a certain limit the height becomes too small and cannot contain the elements.
I would reconsider using a percentage as the height but if you really want to, then I would at least put something like min-height: 100px; (or whatever min-height works based on your styles), I believe that should solve the issue :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62238155",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Run com.google.example.games.bc and fails I try to run the ButtonClick example of google, and I get this exception:
10-12 15:50:22.744 7085-7085/com.google.example.games.bc E/﹕ Device driver API match
Device driver API version: 23
User space API version: 23
10-12 15:50:22.744 7085-7085/com.google.example.games.bc E/﹕ mali: REVISION=Linux-r3p2-01rel3 BUILD_DATE=Wed Oct 9 21:05:57 KST 2013
10-12 15:50:23.049 7085-7085/com.google.example.games.bc E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.IllegalStateException: A fatal developer error has occurred. Check the logs for further information.
at com.google.android.gms.internal.id$h.b(Unknown Source)
at com.google.android.gms.internal.id$h.e(Unknown Source)
at com.google.android.gms.internal.id$b.fv(Unknown Source)
at com.google.android.gms.internal.id$a.handleMessage(Unknown Source)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5419)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
at dalvik.system.NativeStart.main(Native Method)
I changed nothing from the Git project (by Google).
Any clue?
Thanks in advance.
A: Found it!
In the AndroidManifest.xml there is a ReplaceMe tag in:
<meta-data android:name="com.google.android.gms.games.APP_ID"
android:value="ReplaceMe" />
There in strings.xml there is a string resource:
<string name="app_id">ReplaceMe</string>
Should replace the ReplaceMe :) with the app ID from the google play console.
Good luck!
A: If you do not want to pay google play console, you can set <string name="app_id">1</string> in strings.xml
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26325303",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: C# ssl stream wont stop buffering before sending I am trying to use C# to connect over a ssl socket to a server and send xml data back and forth. It seems that data won't be sent till it has reached a certain packet size 1000 bytes, upon which all the packets are just smashed on top of each other. Is there a way to force ssl library to send out packets as I send them?
I am using SslStream and StreamWriter to send the data, and i have already tried making packet size smaller and setting NoDelay to true to no avail. Is there just something I am missing?
sslStream = new SslStream(sslClient.GetStream(), false, new RemoteCertificateValidationCallback(CertificateValidationCallback));
sslStream.AuthenticateAsClient(appSettings.CBPASServer);
showSslInfo(appSettings.CBPASServer, sslStream, true);
streamWriter = new StreamWriter(sslStream);
...
sslStream.Write(xml);
sslStream.Flush();
A: My guess is that it's your StreamWriter that is chunking your data. Try setting AutoFlush = true.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1341636",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to hide header of TreeTableView? Is there any way to hide the header of a TreeTableView in JavaFX?
I am asking, because I have treestructured data which I always want to present within three columns, whereas two of them always will have the same size. So there is no need for the user to modify any columnspecific properties. Also there wont be the possiblity of filtering, sorting the data, since it is just not necessary.
So I am wondering if it is possible to hide the header of the TreeTableView, because it just costs space. Within the documentation as well as in the sources, I couldnt find any hints to do so.
A: Of course jewelsea already answered that question here. Just the topic of the question was little misleading, but it works the same way for TreeTableView.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22450645",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Node.js callback within a loop has wrong iterator value
for(var i in companyTickerList) {
console.log('i = ' + i);
//construct url
var url = base_url + companyTickerList[i];
console.log('url = ' + url);
request(url, function(error, response, xml) {
if(!error && response.statusCode == 200) {
//load xml returned from GET to url
var cik_xml = cheerio.load(xml)
console.log('i = ' + i);
//map company ticker symbol to cik value scraped from xml
TickerToCIK[companyTickerList[i]] = cik_xml('company-info cik').text();
console.log('TICKER = ' + companyTickerList[i] + ' CIK = ' + cik_xml('company-info cik').text());
}
}
//CONSOLE LOG OUTPUT
i = 0
http://www.sec.gov/cgi-bin/browse..........SNPS
i = 1
http://www.sec.gov/cgi-bin/browse..........IBM
i = 2
http://www.sec.gov/cgi-bin/browse..........BA
i = 3
http://www.sec.gov/cgi-bin/browse..........GM
i = 4
http://www.sec.gov/cgi-bin/browse..........F
i = 5
http://www.sec.gov/cgi-bin/browse..........C
i = 6
http://www.sec.gov/cgi-bin/browse..........CVX
i = 6
TICKER = CVX CIK = 0000883241
i = 6
TICKER = CVX CIK = 0000037996
i = 6
TICKER = CVX CIK = 0000831001
i = 6
TICKER = CVX CIK = 0000093410
i = 6
TICKER = CVX CIK = 0001467858
i = 6
TICKER = CVX CIK = 0000012927
i = 6
TICKER = CVX CIK = 0000051143
Why is the iterator value i always equivalent to 6 in the callback function after each request call is triggered? It is making the keys for my TickerToCIK map always be CVX. Do I need to pass i as an argument to the callback function?
A: You will need to use a closure to implement this correctly. For example, something like this.
for(var i in companyTickerList) {
console.log('i = ' + i);
//construct url
var url = base_url + companyTickerList[i];
console.log('url = ' + url);
function(i){
request(url, functon(error, response, xml) {
if(!error && response.statusCode == 200) {
//load xml returned from GET to url
var cik_xml = cheerio.load(xml)
console.log('i = ' + i);
//map company ticker symbol to cik value scraped from xml
TickerToCIK[companyTickerList[i]] = cik_xml('company-info cik').text();
console.log('TICKER = ' + companyTickerList[i] + ' CIK = ' + cik_xml('company-info cik').text());
}
}
}(i)
}
I haven't tested the above, but you can see how I wrapped the request in a function, and passed that function the iterator value as an argument.
A: var is tricky :)
JavaScript actually evaluates your code like this:
var i;
for(i in companyTickerList) {
console.log('i = ' + i);
// ...
meaning, it's like var definition executed before your first line of code.
So, you actually have a variable i which gets updated 6 times and eventually i = 6.
Your request() callback is async, and by the time your first callback actually got invoked, the loop is long gone and i equals 6.
Solution:
One possible solution is to use an IIFE (Immediately-Invoked Function Expression).
That is:
(function (i) {
// async code using i
})(i);
Like so:
for (var i in companyTickerList) {
console.log('i = ' + i);
//construct url
var url = base_url + companyTickerList[i];
console.log('url = ' + url);
(function (i) {
request(url, function (error, response, xml) {
if (!error && response.statusCode == 200) {
//load xml returned from GET to url
var cik_xml = cheerio.load(xml);
console.log('i = ' + i);
//map company ticker symbol to cik value scraped from xml
TickerToCIK[companyTickerList[i]] = cik_xml('company-info cik').text();
console.log('TICKER = ' + companyTickerList[i] + ' CIK = ' + cik_xml('company-info cik').text());
}
});
})(i);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36389324",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Passing parameters from command line to C++ Searching the net for examples how to pass command line parameters to a C++ code, I came up with an abandoned post where this process is being explained. This code was not working and after a few amendments I came up with the following (working) code:
#include <iostream>
#include <windows.h>
#include <fstream>
#include <string>
using namespace std;
// When passing char arrays as parameters they must be pointers
int main(int argc, char* argv[]) {
if (argc < 2) { // Check the value of argc. If not enough parameters have been passed, inform user and exit.
std::cout << "Usage is -i <index file name including path and drive letter>\n"; // Inform the user of how to use the program
std::cin.get();
exit(0);
} else { // if we got enough parameters...
char* indFile;
//std::cout << argv[0];
for (int i = 1; i < argc; i++) { /* We will iterate over argv[] to get the parameters stored inside.
* Note that we're starting on 1 because we don't need to know the
* path of the program, which is stored in argv[0] */
if (i + 1 != argc) {// Check that we haven't finished parsing already
if (strcmp(argv[i],"/x")==0) {
// We know the next argument *should* be the filename:
char indFile=*argv[i+1];
std::cout << "This is the value coming from std::cout << argv[i+1]: " << argv[i+1] <<"\n";
std::cout << "This is the value of indFile coming from char indFile=*argv[i+1]: " <<indFile <<"\n";
} else {
std::cout << argv[i];
std::cout << " Not enough or invalid arguments, please try again.\n";
Sleep(2000);
exit(0);
}
//std::cout << argv[i] << " ";
}
//... some more code
std::cin.get();
return 0;
}
}
}
Executing this code from the Windows command line using:
MyProgram.exe /x filename
returns the next output:
This is the attribute of parameter /x: filename
This is the value from *argv[i+1]: f
The original post from cplusplus.com did not compile; the code above does.
As you can see printing the argv[2] gives me the name of the file. When I try to capture the file name into another var so I can use it in the C++ program, I only get the first character (second response line).
Now for my question: How can I read the value from the command line parameter the pointer is pointing to?
Hope someone can help this newbie in C++ :-)
A: *argv[i+1]
Accesses the 1st char of the char* argv[] argument.
To get the whole value use something like
std::string filename(argv[i+1]);
instead.
A: You can't store a string in a single char.
Here's the once-an-idiom for copying the main arguments to more manageable objects:
#include <string>
#include <vector>
using namespace std;
void foo( vector<string> const& args )
{
// Whatever
(void) args;
}
auto main( int n, char* raw_args[] )
-> int
{
vector<string> const args{ raw_args, raw_args + n };
foo( args );
}
Do note that this code relies on an assumption that the encoding used for the main arguments can represent the actual command line arguments. That assumption holds in Unix-land, but not in Windows. In Windows, if you want to deal with non-ASCII text in command line arguments, you'd better use a third party solution or roll your own, e.g. using Windows' GetCommandLine API function.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39063819",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I count how often a method was called within 10 milliseconds? I have a sensorlistener which runs the method "onsensorchanged" every single time an event has occured. Now I want to know how often this method is executed within 10 millisecond.
I have a timespan (current Timestamp- previous Timestamp), which should execute "counter++" when my timespan(total millisec) is smaller then 10.
Unfortunately my counter is always 0 somehow.
I did the initializiation outside of the onSensorChanged method because it would always initialize each time the method would be running (to 0).
DateTime timestamp;
DateTime timestampAlt;
TimeSpan deltaT;
int counter = 0;
public void OnSensorChanged(SensorEvent e)
{
timestamp = System.DateTime.Now; //timestamp of now
deltaT = timestamp - timestampAlt; //delta of timestamp of event 1 and event 2
//if delta between two events happened before 10 milli sec past, ignore
if (deltaT.TotalMilliseconds <= 10 || deltaT.TotalMilliseconds <= -10) //deltaT.Seconds <= 0.01
{
counter++;
return;
}
Console.WriteLine(counter);
//if 10 ms past, our previous timestamp become the old
timestampAlt = timestamp;
}
A: DateTime.Now itself may take too much time being calculated, you'll be better off using a System.Diagnostics.Stopwatch.
Something like this:
Stopwatch stopwatch = new Stopwatch();
int counter = 0;
public void OnSensorChanged(SensorEvent e)
{
if (!stopwatch.IsRunning)
{
// start the stopwatch
stopwatch.Start();
}
else
{
if (stopwatch.ElapsedMiliseconds <= 10)
{
counter++;
return;
}
}
Console.WriteLine(counter);
// 10ms passed, restart the stopwatch
stopwatch.Restart();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55618042",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How to store an Encrypted type in flutter sharedprefrence Am designing an app in flutter and I have successfully encrypted a string using encrypt. now i want to store this encrypted data in sharedpreference so i can retrieve it later and decrypt it before using. I have tried setString() it does not work as it seem 'Encrypted' is a type itself so won't work with strings. Is there any work around.
this is my code
Encrypted runEncrypt( String caption) {
final key = Key.fromUtf8('u^Hrf64hFrM08HuytDeMK7654DgJlP');
final iv = IV.fromLength(16);
final encryptPro = Encrypter(AES(key));
final encrypted = encryptPro.encrypt(caption, iv: iv);
return encrypted;
}
/////
Encrypted keyz=runEncrypt('this is the key');
pref.setString("key",keyz);
A: You could use the base64 property of your encrypted object it returns a String.
In the source code of the package it says that it returns the Encrypted as a Base64 String representation.
pref.setString("key", keyz.base64);
use the same encoding while decrypting
Encrypter.decrypt64(valueFromSharedPref)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63592608",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: C++ Importing filename from variable I'm have variable 'filename' with contents 'code.h', i'm need do this,
#include <filename>
why it's not working? Or #include not works with variables?
A: #include is for other header files not variables. If you want to conditionally include header files you can use precompiler commands:
//config.h
#define USE_HEADER_CODE_H
//other.h
#include <config.h>
#if defined(USE_HEADER_CODE_H)
#include <code.h>
#else
#include <other_code.h>
#endif
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61949180",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: PostgreSQL WHERE IN LIKE query I was wondering if it's possible to do a query using the IN clause where the options inside it are LIKE clauses, for example I have my existing SQL which returns the same results as I intend it just seems like a round about way to do it.
SELECT *
FROM pg_stat_activity
WHERE application_name NOT LIKE '%psql%'
AND (current_timestamp - state_change) > INTERVAL '30 minutes'
AND state IN (
SELECT state
FROM pg_stat_activity
WHERE state LIKE '%idle%'
OR state LIKE '%disabled%'
)
Is there a way to replace with something along the lines of
SELECT *
FROM pg_stat_activity
WHERE application_name NOT LIKE '%psql%'
AND (current_timestamp - state_change) > INTERVAL '30 minutes'
AND state IN ('%idle%', '%disabled%')
A: x IN (a, b) can be consisidered shorthand for x = ANY (ARRAY[a,b]). Similarly, x IN (SELECT ...) and x = ANY (SELECT ...).
The = can actually be replaced by any binary operator. Thus, you can use:
SELECT ... WHERE x LIKE ANY (SELECT ...)
A: Use SIMILAR TO instead of LIKE
AND state SIMILAR TO '%(idle|disabled)%'
https://www.postgresql.org/docs/9.0/static/functions-matching.html
A: Users of MySQL or Oracle may find it a bit different, but in PostGreSQL, to filter data using LIKE clause, one should use something like -
select * from table-name where column-name::text like '%whatever-to-be-searched%'
A: Actually using something IN (<value list>) is similar to something = any(array[<value list>]) in the PostgreSQL:
postgres=# explain select 1 where 'a' in ('a','b','c');
QUERY PLAN
----------------------------------------------------------
Result (cost=0.00..0.01 rows=1 width=0)
One-Time Filter: ('a'::text = ANY ('{a,b,c}'::text[]))
(2 rows)
Fortunately we can use like or even ilike instead of =:
select 1 where 'aa' ilike any(array['%A%','%B%','%C%']);
?column?
----------
1
(1 row)
So in your case it could be
... state LIKE ANY(ARRAY['%idle%', '%disabled%'])
And the additional advantage: it can be passed as a parameter from the client application.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38073291",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
}
|
Q: Named page-router-outlet adds blue header on top of the app I am using nativescript and Angular and trying to implement tabs. Everything is good however i get blue line with word 'client' on top of the app. It comes from page-router-outlet. I know it sounds crazy but i do not have any items with word 'client' in my app keeping in mind that i just started and copied bottom navigation from example. I will attach screenshot in order to visualize it.
A: It must be name of your app. By default the Actionbar (the blue bar) might show the name of your app. You may get rid of the ActionBar from page-router-outlet by setting actionBarVisibility attribute to never
<page-router-outlet actionBarVisibility="never"></page-router-outlet>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60082574",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: R : Split string based on list of words I have 2 columns say ID and Hours. ID is self-explanatory. Hours column consists of hours for which an entity is open on each weekday as mentioned below. Note certain entities might be open intermittently in a day as shown in id 2.
ID | Hours
---
1 | {"sunday":[["10:00","21:30"]],"saturday":[["10:00","21:30"]],
"tuesday":[["10:00","21:30"]],"friday":[["10:00","21:30"]],
"thursday":[["10:00","21:30"]],"wednesday":[["10:00","21:30"]],
"monday":[["10:00","21:30"]]}
---
2 | {"sunday":[["7:00","15:00"],["17:30","21:30"]],
"saturday":[["7:00","15:00"],["17:30","21:30"]],
"tuesday":[["7:00","15:00"],["17:30","21:30"]],
"friday":[["7:00","15:00"],["17:30","21:30"]],"thursday":[["7:00","15:00"],["17:30","21:30"]],
"wednesday":[["7:00","15:00"],["17:30","21:30"]],
"monday":[["7:00","15:00"],["17:30","21:30"]]}
What I am looking for: Split the hours into different columns. Also, time should be placed under respective day.
ID | Sunday | Monday | Tuesday | Wednesday | Thursday | Friday | Saturday
---
1 | ["10:00","21:30"] | ["10:00","21:30"] | ["10:00","21:30"] | ["10:00","21:30"] | ["10:00","21:30"] | ["10:00","21:30"] | ["10:00","21:30"]
---
2 | ["7:00","15:00"],["17:30","21:30"] | ["7:00","15:00"],["17:30","21:30"] | ["7:00","15:00"],["17:30","21:30"] | ["7:00","15:00"],["17:30","21:30"] | ["7:00","15:00"],["17:30","21:30"] | ["7:00","15:00"],["17:30","21:30"] | ["7:00","15:00"],["17:30","21:30"]
I hope this information helps. In case it's not clear please let me know and I will try to improvise my question.
Thanks for your help in advance.
Regards,
Ankur
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45943928",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: linq to sql select new keyword and assign column alias name i wants to assign column alias to another column in linq to sql select new keyword my code is
var query=from d in db.tblAttributeDatas
select new
{
a=d.strValue,
b=a
};
but compiler give me error.
can not resolved symbol a
.
A: You cannot use alias that way.
You have to do it using let this way:
var query=from d in db.tblAttributeDatas
let str = d.strValue // hold value here
select new
{
a=str, // now assign here
b=str
};
A: assign the same value to b .. there is no harm..
var query = from d in db.tblAttributeDatas
select new
{
a = d.strValue,
b = d.strValue
};
A: Basically, you can't do this because of the nature of object initializers (which is: initializing objects using the object literal notation { ... }).
This simple line of code...
var x = new { a = 1, b = 2 };
...is executed in IL code as...
<>f__AnonymousType0<System.Int32,System.Int32>..ctor
So you see that the anonymous type is created having a two-parameter constructor. Suppose this constructor would be visible as...
class X
{
public X(int a, int b) { }
}
It's obvious you can't call this constructor by
var x = new X(1, a);
You must supply two values. One constructor argument can't "borrow" the value of the other argument.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30323540",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to make mysqli_query compare a variable identicly? Here is my code;
if ($_SERVER['QUERY_STRING']) {
$qrystring = $_SERVER['QUERY_STRING'];
$q = "SELECT * FROM accounts WHERE username = '$qrystring'";
$r = mysqli_query($dbc, $q);
if ($r) {
if (mysqli_num_rows($r) > 0) {
echo 'Yay account active';
}
else {
header('location: create');
}
@mysqli_free_result($r);
}}
Now for example when $qrystring = User, and in the database it equals user, mysql still compares it as correct. When I use the identical statement of === it breaks the code and it will not work?
I want it to be case sensitive.
Any ideas?
thanks.
A: See: http://dev.mysql.com/doc/refman/5.0/en/charset-binary-op.html
SELECT * FROM accounts WHERE BINARY username = '$qrystring'";
And also do what halfdan said! ;)
A: Please sanitize your $qrystring variable before passing it unfiltered to the database. (See SQL injection).
To make a case sensitive match you will have to use COLLATE on your column:
username = COLLATE latin1_general_cs = '$querystring'
From the manual:
Simple comparison operations (>=, >, =, <, <=, sorting, and grouping) are based on each character's “sort value.” Characters with the same sort value are treated as the same character. For example, if “e” and “é” have the same sort value in a given collation, they compare as equal.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5654132",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Openstack API not providing precise data I am using Openstack - Stein in CentOS 7.9
I was using python to collect data about the openstack nova performance, like server names and id in the openstack project, i have 3 instance(server) created, i can see all three instance in openstack cli, but when i connect to api mentioned in openstack, it provides no data or less data.
I refereed openstack documentation here
[root@centos-vm1 kavin(keystone_admin)]# openstack server list
+--------------------------------------+-----------------+--------+----------------------------------------+-------+----------+
| ID | Name | Status | Networks | Image | Flavor |
+--------------------------------------+-----------------+--------+----------------------------------------+-------+----------+
| 08cf6226-0303-4b4c-ba53-10af79b81dae | test_instance_3 | ACTIVE | test_networ_3=10.150.0.8 | | m1.tiny |
| 9986f205-82b3-4cbb-bcdc-fb32eab97c83 | test_instance_1 | ACTIVE | test_networ_2=10.100.0.5, x.x.x.x | | m1.small |
| d1c0f520-8540-432c-8fe1-554390fd79bf | test_instance_2 | ACTIVE | test_networ_1=10.50.0.8 | | m1.small |
+--------------------------------------+-----------------+--------+----------------------------------------+-------+----------+
My python code:
import requests,json
from six.moves.urllib.parse import urljoin
identity = {
"methods": ["password"],
"password": {
"user": {
"name": "admin",
"domain": { "id": "default" },
"password": "xxxxxxxxxxxxxxx"
}
}
}
OS_AUTH_URL = 'http://x.x.x.x:5000/v3'
data = {'auth': {'identity': identity}}
HEADERS = {'Content-Type': 'application/json', 'scope': 'unscoped'}
r = requests.post(
OS_AUTH_URL+'/auth/tokens',
headers = HEADERS,
json = data,
verify = False
)
auth_token = r.headers['X-Subject-Token'] # i got auth token
# server list
NOVA_URL="http://x.x.x.x:8774/v2.1"
HEADERS = {"X-Auth-Token" : str(auth_token)}
r = requests.get(
NOVA_URL+'/servers',
headers = HEADERS,
)
r.raise_for_status()
print(r.json())
Output :
{'servers': []}
help me, collect accurate data using api calls, thanks
A: According to api-ref List Servers doc, maybe you should add the project scope in the request.
By default the servers are filtered using the project ID associated with the authenticated request.
In my opinion, you could use openstacksdk to execute the operation, simply with the Connection object and list_servers method.
import openstack
conn = openstack.connect(
region_name='example-region',
auth_url='http://x.x.x.x:5000/v3/',
username='amazing-user',
password='super-secret-password',
project_id='33...b5',
domain_id='05...03'
)
servers = conn.list_servers()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73772437",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: using Collections.binarySearch to remove duplicates from a pre-populated ArrayList For an assignment, I have been given the task of reading in a pre-populated file as an ArrayList, sorting it, and removing all duplicates. I have been tasked to doing this with the binarySearch API. He's being rather specific. I have never done this before, and I'm not sure what I need to do to get Collections.binarySearch to work. The instructor gave me a start, but I know I am doing the parameters of Collections.binarySearch incorrectly, but I cannot for the life of me figure out the correct way to do this. If anyone can help out, it would be greatly appreciated.
This is what I have so far. If it matters at all, I can post the integers from set1.txt
public static void main(String[] args) {
collections program = new Collections();
program.readFile();
}//main
public void readFile() {
File f = new File("set1.txt");
try {
Scanner in = new Scanner(f);
while (in.hasNext()) {
int x = in.nextInt();
int index = Collections.binarySearch(x,0);
if (index == 1)
list.add(x);
}//while
Collections.sort(list);
in.close();
}//try
catch (IOException e) {
e.printStackTrace();
}//catch
}//readFile
A: Once you've sorted the list, duplicate elements (if any) will be next to one another, so you can simply iterate over the list removing any duplicate elements, no searching required. (We iterate backwards to avoid the awkwardness of deciding whether to increment the loop counter after removing an element.)
Collections.sort(list);
for (int i = list.size()-1; i >= 0; --i)
if (list.get(i).equals(list.get(i+1)))
list.remove(i);
But a more convenient way to ensure uniqueness is to create a Set holding the contents of your list, then create a new list from the set. The new list will contain the unique elements of the input list in the set's iteration order, so we can sort at the same time by using a TreeSet. (Using a HashSet to create the list, then calling Collections.sort(list) may or may not be faster, and the above solution may be faster still -- if it matters to you, profile to ensure it's a problem, then benchmark.)
list = new ArrayList<>(new TreeSet<>(list));
If reusing the input list is important (either as an arbitrary homework requirement or to minimize memory use/churn), you can do something like
Set<T> set = new TreeSet<>(list);
list.clear();
list.addAll(set);
A: Since the new Java is out, I might as well post this to help "future seekers".
ArrayList<String> newList = oldList.stream().distinct().collect(Collectors.toCollection(ArrayList::new));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24318202",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Get into Firebase complex object containing another object I've got Angular2 project connected directly with Firebase.
The structure of my database is presented in the picture below. So we've got couple of objects.
Main is orders, then the key od order, some extra information and another object "items" which contains several objects like 0, 1 etc. Each of them has a object called "product" which has some other parameters...
orders
-> datePlaced,
items
-> 0
-> quantity, totalPrice, product
->
imageUrl,
price,
title
My point is that when I'm creating "My Orders" tab, I'd like to get information of every item in specific order e.g. I see list of orders, and small button "View order", I click and I see details about this order with special key.
I prepared view with orders, buttons but I cannot take any objects form object orders, I've got a blank page.
order-details.component.ts
export class OrderDetailsComponent implements OnInit, OnDestroy {
order$;
userId: string;
userSubscription: Subscription;
constructor(private orderService: OrderService, private authService: AuthService) {}
async ngOnInit() {
this.userSubscription = this.authService.user$.subscribe(user => this.userId = user.uid);
this.order$ = this.authService.user$.switchMap(u => this.orderService.getOrdersByUser(u.uid));
}
ngOnDestroy() {
this.userSubscription.unsubscribe();
}
}
order-details.component.html
<div class="card" *ngIf="order$ | async as order">
<div class="card-body">
<h5 class="card-title">Your Order</h5>
<p class="card-text">You ordered {{ order.datePlaced | date }} items</p>
<ul class="list-group list-group-flush">
<li *ngFor="let order of order.shipping" class="list-group-item">
{{ order.city }} x {{ order.city }}
<div class="float-right">
{{ order.totalPrice | currency:'USD':'symbol' }}
</div>
</li>
<li class="list-group-item font-weight-bold">
Total
<div class="float-right">
{{ order.totalPrice | currency:'USD':'symbol' }}
</div>
</li>
</ul>
</div>
</div>
order.service.ts
export class OrderService {
constructor(private db: AngularFireDatabase, private shoppingCartService: ShoppingCartService) { }
async placeOrder(order) {
let result = await this.db.list('/orders').push(order);
this.shoppingCartService.clearCart();
return result;
}
getOrders() {
return this.db.list('/orders');
}
getOrdersByUser(userId: string) {
return this.db.list('/orders', {
query: {
orderByChild: 'userId',
equalTo: userId
}
});
}
}
How can I get every parameter from complex object "orders"?
A: I solved this by taking param routes in my order-details.component.ts and then a create function getOrder(id) in order service. When you have id of your order it's quite simple to take object from database.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50453188",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Reading XML data from SQL Server with Hear and Node values I have the following XML data in a file "Test1.xml":
<TextValuess>
<TextValues Name="Value1" Override="true" Type="String">
<DEV>Source=DEV;Catalog=DEV_DMT;Integrated Security=SSPI;</DEV>
<INT10>Source=LAB;Catalog=TST_INT10;Integrated Security=SSPI;</INT10>
<INT>Source=LAB1;Catalog=TST_INT1;Integrated Security=SSPI;</INT>
<INT2>Source=LAB10;Catalog=TST_INT12;Integrated Security=SSPI;</INT2>
</TextValues>
<TextValues Name="ENVIRONMENT" Override="true" Type="String">
<DEV>DEV</DEV>
<INT10>INT10</INT10>
<INT>INT1</INT>
<INT2>INT15</INT2>
</TextValues>
</TextValuess>
I am trying to read the INT10 values and Name of the <TextValues> tag. I need output like below in SQL Server:
Name Value
---- -----
Value1 LAB
Environment INT10
I have tried with these SQL statements. I was able to get either the Name value or the INT10 values.
Statement 1:
select c3.value('INT10[1]','varchar(50)')
from
(select cast(c1 as xml)
from OPENROWSET (BULK 'D:\Tasks\Test1.xml',SINGLE_BLOB) as T1(c1)) as T2(c2)
cross apply c2.nodes('/TextValuess/TextValues') T3(c3)
With this I was able to retrieve the values for INT10
Statement 2:
DECLARE @XML AS XML, @hDoc AS INT, @SQL NVARCHAR (MAX)
SELECT @XML = ' <TextValuess>
<TextValues Name="Value1" Override="true" Type="String">
<DEV>Source=DEV;Catalog=DEV_DMT;Integrated Security=SSPI;</DEV>
<INT10>Source=LAB;Catalog=TST_INT10;Integrated Security=SSPI;</INT10>
<INT>Source=LAB1;Catalog=TST_INT1;Integrated Security=SSPI;</INT>
<INT2>Source=LAB10;Catalog=TST_INT12;Integrated Security=SSPI;</INT2>
</TextValues>
<TextValues Name="ENVIRONMENT" Override="true" Type="String">
<DEV>DEV</DEV>
<INT10>INT10</INT10>
<INT>INT1</INT>
<INT2>INT15</INT2>
</TextValues>
</TextValuess>'
EXEC sp_xml_preparedocument @hDoc OUTPUT, @XML
SELECT Name ,INT10
FROM OPENXML(@hDoc, 'TextValuess/TextValues/INT10')
WITH
(
Name [varchar](50) '../@Name',
INT10 [varchar](100) '../@INT10'
)
With this I was able to retrieve only Name Information but not the INT10 Value.
A: Try this code:
-- declare a XML variable
DECLARE @XmlInput XML;
-- load the XML from the file into that XML variable
SELECT @XmlInput = CAST(c1 AS XML)
FROM OPENROWSET (BULK 'D:\Tasks\Test1.xml',SINGLE_BLOB) AS T1(c1)
-- extract the "Name" attribute and "INT10" element from the XML
SELECT
Name = XC.value('@Name', 'varchar(50)'),
Int10Value = XC.value('(INT10)[1]', 'varchar(100)')
FROM
@XmlData.nodes('/TextValuess/TextValues') AS XT(XC)
The call to .nodes() using the built-in, much preferred XQuery functionality (dump the OPENXML stuff - it's old and legacy and has memory leaks - XQuery is much easier to use, too!) returns a list of XML fragments - one for each match of the XPath expression in your document (here: one for each <TextValues> node under the root).
Then you reach into that XML fragment, and extract the name attribute (using the @Name expression), and the first (and only) <INT10> sub-element and convert those to "regular" values (with a datatype defined by the second parameter of the .value() call)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53845142",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Cannot open Utilities 'FilterOptions' I'm trying to run a code like this in Mathematica:
(* initialize everything *)
ClearAll["Global`*"]
Remove["Global`*"]
(* all *nb are in $WorkingDirectory *)
$WorkingDirectory = "/Users/U1/Workspace/BCOASMBH/Core/Fortran/"
(* Load Assumptions and format.m *)
Get[FileNameJoin[{$WorkingDirectory, "TemplateForHamiltonian.nb"}]];
However, I keep getting the error:
Get: Cannot open Utilities`FilterOptions`.
Needs: Context Utilities`FilterOptions` was not created when Needs was evaluated.
==========================
Example Script For Writing
==========================
filename = "testing.f"
stmp = OpenWrite[filename, FormatType -> OutputForm];
Write[stmp, FortranAssign[VariableInFortran, FormulaInMathematica, \
AssignPrecision -> 16, AssignTemporary -> {t, Array}]];
Close[stmp];
I'm new to the format.m package so I'm not sure what the error stems from or what can be done about it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62830064",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: c++ template member function with partial spezialisation outside class this code use a template member that work different for std::vector and other types. So far it works fine. But what is the correct syntax to define the get methode for std::vector outside the class ? i am aware about using traits and other helpers to make this working but i would like this simple solutions if there is an valid syntax.
#include <iostream>
#include <vector>
using namespace std;
struct s
{
template < class X > void get (X x)
{
cout << "inner\n";
};
template <class X> void get(std::vector<X> vec)
{
cout << "inline any vector\n";
}
};
int main ()
{
std::vector < int >vec;
std::vector< double> dvec;
s x;
x.get (1);
x.get (vec);
x.get(dvec);
return 0;
}
this seems not to work
template <class X> void s::get(std::vector<X> v)
{
}
A:
what is the correct syntax to define the get methode for std::vector outside the class ?
That would be to just declare it in the class template and then go ahead and define it outside:
struct s {
template < class X >
void get (X x) {
cout << "inner\n";
}
template <class X> // declaration
void get(std::vector<X> v);
};
template <class X> // definition
void s::get(std::vector<X> v) {}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66249376",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Create object set with multiple properties I have an object with multiple boolean (and integer) properties. I want to create a collection of objects with lot of different properties to have a good dataSet used for tests.
For example
public class A
{
public int value {get; set;} //want to try beetween 0 and 5
public bool foo {get; set;}
public bool bar {get; set;}
public bool boo {get; set;}
}
For this example I like to have a list with 6*2*2 = 24 elementw, with value = 0/1/2/3/4/5, foo = true/false, bar = true/false, but boo always false.
I could do that using 24 lines of code. But it's a lot and if I have one more bool it doubles the number of line.
I may be use one loop per property but I don't think it's a good way to have too many nested loop. I also might do this by reflection, but I think this is too much work, isn´t it?
I think there is another way to do it better but I don't find it.
A: What is your problem on this old loop-based approach?
var boolVals = new[] { true, false };
var intVals = new[] { 0, 1, 2, 3, 4, 5 };
var myList = new List<A>();
foreach(var foo in boolVals) {
foreach(var value in intVals) {
foreach(var bar in boolVals) {
foreach (var boo in boolVals) {
myList.Add(new A { value = value, foo = foo, bar = bar, boo = boo });
}
}
}
}
You have to add a new nesting for every property you add and loop the appropriate set of values this property might have.
This appraoch fils every possible permutation of your values within a few lines of easy to read code.
Of course it looks a bit ugly. But it increases only by one further nesting on every added property.
A: Since you don't explicitly ask for an all-permutation solution, I'd suggest going random. You could employ the constructor...
public class A
{
public int value {get; set;} //want to try beetween 0 and 5
public bool foo {get; set;}
public bool bar {get; set;}
public bool boo {get; set;}
public A()
{
// initialize value, foo, bar, boo with desired default / random here
}
}
var myList = new List<A>();
for (int i=0; i<=24; i++) myLyst.add(new A());
this seems quite readable and maintainable to me. You could also pass an argument to new A() and use it to calculate the n-th permutation if needed, but I guess this goes beyond the scope of the question.
A: You can do this using reflection and a data structure that keeps track of the value (via equivalent indices) for each property
This automatically accounts for all properties in the class and you can extend it for other property types by simply adding to the ValuesFor dictionary
using System;
using System.Collections.Generic;
using System.Reflection;
public class Program
{
private static Dictionary<string, object[]> ValuesFor = new Dictionary<string, object[]>()
{
{ typeof(int).ToString(), new object[] { 0, 1, 2, 3, 4, 5 } },
{ typeof(bool).ToString(), new object[] { true, false } }
};
public static void Main()
{
var properties = typeof(A).GetProperties(BindingFlags.Instance | BindingFlags.Public);
int[] valueIndices = new int[properties.Length];
do
{
createObject(properties, valueIndices);
} while (setNext(properties, valueIndices));
Console.ReadKey();
}
/// <summary>
/// This updates the valueIndex array to the next value
/// </summary>
/// <returns>returns true if the valueIndex array has been updated</returns>
public static bool setNext(PropertyInfo[] properties, int[] valueIndices)
{
for (var i = 0; i < properties.Length; i++)
{
if (valueIndices[i] < ValuesFor[properties[i].PropertyType.ToString()].Length - 1) {
valueIndices[i]++;
for (var j = 0; j < i; j++)
valueIndices[j] = 0;
return true;
}
}
return false;
}
/// <summary>
/// Creates the object
/// </summary>
public static void createObject(PropertyInfo[] properties, int[] valueIndices)
{
var a = new A();
for (var i = 0; i < properties.Length; i++)
{
properties[i].SetValue(a, ValuesFor[properties[i].PropertyType.ToString()][valueIndices[i]]);
}
print(a, properties);
}
public static void print(object a, PropertyInfo[] properties)
{
Console.Write("Created : ");
for (var i = 0; i < properties.Length; i++)
Console.Write(properties[i].Name + "=" + properties[i].GetValue(a) + " ");
Console.Write("\n");
}
public class A
{
public int value { get; set; }
public bool foo { get; set; }
public bool bar { get; set; }
public bool boo { get; set; }
}
}
Currently createObject, just creates the object and calls print to print out the object. Instead, you could add it to a collection and run your tests with it (or directly put your tests instead of print)
Fiddle - https://dotnetfiddle.net/oeLqc5
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35840905",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Label with as: :boolean value in simple_form I have the following code :
<%= profile.simple_fields_for :options, OpenStruct.new(@user.profile.options) do |option| %>
<div class="hint">
<%= option.label :display_profile %>
<%= option.input :display_profile,
as: :boolean,
label: false
%>
</div>
But in my html code the label is in the input
If I remove as: :boolean in my form, the html is good (but It's not a boolean field)
How can I fix it ?
** EDIT **
I updated my code to :
<%= f.simple_fields_for :profile do |profile| %>
<%= profile.simple_fields_for :options, OpenStruct.new(@user.profile.options) do |option| %>
<div class="hint">
<%= option.label :display_profile %>
<%= option.input :display_profile,
as: :boolean,
boolean_style: :inline,
label: false
</div>
But now I have two <div> How can I remove : <div class="checkbox"> ?
<div class="hint">
<label class="string required" for="user_profile_attributes_options_display_profile">Afficher votre profil</label>
<div class="field boolean optional user_profile_options_display_profile">
<div class="checkbox">
<input name="user[profile_attributes][options][display_profile]" type="hidden" value="0" />
<input class="boolean optional" type="checkbox" value="1" checked="checked" name="user[profile_attributes][options][display_profile]" id="user_profile_attributes_options_display_profile" />
</div>
</div>
</div>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60114778",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to send last debounced request while request param is changing? I was using React.useCallBack() to produced a debounced function, something like:
const debouncedFunction = React.useCallback(
_.debounce(function, 2000),
[someInputValue]
)
and trigger it using React.useEffect(), like:
React.useEffect(() => {
debouncedFunction();
},[someInputValue])
When I change someInputValue(like typing "hi" in a Input component) in a short time(less than 2 seconds), 2 requests were sent, one with param "h" and one with param "hi".
I understand this was due to debouncedFunction was recreated every time someInputValue was changed, so multiple debounced requests cannot be merged into a single one. So what should I do to send one "merged" request with param "hi"?
A: Without using an extra lib:
const useDebounce = (value, delay, fn) => { //--> custom hook
React.useEffect(() => {
const timeout = setTimeout(() => {
fn();
}, delay);
return ()=> {
clearTimeout(timeout);
}
}, [value]);
};
SomeComponent.js
const [someInputValue, setsomeInputValue] = useState(null);
const fn = ()=> console.log(someInputValue);
useDebounce(someInputValue, 2000, fn);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65774515",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is it possible to force ignore the :hover pseudoclass for iPhone/iPad users? I have some css menus on my site that expand with :hover (without js)
This works in a semi-broken way on iDevices, for example a tap will activate the :hover rule and expand the menu, but then tapping elsewhere doesn't remove the :hover. Also if there is a link inside the element that is :hover'ed, you have to tap twice to activate the link (first tap triggers :hover, second tap triggers link).
I've been able to make things work nicely on iphone by binding the touchstart event.
The problem is that sometimes mobile safari still chooses to trigger the :hover rule from the css instead of my touchstart events!
I know this is the problem because when I disable all the :hover rules manually in the css, mobile safari works great (but regular browsers obviously don't anymore).
Is there a way to dynamically "cancel" :hover rules for certain elements when the user is on mobile safari?
See and compare iOS behavior here: http://jsfiddle.net/74s35/3/
Note: that only some css properties trigger the two-click behavior, e.g. display:none; but not background: red; or text-decoration: underline;
A: I found that ":hover" is unpredictable in iPhone/iPad Safari. Sometimes tap on element make that element ":hover", while sometimes it drifts to other elements.
For the time being, I just have a "no-touch" class at body.
<body class="yui3-skin-sam no-touch">
...
</body>
And have all CSS rules with ":hover" below ".no-touch":
.no-touch my:hover{
color: red;
}
Somewhere in the page, I have javascript to remove no-touch class from body.
if ('ontouchstart' in document) {
Y.one('body').removeClass('no-touch');
}
This doesn't look perfect, but it works anyway.
A: :hover isn't the issue here. Safari for iOS follows a very odd rule. It fires mouseover and mousemove first; if anything is changed during these events, 'click' and related events don't get fired:
mouseenter and mouseleave appear to be included, though they're not specified in the chart.
If you modify anything as a result of these events, click events won't get fired. That includes something higher up in the DOM tree. For example, this will prevent single clicks from working on your website with jQuery:
$(window).on('mousemove', function() {
$('body').attr('rel', Math.random());
});
Edit: For clarification, jQuery's hover event includes mouseenter and mouseleave. These will both prevent click if content is changed.
A: There are basically three scenarios:
*
*User only has a mouse/pointer device and can activate :hover
*User only has a touchscreen, and can not activate :hover elements
*User has both a touchscreen and a pointer device
The originally accepted answer works great if only the first two scenarios are possible, where a user has either pointer or touchscreen. This was common when the OP asked the question 4 years ago. Several users have pointed out that Windows 8 and Surface devices are making the third scenario more likely.
The iOS solution to the problem of not being able to hover on touchscreen devices (as detailed by @Zenexer) is clever, but can cause straightforward code to misbehave (as noted by the OP). Disabling hover only for touchscreen devices means that you will still need to code a touchscreen friendly alternative. Detecting when a user has both pointer and touchscreen further muddies the waters (as explained by @Simon_Weaver).
At this point, the safest solution is to avoid using :hover as the only way a user can interact with your website. Hover effects are a good way of indicating that a link or button is actionable, but a user should not be required to hover an element to perform an action on your website.
Re-thinking “hover” functionality with touchscreens in mind has a good discussion about alternative UX approaches. The solutions provided by the answer there include:
*
*Replacing hover menus with direct actions (always visible links)
*Replacing on-hover menus with on-tap menus
*Moving large amounts of on-hover content into a separate page
Moving forward, this will probably be the best solution for all new projects. The accepted answer is probably the second best solution, but be sure to account for devices that also have pointer devices. Be careful not to eliminate functionality when a device has a touchscreen just to work around iOS's :hover hack.
A: A better solution, without any JS, css class and viewport check: you can use Interaction Media Features (Media Queries Level 4)
Like this:
@media (hover) {
// properties
my:hover {
color: red;
}
}
iOS Safari supports it
More about:
https://www.jonathanfielding.com/an-introduction-to-interaction-media-features/
A: The browser feature detection library Modernizer includes a check for touch events.
It’s default behavior is to apply classes to your html element for each feature being detected. You can then use these classes to style your document.
If touch events are not enabled Modernizr can add a class of no-touch:
<html class="no-touch">
And then scope your hover styles with this class:
.no-touch a:hover { /* hover styles here */ }
You can download a custom Modernizr build to include as few or as many feature detections as you need.
Here's an example of some classes that may be applied:
<html class="js no-touch postmessage history multiplebgs
boxshadow opacity cssanimations csscolumns cssgradients
csstransforms csstransitions fontface localstorage sessionstorage
svg inlinesvg no-blobbuilder blob bloburls download formdata">
A: Some devices (as others have said) have both touch and mouse events. The Microsoft Surface for example has a touch screen, a trackpad AND a stylus which actually raises hover events when it is hovered above the screen.
Any solution that disables :hover based on the presence of 'touch' events will also affect Surface users (and many other similar devices). Many new laptops are touch and will respond to touch events - so disabling hovering is a really bad practice.
This is a bug in Safari, there's absolutely no justification for this terrible behavior. I refuse to sabotage non iOS browsers because of a bug in iOS Safari which has apparently been there for years. I really hope they fix this for iOS8 next week but in the meantime....
My solution:
Some have suggested using Modernizr already, well Modernizr allows you to create your own tests. What I'm basically doing here is 'abstracting' the idea of a browser that supports :hover into a Modernizr test that I can use throughout my code without hardcoding if (iOS) throughout.
Modernizr.addTest('workinghover', function ()
{
// Safari doesn't 'announce' to the world that it behaves badly with :hover
// so we have to check the userAgent
return navigator.userAgent.match(/(iPad|iPhone|iPod)/g) ? false : true;
});
Then the css becomes something like this
html.workinghover .rollover:hover
{
// rollover css
}
Only on iOS will this test fail and disable rollover.
The best part of such abstraction is that if I find it breaks on a certain android or if it's fixed in iOS9 then I can just modify the test.
A: Adding the FastClick library to your page will cause all taps on a mobile device to be turned into click events (regardless of where the user clicks), so it should also fix the hover issue on mobile devices. I edited your fiddle as an example: http://jsfiddle.net/FvACN/8/.
Just include the fastclick.min.js lib on your page, and activate via:
FastClick.attach(document.body);
As a side benefit, it will also remove the annoying 300ms onClick delay that mobile devices suffer from.
There are a couple of minor consequences to using FastClick that may or may not matter for your site:
*
*If you tap somewhere on the page, scroll up, scroll back down, and then release your finger on the exact same position that you initially placed it, FastClick will interpret that as a "click", even though it's obviously not. At least that's how it works in the version of FastClick that I'm currently using (1.0.0). Someone may have fixed the issue since that version.
*FastClick removes the ability for someone to "double click".
A: The JQuery version
in your .css use
.no-touch .my-element:hover
for all your hover rules
include JQuery and the following script
function removeHoverState(){
$("body").removeClass("no-touch");
}
Then in body tag add
class="no-touch" ontouchstart="removeHoverState()"
as soon as the ontouchstart fires the class for all hover states is removed
A: I agree disabling hover for touch is the way to go.
However, to save yourself the trouble of re-writing your css, just wrap any :hover items in @supports not (-webkit-overflow-scrolling: touch) {}
.hover, .hover-iOS {
display:inline-block;
font-family:arial;
background:red;
color:white;
padding:5px;
}
.hover:hover {
cursor:pointer;
background:green;
}
.hover-iOS {
background:grey;
}
@supports not (-webkit-overflow-scrolling: touch) {
.hover-iOS:hover {
cursor:pointer;
background:blue;
}
}
<input type="text" class="hover" placeholder="Hover over me" />
<input type="text" class="hover-iOS" placeholder="Hover over me (iOS)" />
A: Instead of only having hover effects when touch is not available I created a system for handling touch events and that has solved the problem for me. First, I defined an object for testing for "tap" (equivalent to "click") events.
touchTester =
{
touchStarted: false
,moveLimit: 5
,moveCount: null
,isSupported: 'ontouchend' in document
,isTap: function(event)
{
if (!this.isSupported) {
return true;
}
switch (event.originalEvent.type) {
case 'touchstart':
this.touchStarted = true;
this.moveCount = 0;
return false;
case 'touchmove':
this.moveCount++;
this.touchStarted = (this.moveCount <= this.moveLimit);
return false;
case 'touchend':
var isTap = this.touchStarted;
this.touchStarted = false;
return isTap;
default:
return true;
}
}
};
Then, in my event handler I do something like the following:
$('#nav').on('click touchstart touchmove touchend', 'ul > li > a'
,function handleClick(event) {
if (!touchTester.isTap(event)) {
return true;
}
// touch was click or touch equivalent
// nromal handling goes here.
});
A: Thanks @Morgan Cheng for the answer, however I've slightly modified the JS function for getting the "touchstart" (code taken from @Timothy Perez answer), though, you need jQuery 1.7+ for this
$(document).on({ 'touchstart' : function(){
//do whatever you want here
} });
A: Given the response provided by Zenexer, a pattern that requires no additional HTML tags is:
jQuery('a').on('mouseover', function(event) {
event.preventDefault();
// Show and hide your drop down nav or other elem
});
jQuery('a').on('click', function(event) {
if (jQuery(event.target).children('.dropdown').is(':visible') {
// Hide your dropdown nav here to unstick
}
});
This method fires off the mouseover first, the click second.
A: For those with common use case of disabling :hover events on iOS Safari, the simplest way is to use a min-width media query for your :hover events which stays above the screen width of the devices you are avoiding. Example:
@media only screen and (min-width: 1024px) {
.my-div:hover { // will only work on devices larger than iOS touch-enabled devices. Will still work on touch-enabled PCs etc.
background-color: red;
}
}
A: For someone still looking for a solution if none of the above worked,
Try this,
@media (hover: hover)
{
.Link:hover
{
color:#00d8fe;
}
}
This hover pseudo will only be applied for devices with pointers and works normal on touch devices with just .active classes.
A: Just look at the screen size....
@media (min-width: 550px) {
.menu ul li:hover > ul {
display: block;
}
}
A: heres the code you'll want to place it in
// a function to parse the user agent string; useful for
// detecting lots of browsers, not just the iPad.
function checkUserAgent(vs) {
var pattern = new RegExp(vs, 'i');
return !!pattern.test(navigator.userAgent);
}
if ( checkUserAgent('iPad') ) {
// iPad specific stuff here
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2741816",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "98"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.