qid
int64
10
74.7M
question
stringlengths
15
26.2k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
27
28.1k
response_k
stringlengths
23
26.8k
31,607,196
For some entities we need to keep loads (thousands) of detached enties permanently in memory. Many of their attributes are from a limited set of strings (though not limited enough to put it into an enumeration). Is it possible to have hibernate use String.intern for those attributes to save space? Ideally that should work via an annotation I could put on each of those attributes, or something easily changeable, without confusing the source code too much by this implementation concern.
2015/07/24
[ "https://Stackoverflow.com/questions/31607196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21499/" ]
As you suggest yourself, it's perfectly doable with a JPA attribute converter. You could do it on a general level by using `autoApply = true` on the converter, or you could do it on a field by field level with the `@Convert` annotation. ``` import javax.persistence.AttributeConverter; import javax.persistence.Converter; @Converter(autoApply = true) public class StringInternConverter implements AttributeConverter<String, String> { @Override public String convertToDatabaseColumn(String attribute) { return attribute; } @Override public String convertToEntityAttribute(String dbData) { return dbData != null? dbData.intern(): null; } } ``` Tested with Hibernate 5.2.10 and works like a charm!
1) You can use property access for the critical properties and intern the strings in the setters: ``` public void setFoo(String foo) { this.foo = foo != null ? foo.intern() : null; } ``` 2) If the above solution is tedious (you may have lots of such `String` properties), then you could register a [Hibernate interceptor](https://docs.jboss.org/hibernate/core/4.3/javadocs/org/hibernate/Interceptor.html) and intern all of the `String` fields using reflection: ``` for (Field field : getDeclaredFields(entity)) { if (!isStaticOrFinal(field)) { field.setAccessible(true); Object value = field.get(entity); if (value instanceof String) { field.set(entity, ((String) value).intern()); } } } private List<Field> getDeclaredFields(Object object) { List<Field> result = new ArrayList<Field>(Arrays.asList(object.getClass().getDeclaredFields())); for (Class<?> superclass = object.getClass().getSuperclass(); superclass != null; superclass = superclass.getSuperclass()) { result.addAll(Arrays.asList(superclass.getDeclaredFields())); } return result; } private boolean isStaticOrFinal(Field field) { return ((Modifier.STATIC | Modifier.FINAL) & field.getModifiers()) != 0; } ``` You can execute this in the `onSave` and `onLoad` interceptor methods.
2,046,502
I want to create a file named "new text document.txt" in the folder `%tv%` using a batch file ( `*.bat`). This is my batch file: ``` set tv=D:\prog\arpack96\ARPACK\SRC cd "%tv%" @CON >> "new text document.txt" set tv= ``` Although I can really create the file in `%tv%`, but when I run the above batch file, I will get an error message saying > > ' ' is not recognized as an internal > or external command, operable program > or batch file. > > > Is there anyway to get rid of this error message? Or I am creating the file using the wrong command?
2010/01/12
[ "https://Stackoverflow.com/questions/2046502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3834/" ]
In order to get a truly empty file without having to provide user interaction, you can use the `set /p` command with a little trickery: ``` set tv=c:\documents and settings\administrator cd "%tv%" <nul >"new text document.txt" (set /p tv=) ``` The `set /p` asks the user for input into the `tv` variable after outputting the prompt after the `=` character. Since the prompt is empty, no prompt is shown. Since you're reading from nul, it doesn't wait for user interaction. And you can store the empty string straight into `tv` thus removing the need to unset it. --- Actually, after some more thought, there's an easier way. I've used that `set /p` trick in the past since it's the only way I know of echoing text without a newline being added (great for progress bars in the console). But if all you want is an empty file, you can probably get away with: ``` copy /y nul "new text document.txt" ``` The `copy` simply copies the contents of the `nul` device (effectively an empty file) to your new file name. The `/y` is to ensure it's overwritten without bothering the user.
Create an empty file from a \*.bat file - this worked for me. ``` echo off > test.txt ```
66,604,703
**HTML** ``` <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>sample</title> </head> <style > body{ background: black; } div{ background : red; height: 200px; margin : 20px 100px; width : auto; display: none; } button{ color: red; font-weight:bold; background : grey; padding : 5px 20px; font-size : 1rem; } </style> <body> <div id="myDIV"> </div> <button type="button" onclick=myFunction() name="button">CLICK ME</button> </body> <script> function myFunction(){ document.getElementById("myDIV").style.display = "block"; } </script> </html> ``` ***QUESTION*** As you can see, when i click the button, the div appear. But this i want the dev to appear in a smooth manner. I tried [this](https://stackoverflow.com/questions/635706/how-to-scroll-to-an-element-inside-a-div) solution but it did'nt work for me.
2021/03/12
[ "https://Stackoverflow.com/questions/66604703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15135917/" ]
You can use **CSS transition** to make it *smooth*. If you want **transitions** you can't use `display: none;` to hide it because with `display` it is completely **hidden** or completely **visible**, instead, you can use `height` or `opacity`. To toggle its visibility, I also recommend toggling a class with the styles for the shown state instead of settings them directly in the script, it makes it easier to maintain and to add more visual effects ```js function myFunction() { document.getElementById("myDIV").classList.toggle("shown") } ``` ```css body { background: black; } .shown { height: 200px; opacity: 1; } div { background: red; height: 0px; opacity: 0; margin: 20px 100px; width: auto; transition: all 1s; } button { color: red; font-weight: bold; background: grey; padding: 5px 20px; font-size: 1rem; } ``` ```html <div id="myDIV"> </div> <button type="button" onclick=myFunction() name="button">CLICK ME</button> ```
Here is a solution using opacity. It seems like a good use case because it also eliminates content shifting in this example (the button changing position). ```js function myFunction(){ document.getElementById("myDIV").classList.add('div-show'); } ``` ```css body{ background: black; } div{ background : red; height: 200px; margin : 20px 100px; width : auto; //display: none; opacity:0; transition:opacity.3s; } .div-show{ opacity:1; } button{ color: red; font-weight:bold; background : grey; padding : 5px 20px; font-size : 1rem; } ``` ```html <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>sample</title> </head> <body> <div id="myDIV"> </div> <button type="button" onclick=myFunction() name="button">CLICK ME</button> </body> </html> ```
6,794,156
Basically this line of code does not work and I'm not quite sure as to why: ``` String[] stringHolder = string.split("_(B"); ``` I get this error: Unclosed group near index 3 This line of code works however: ``` String[] stringHolder = string.split("_B"); ``` So this leads me to believe that it's caused by the "(". Can anyone tell me how to make this work?
2011/07/22
[ "https://Stackoverflow.com/questions/6794156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/783401/" ]
The `(` is a special character in regex, you need to escape it with a `\`. And since `\` needs to be escaped inside a string literal, you add two: ``` String[] stringHolder = string.split("_\\(B"); ``` More info: [Use Round Brackets for Grouping](http://www.regular-expressions.info/brackets.html)
The `split()` method takes a regular expression, not a string literal. So you need to escape the opening bracket/parenthesis: ``` String[] stringHolder = string.split("_\\(B"); ``` Brackets are special characters in regular expressions, used for groups.
17,276,296
I am just finished with my script in Python and i want my collegues to use it as well. It runs in python 2.7 Windows 7 64 bit professional env. Now comes the question: How can i make them use my script in an easy way? * First choice is the hard way, making them install python on their machines and then install paramiko,Tkinter . I had a very hard time finding & installing these modules (especially for windows binary files) and do not want to suffer from the same issues again. * I am a newbie in this environment and I think there would be practical solutions to this problem. So i wanted to ask you guys , any ideas appreciated.
2013/06/24
[ "https://Stackoverflow.com/questions/17276296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2516297/" ]
You need to convert it to an executable. py2exe is a module that does this for you. Follow the tutorial [here](http://www.py2exe.org/).
Pyinstaller is the python .exe maker that I've had the most success with --> <http://www.pyinstaller.org/>
4,831
I have a project where I aim to create a retro arcade game cabinet, the technology would be ~1988. For now I am planning to only simulate the system on my PC in order to develop the game. The dedicated hardware, if ever created, will come later. **However I have to know what kind of video hardware to simulate in order to really start development.** My requirements would be the following (nothing is set in stone, those are just general ideas): * Composite output (possibly encoded from RGB with an external chip), X resolution 256 px, Y resolution between 192 and 240 px (more than 224 lines would be hidden by NTSC overscan anyway I guess) * One fully scrollable background layer capable of 3BP or 4BP graphics with either 8x8 or 16x16 character tiles. * *Possibly* one simpler non-scrollable background layer of 2BP graphics that could serve for backdrops or text overlays * A lot of 3BP or 4BP sprites, at least 16x16 in size (if larger is available it doesn't hurt) (if there's enough sprites available then only one background layer is necessary) * Palette: At least 32 colours simultaneously - (if either sprites or BG graphics are in 4BP it's enough to have a single palette (Sega Master System style)) Ideally I'd want to be able to create the system with parts if the need ever arises. If that is the case, I'd like to use retro parts, through-hole components and +5V parts whenever possible. **Was there a video chip available at that time that could be used?**
2017/10/04
[ "https://retrocomputing.stackexchange.com/questions/4831", "https://retrocomputing.stackexchange.com", "https://retrocomputing.stackexchange.com/users/2123/" ]
The [Yamaha V9958](https://en.wikipedia.org/wiki/Yamaha_V9958) video chip was used in the MSX2+ (1988) and MSX Turbo-R (1990). It supports a resolution of 256x212 with up to 19,268 colors, 32 4BPP sprites, and horizontal and vertical scroll registers. It's a successor of the TMS9918 which was the basis of the video chip used in the Sega Master System that you mentioned.
Assuming you're happy with a forward-looking 1988 machine, how about the [TMS34010](https://en.wikipedia.org/wiki/TMS34010) (from 1986) or '020 (from 1988)? It's a RISC CPU/GPU combination, so you're supposed to supply a frame buffer, and its instruction set includes 2d drawing. It became the basis of the solid polygon Hard Drivin' and STUN Runner in 1989 but was also later found in heavy sprite movers like Smash TV and Mortal Kombat, so it's adaptable to either style. Probably your easiest solution for interfacing to one would be to pick up one of the ISA TIGA boards — that'll get you the processor and a frame buffer, behind a well-defined bus for which I'm sure a connector would be locatable.
45,931,291
I have 2 view controller. 1. ViewController (VC) 2. WebViewController (WVC) In VC I click on a button and WVC is shown. After successfully completing all tasks in WVC, I want to show VC and execute a particular function in VC. Now, Storyboard contains some objects and add to VC using click and drag. Initially, it has some values(not nil). I Click on button, WVC is pushed, After completing all task in WVC, VC is pushed. Now some values in VC is nil. error,welcome (`UILabel`, `UIView`) is nil... And also is want to call a function in VC. How it is possible.? Code ---- ViewController.swift -------------------- ``` class LoginController:UIViewController,UITextFieldDelegate{ @IBOutlet weak var password: UITextField! @IBOutlet weak var username: UITextField! @IBOutlet weak var error: UILabel! @IBOutlet weak var welocome: UILabel! ...... @IBAction func BtnClicked(sender: AnyObject) { let webViewCnt = self.storyboard!.instantiateViewControllerWithIdentifier("WebViewController") as UIViewController self.navigationController?.pushViewController(webViewCnt, animated: true) } func doSomeProcess(){ } } ``` WebViewController.swift ----------------------- ``` class WebViewController: UIViewController, UITextFieldDelegate,UIWebViewDelegate { override func viewDidLoad() { super.viewDidLoad() webView.delegate = self self.start() } func start(){ ---- do some process ---- dispatch_async(dispatch_get_main_queue(), { () -> Void in let ViewCont = self.storyboard!.instantiateViewControllerWithIdentifier("LoginController") as UIViewController self.navigationController?.pushViewController(ViewCont, animated: true) ViewController().doSomeProcess() // call viewcontroller doSomeProcess() function } }) } } ```
2017/08/29
[ "https://Stackoverflow.com/questions/45931291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5597739/" ]
**Try to pop:** In this start() method just replace a line `self.navigationController?.popViewController(animated: true)` instead of pushing the ViewController. ``` func start(){ ---- do some process ---- dispatch_async(dispatch_get_main_queue(), { () -> Void in let ViewCont = self.storyboard!.instantiateViewControllerWithIdentifier("LoginController") as UIViewController self.navigationController?.pushViewController(ViewCont, animated: true) ViewController().doSomeProcess() // call viewcontroller doSomeProcess() function } }) } ``` **Reason:** When you are pushing to any ViewController, The storyboard will create a new reference of ViewController and the OOP's says every object has its own properties and method so that's why your pushing view controller properties may be `nil` assume that your `username: UITextField!` text will be nil due to separate instance of ViewController. For calling the function of your view-controller you have to implement the [delegate](https://stackoverflow.com/questions/40501780/examples-of-delegates-in-swift-3) if it is not for every time else you may work in `viewwillappear`.
From my understanding, probably what you want is to dismiss `WVC` and go back to `VC`. in `WebViewController`'s `start()`: ``` self.navigationController?.popViewController(animated: true) ``` and after pop, you need to execute `doSomeProcess()` function. There're several ways to do this and I'll introduce one here. in `ViewController`, implement `UINavigationControllerDelegate`: ``` func navigationController(_ navigationController: UINavigationController, animationCOntrollerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewCOntroller) -> UIViewControllerAnimatedTransitioning? { switch operation { case .pop: let to = toVC as! ViewController to.doSomeProcess() default: break } return nil } ``` of course you'll need ``` self.navigationController?.delegate = self ``` inside `VC`'s `viewDidLoad()` as well.
31,749,593
I want to find the parameters of `ParamGridBuilder` that make the best model in CrossValidator in Spark 1.4.x, In [Pipeline Example](http://spark.apache.org/docs/latest/ml-guide.html#example-model-selection-via-cross-validation) in Spark documentation, they add different parameters (`numFeatures`, `regParam`) by using `ParamGridBuilder` in the Pipeline. Then by the following line of code they make the best model: ``` val cvModel = crossval.fit(training.toDF) ``` Now, I want to know what are the parameters (`numFeatures`, `regParam`) from `ParamGridBuilder` that produces the best model. I already used the following commands without success: ``` cvModel.bestModel.extractParamMap().toString() cvModel.params.toList.mkString("(", ",", ")") cvModel.estimatorParamMaps.toString() cvModel.explainParams() cvModel.getEstimatorParamMaps.mkString("(", ",", ")") cvModel.toString() ``` Any help? Thanks in advance,
2015/07/31
[ "https://Stackoverflow.com/questions/31749593", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4288229/" ]
This is the ParamGridBuilder() ``` paraGrid = ParamGridBuilder().addGrid( hashingTF.numFeatures, [10, 100, 1000] ).addGrid( lr.regParam, [0.1, 0.01, 0.001] ).build() ``` There are 3 stages in pipeline. It seems we can assess parameters as the following: ``` for stage in cv_model.bestModel.stages: print 'stages: {}'.format(stage) print stage.params print '\n' stage: Tokenizer_46ffb9fac5968c6c152b [Param(parent='Tokenizer_46ffb9fac5968c6c152b', name='inputCol', doc='input column name'), Param(parent='Tokenizer_46ffb9fac5968c6c152b', name='outputCol', doc='output column name')] stage: HashingTF_40e1af3ba73764848d43 [Param(parent='HashingTF_40e1af3ba73764848d43', name='inputCol', doc='input column name'), Param(parent='HashingTF_40e1af3ba73764848d43', name='numFeatures', doc='number of features'), Param(parent='HashingTF_40e1af3ba73764848d43', name='outputCol', doc='output column name')] stage: LogisticRegression_451b8c8dbef84ecab7a9 [] ``` However, there is no parameter in the last stage, logiscRegression. We can also get ***weight*** and ***intercept*** parameter from logistregression like the following: ``` cv_model.bestModel.stages[1].getNumFeatures() 10 cv_model.bestModel.stages[2].intercept 1.5791827733883774 cv_model.bestModel.stages[2].weights DenseVector([-2.5361, -0.9541, 0.4124, 4.2108, 4.4707, 4.9451, -0.3045, 5.4348, -0.1977, -1.8361]) ``` Full exploration: <http://kuanliang.github.io/2016-06-07-SparkML-pipeline/>
[![enter image description here](https://i.stack.imgur.com/7LL7l.png)](https://i.stack.imgur.com/7LL7l.png) If java,see this debug show; ``` bestModel.parent().extractParamMap() ```
13,235,317
I want to use the new Log4J 2 - Java Logging Framework. Everything work fine, but I tried since a hour to load a custom configuration file to configure the logging (like log level). This is my log4j2.xml: ``` <?xml version="1.0" encoding="UTF-8"?> <configuration status="OFF"> <appenders> <Console name="Console" target="SYSTEM_OUT"> <PatternLayout pattern="%d{HH:mm:ss} [%t] %-5level %logger{36} - %msg%n"/> </Console> </appenders> <loggers> <root level="error"> <appender-ref ref="Console"/> </root> </loggers> </configuration> ``` I tried the following, but nothing works: * Move the log4j2.xml file so it's located in the default package. * Move the log4j2.xml file anywhere in the project * Name the log4j2.xml file as "log4j.xml" * Create a folder in your project, place your log4j2.xml file there and add that folder to your runtime classpath Since the [official website](http://logging.apache.org/log4j/2.x/) can't help me, I hope you can help me get Log4j 2 working with my configuration file.
2012/11/05
[ "https://Stackoverflow.com/questions/13235317", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3597614/" ]
TIP : To use custom log4j files. (Rather default "log4j2.xml" thingie). It might be useful to have multiple configurations in some instances. Just in case if any one using maven and wish to configure log4j2, Here is what you need in your pom.xml : ``` <systemProperties> <property> <name>/log4j.configuration</name> <value>.../../Foo-log4j.xml</value> </property> </systemProperties> ``` By default, "log4j2.xml" is the file name expected. But however, we can override that by setting log4j.configuration system property. In the above example, I have used custom configuration file as "Foo-log4j.xml". You can do the same via CLI : ``` -Dlog4j.configuration="Foo-log4j.xml" ```
My 2 cents: Software system: log4j 2, NetBeans and TestNG. I had the same problem, but with the testing environment. In default, (that is, in log4j2.xml file located in src/) the logging level is set to error. But when running the tests, I want the logging to be trace. And, of course logged to some more or less hardcoded file. That is, originally I did something like: ``` public class someTestClass { static final Logger log=LogManager.getLogger("test.someTestClass"); ...... @Test public void SomeMethod(){ System.setProperty("log4j.configurationFile", "resources/log4j2_conf.xml"); log.trace("This will not show because the default logging level is ERROR and the resources/log4j2_conf.xml is not loaded"); } ``` The problem is that by the time the System.setProperty instruction will be executed, the log4j will be already be set (That is, the static final Logger log =... will be executed first.) What I did, is use the @BeforeClass like this: ``` public class someTestClass { Logger log; @BeforeClass public void setLogger(){ SetEnv.SetEnvironment(); log = LogManager.getLogger("TestRealClientRealServer"); } ...... @Test public void SomeMethod(){ log.trace("This will show, because in log4j2_conf.xml the root level is set to TRACE"); } } ``` BTW, resources/ can be placed in test packages so you don't ship the "test" log4j setup. Hope it helps
101,755
I have a trigger on "Opportunity" object which on record update also updates it "OpportunityLineItem" records. We have a validation rule on "OpportunityLineItem" that if a field is blank the error should be thrown. Now in my org we have many "Opportunity" records with its corresponding "OLI" records with that field as blank. So now whenever the trigger fires we receive an exception like below. [![enter image description here](https://i.stack.imgur.com/VOfcE.png)](https://i.stack.imgur.com/VOfcE.png) **Is there any way to handle this exception in a more refined way something like below ?** [![enter image description here](https://i.stack.imgur.com/e4tV7.png)](https://i.stack.imgur.com/e4tV7.png) Below is the trigger code and class. ``` trigger Opportunity_CloseDate_Update on Opportunity (after update) { OpportunityProductScheduleHelper helper = new OpportunityProductScheduleHelper(); if (Trigger.isUpdate) { helper.doUpdate(Trigger.newMap, Trigger.oldMap); } } ``` **Trigger Class** ``` public with sharing class OpportunityProductScheduleHelper { public OpportunityProductScheduleHelper() { } // On Update, send all Opportunities for FAE and Manufacturer Rep to the GSM for Approval when the StageName // changes to 'Stage 3' public void doUpdate(Map<Id, Opportunity> newmap, Map<Id, Opportunity> oldmap) { //Check the opportunites in the trigger to see if the Close Date changed. //if so add them to a Set Integer Days_Shifted; List<OpportunityLineItem> OppLineItemList = new List<OpportunityLineItem>(); for (Opportunity newOpp: newmap.values()) { Opportunity oldOpp = oldmap.get(newOpp.id); if(newOpp.CloseDate <> oldOpp.CloseDate){ Days_Shifted = oldOpp.CloseDate.daysBetween(newOpp.CloseDate); List<OpportunityLineItem> LineItemList = [SELECT id, ServiceDate, OpportunityId FROM OpportunityLineItem WHERE OpportunityId =:newOpp.id]; for(OpportunityLineItem OppLine : LineItemList){ OppLine.ServiceDate = newOpp.CloseDate; OppLineItemList.add(OppLine); updateSchedule(Days_Shifted, OppLine.Id); //Now here for each opportunity line item schedule item. for(OpportunityLineItemSchedule opplsched : OppLine.OpportunityLineItemSchedules){ system.debug('Going to shift :' + opplsched.Id + ' ' + Days_Shifted + ' days.'); } } } } //update the line items if(!OppLineItemList.isEmpty()){ update OppLineItemList; //This is line 40 } } private void updateSchedule(Integer Days_Shifted, Id OppLineItemId){ List<OpportunityLineItemSchedule> OldScheduleLines = [SELECT id, ScheduleDate, OpportunityLineItemId FROM OpportunityLineItemSchedule WHERE OpportunityLineItemId =:OppLineItemId]; for(OpportunityLineItemSchedule OppSchedLine : OldScheduleLines){ OppSchedLine.ScheduleDate = OppSchedLine.ScheduleDate + Days_Shifted; } //update the scheduledates if(!OldScheduleLines.isEmpty()){ update OldScheduleLines; } } } ``` Please let me know any way to achieve this.
2015/12/08
[ "https://salesforce.stackexchange.com/questions/101755", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/12252/" ]
put these line in try catch ``` if(!OppLineItemList.isEmpty()){ update OppLineItemList; //This is line 40 } ``` something like ``` try { if(!OppLineItemList.isEmpty()){ update OppLineItemList; //This is line 40 } } catch(exception ex) { //display custom message trigger.New[0].adderror('Your custom message'); break; } ``` It will help you. Or in handler pass your trigger. new list and then ``` OppLineItemList[0].adderror('Your custom message'); ``` **Update:** Or you can try one thing ``` Integer count = 0; Database.SaveResult[] srList = Database.update(OppLineItemList, false); for (Database.SaveResult sr : srList) { if (!sr.isSuccess()) for(Database.Error err : sr.getErrors()) OppLineItemList[count].adderror('Your custom message or can use err.getMessage()'); count++; } ``` it will give you error on that particular record and will work as excepted with bulk records
Insert of just **`update`** you can use **`Database.update(List<sObject>)`** method. That will return you **`Database.SaveResult`** (or list of them ) that will contain all the errors if they are Here is more information about <https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_database.htm#apex_System_Database_update>
18,971
This has been bugging me for sometime and now with a important deadline tonight i need to find a solution to my Workflow issues. I have 2 workflows i need to construct and through all my testing and designer none of my steps are working. I am kind of new to SP2010 admin - so forgive me if these seem basic. WF1: To send a notifcation as to when a discussion thread has been updated to the author only after sending to a group to tell them a new thread is there. So step 1: Email group when created Step 2: When modified by that group , email author - this has been falling over WF2: Reminder to Task if not completed Now i have tried hundreds of different wf's and none seem to work, the sticky wicket is the pause. I can set the pause to 1min and still no reminder. The current WF for this is: Pause for 0 days , 0 hours, 0 minutes then Wait for Status to not equal Completed then Email {User} Any suggestions will be much appreciated Many Thanks DM
2011/09/08
[ "https://sharepoint.stackexchange.com/questions/18971", "https://sharepoint.stackexchange.com", "https://sharepoint.stackexchange.com/users/4693/" ]
For WF1, you should consider creating a variable and setting it to the author of the original thread. Then you can use that value to send the reply emails to. That way, the value of "creator" isn't overwritten when a reply to the thread is done. For WF2, the pausing of a workflow for a time period relies on the workflow timer job that runs in the farm. You need to verify how often this timer job is running, and set your pause no shorter than that. You should also be aware that if you set it to a date, it generally will be sent out around midnight on that date.
WF2: my guess is that your issue is with "Wait for Status to not equal Completed", because the workflow will wait for the status to change. Instead, try this: if status is equal to completed then stop workflow else send reminder
19,523,913
How can I remove all the HTML tags including &nbsp using regex in C#. My string looks like ``` "<div>hello</div><div><br></div><div><br></div><div><br></div><div><br></div><div><br></div><div><br></div><div><br></div><div><br></div><div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;</div><div><br></div><div><br></div><div><br></div><div><br></div><div><br></div><div><br></div><div><br></div><div><br></div><div><br></div><div><br></div><div><br></div><div><br></div><div><br></div>" ```
2013/10/22
[ "https://Stackoverflow.com/questions/19523913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2210098/" ]
I've been using this function for a while. Removes pretty much any messy html you can throw at it and leaves the text intact. ``` private static readonly Regex _tags_ = new Regex(@"<[^>]+?>", RegexOptions.Multiline | RegexOptions.Compiled); //add characters that are should not be removed to this regex private static readonly Regex _notOkCharacter_ = new Regex(@"[^\w;&#@.:/\\?=|%!() -]", RegexOptions.Compiled); public static String UnHtml(String html) { html = HttpUtility.UrlDecode(html); html = HttpUtility.HtmlDecode(html); html = RemoveTag(html, "<!--", "-->"); html = RemoveTag(html, "<script", "</script>"); html = RemoveTag(html, "<style", "</style>"); //replace matches of these regexes with space html = _tags_.Replace(html, " "); html = _notOkCharacter_.Replace(html, " "); html = SingleSpacedTrim(html); return html; } private static String RemoveTag(String html, String startTag, String endTag) { Boolean bAgain; do { bAgain = false; Int32 startTagPos = html.IndexOf(startTag, 0, StringComparison.CurrentCultureIgnoreCase); if (startTagPos < 0) continue; Int32 endTagPos = html.IndexOf(endTag, startTagPos + 1, StringComparison.CurrentCultureIgnoreCase); if (endTagPos <= startTagPos) continue; html = html.Remove(startTagPos, endTagPos - startTagPos + endTag.Length); bAgain = true; } while (bAgain); return html; } private static String SingleSpacedTrim(String inString) { StringBuilder sb = new StringBuilder(); Boolean inBlanks = false; foreach (Char c in inString) { switch (c) { case '\r': case '\n': case '\t': case ' ': if (!inBlanks) { inBlanks = true; sb.Append(' '); } continue; default: inBlanks = false; sb.Append(c); break; } } return sb.ToString().Trim(); } ```
``` var noHtml = Regex.Replace(inputHTML, @"<[^>]*(>|$)|&nbsp;|&zwnj;|&raquo;|&laquo;", string.Empty).Trim(); ```
23,216,127
I have a data like this in a table: ``` column1 column2 a 1 a 2 b 2 b 3 a 4 c 5 ``` I want a output like this: ``` column1 column2 a 1-2 b 2-3 a 4-0 c 5-0 ```
2014/04/22
[ "https://Stackoverflow.com/questions/23216127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/654652/" ]
Try this query: ``` with vw1 as (select table1.*,rownum rn from table1), vw2 as (select col1,col2,rn,rn - col2 dis from vw1), vw3 as (select col1,min(rn),to_char(min(col2))||' - '|| case when min(col2) = max(col2) then '0' else to_char(max(col2)) end col2 from vw2 group by col1,dis order by min(rn)) select col1,col2 from vw3; ``` [SQL Fiddle](http://sqlfiddle.com/#!4/66804/1) ----------------------------------------------
You haven't really given a lot of information. - Will there always only be 1 or 2 values in column2, for each value in column1? - Will column2 always be in order? - etc, etc? But, for the given data, the following should give the results you have asked for. ``` SELECT column1, MIN(column2) AS first_column2, CASE WHEN COUNT(*) = 1 THEN 0 ELSE MAX(column2) END AS final_column2 FROM ( SELECT ROW_NUMBER() OVER ( ORDER BY column2, column1) AS sequence_main, ROW_NUMBER() OVER (PARTITION BY column1 ORDER BY column2 ) AS sequence_c1, * FROM your_table ) AS sequenced_table GROUP BY sequence_main - sequence_c1, column1 ORDER BY MIN(sequence_main) ``` Example calculations: ``` column1 column2 | sequence_main sequence_c1 main - c1 | group a 1 | 1 1 0 | a1 a 2 | 2 2 0 | a1 b 2 | 3 1 2 | b2 b 3 | 4 2 2 | b2 a 4 | 5 3 2 | a2 c 5 | 6 1 5 | c5 ```
384,592
I’m doing some review and some of the questions ask what would effect capacitance, and I think that because of C=Q/V that a change in Q or V should affect the capacitance yet it doesn’t. Why is that?
2018/02/06
[ "https://physics.stackexchange.com/questions/384592", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/183945/" ]
You have to distinguish between the simple *mathematical* meaning of the equation and the *physical* meaning. In this case the equation alone says mathematically that $C$ would change if you only changed $Q$ or $V$ but not both. But physically that's not really possible. The capacitance is taken to be constant: its value is independent of $Q$ and $V$ (though it may depend on the configuration of the capacitor), which means that this equation does not determine $C$. Instead the equation describes how $Q$ and $V$ depend on each other. For example, this physical “law” is saying that charge can only increase if you also increase voltage. You can’t just wish charge into a capacitor. If you throw charges at it without changing the voltage at the capacitor’s terminals, the charge will flow away to the rest of the circuit to keep the voltage the same. If there is some reason the charges cannot flow away, the presence of those charges will actually *change* the voltage proportionally. Alternatively, the only way you can change the voltage between the capacitor’s plates is to change the plates' relative charges. Things that change *capacitance itself* include changing the sizes of the plates, their separation, or the material separating them — but not just $Q$ or $V$.
For a *given* geometry - say two parallel plates - adding more charges to the plates (more + charges on one plate, more - on the other plate) will lead to an increase in the electric field since the field between the plates is $E\sim \sigma/\epsilon$ where $\sigma$ is the surface charge density. Since the field is constant between the plate, the potential difference $\Delta V=\sigma d/\epsilon$ where $d$ is the distance between the plates so doubling the charge also doubles the potential difference, and thus $\frac{Q}{V}$ remains constant when adding charges. This is a general feature: adding charges will also increase the voltage difference, but always in such a way that the ratio remains constant and is determined by the geometry of the system.
2,321,872
I have just now installed Python 2.6 on my Windows 7 (64 bit) Lenovo t61p laptop. I have downloaded [Sphinx](http://sphinx.pocoo.org/) and [nose](http://somethingaboutorange.com/mrl/projects/nose/0.11.1/) and apparently installed them correctly using ``` python setup.py install ``` (at least no errors were reported during the installation). Now I am trying to install [pymongo](http://api.mongodb.org/python/1.4%2B/index.html) using `easy_install` but I am not having much success. It seems that `easy_install` isn't working at all. I execute `easy_install` as administrator: ``` C:\>easy_install Cannot find Python executable C:\Program Files\Python26\python.exe ``` The path `C:\Program Files\Python26\python.exe` *is* correct. I have found [this bug report on bugs.python.org](http://bugs.python.org/setuptools/issue2) which seems to be related, although its status is 'Resolved'. Do you have any ideas as to what may be wrong? Any pointers, hints or tips for diagnosing the problem further would be greatly appreciated. **EDIT**: This is the stacktrace I receive when trying to install pymongo: ``` C:\Users\Rune Ibsen\Documents\Downloads\pymongo-1.4>python setup.py install running install running bdist_egg running egg_info writing pymongo.egg-info\PKG-INFO writing top-level names to pymongo.egg-info\top_level.txt writing dependency_links to pymongo.egg-info\dependency_links.txt reading manifest file 'pymongo.egg-info\SOURCES.txt' reading manifest template 'MANIFEST.in' writing manifest file 'pymongo.egg-info\SOURCES.txt' installing library code to build\bdist.win-amd64\egg running install_lib running build_py running build_ext building 'pymongo._cbson' extension Traceback (most recent call last): File "setup.py", line 166, in <module> "doc": doc}) File "C:\Program Files\Python26\lib\distutils\core.py", line 152, in setup dist.run_commands() File "C:\Program Files\Python26\lib\distutils\dist.py", line 975, in run_commands self.run_command(cmd) File "C:\Program Files\Python26\lib\distutils\dist.py", line 995, in run_command cmd_obj.run() File "C:\Program Files\Python26\lib\site-packages\setuptools-0.6c9-py2.6.egg\setuptools\command\install.py", line 76, in run File "C:\Program Files\Python26\lib\site-packages\setuptools-0.6c9-py2.6.egg\setuptools\command\install.py", line 96, in do_egg_install File "C:\Program Files\Python26\lib\distutils\cmd.py", line 333, in run_command self.distribution.run_command(command) File "C:\Program Files\Python26\lib\distutils\dist.py", line 995, in run_command cmd_obj.run() File "C:\Program Files\Python26\lib\site-packages\setuptools-0.6c9-py2.6.egg\setuptools\command\bdist_egg.py", line 174, in run File "C:\Program Files\Python26\lib\site-packages\setuptools-0.6c9-py2.6.egg\setuptools\command\bdist_egg.py", line 161, in call_command File "C:\Program Files\Python26\lib\distutils\cmd.py", line 333, in run_command self.distribution.run_command(command) File "C:\Program Files\Python26\lib\distutils\dist.py", line 995, in run_command cmd_obj.run() File "C:\Program Files\Python26\lib\site-packages\setuptools-0.6c9-py2.6.egg\setuptools\command\install_lib.py", line 20, in run File "C:\Program Files\Python26\lib\distutils\command\install_lib.py", line 113, in build self.run_command('build_ext') File "C:\Program Files\Python26\lib\distutils\cmd.py", line 333, in run_command self.distribution.run_command(command) File "C:\Program Files\Python26\lib\distutils\dist.py", line 995, in run_command cmd_obj.run() File "setup.py", line 107, in run build_ext.run(self) File "C:\Program Files\Python26\lib\distutils\command\build_ext.py", line 340, in run self.build_extensions() File "C:\Program Files\Python26\lib\distutils\command\build_ext.py", line 449, in build_extensions self.build_extension(ext) File "setup.py", line 117, in build_extension build_ext.build_extension(self, ext) File "C:\Program Files\Python26\lib\distutils\command\build_ext.py", line 499, in build_extension depends=ext.depends) File "C:\Program Files\Python26\lib\distutils\msvc9compiler.py", line 448, in compile self.initialize() File "C:\Program Files\Python26\lib\distutils\msvc9compiler.py", line 358, in initialize vc_env = query_vcvarsall(VERSION, plat_spec) File "C:\Program Files\Python26\lib\distutils\msvc9compiler.py", line 274, in query_vcvarsall raise ValueError(str(list(result.keys()))) ValueError: [u'path'] C:\Users\Rune Ibsen\Documents\Downloads\pymongo-1.4> ``` PS.: I previously installed Python 3.1 but later installed 2.6 because I am not sure whether pymongo supports 3.1. PPS.: I have tried installing pymongo using the `python setup.py install` approach, but this resulted in a nasty-looking stack trace, so I thought I would try to let easy\_install take care of it for me. PPPS.: I am completely new to Python, easy\_install, eggs etc.
2010/02/23
[ "https://Stackoverflow.com/questions/2321872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40348/" ]
I don't know anything about these specific packages so I may not be much help. But for what it's worth I have run into the "can't find python executable" errors before with 64 bit python. It happened when the package I was trying to install didn't have a 64 bit version and it was looking for 32 bit python. I ended up just installing and using the 32 bit python. That may not be the issue here, but I figured I'd through it out there.
Install this 64-bit version of setuptools instead. <http://www.lfd.uci.edu/~gohlke/pythonlibs/#setuptools>
19,033,760
I recently updated the NewRelic agent using this commmand: ``` Update-Package NewRelic.Azure.WebSites ``` When I redeploy my site, it fails with this error in the logs. Any ideas? ``` Copying all files to temporary location below for package/publish: C:\DWASFiles\Sites\mysite\Temp\eca8e7b2-2483-4759-ba73-1c04312a8910. KuduSync.NET from: 'C:\DWASFiles\Sites\mysite\Temp\eca8e7b2-2483-4759-ba73-1c04312a8910' to: 'C:\DWASFiles\Sites\mysite\VirtualDirectory0\site\wwwroot' Error: The process cannot access the file 'C:\DWASFiles\Sites\mysite\VirtualDirectory0\site\wwwroot\newrelic\NewRelic.Agent.Core.dll' because it is being used by another process. Copying file: 'Web.config' Copying file: 'bin\mysite.dll' Copying file: 'bin\zh\mysite.resources.dll' Copying file: 'newrelic\NewRelic.Agent.Core.dll' An error has occurred during web site deployment ``` UPDATE: \* I've tried uninstalling New Relic. It tries to delete the dll and Fails. \* I've tried a web deploy. It fails in the same way. Only thing left at this point is to simply create a new azure website and redeploy. .
2013/09/26
[ "https://Stackoverflow.com/questions/19033760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/142098/" ]
When updating the New Relic .NET NuGet package for Azure Websites, try stopping the site, deploying and then restarting the instance. The expected behavior is that the process stops, then the assets get overwritten during a deployment with the ones New Relic packs up in the site root (located at: C:\Home\site\wwwroot\newrelic): <https://newrelic.com/docs/dotnet/azure-web-sites#h2-1>
I experienced the same problem after updating the Microsoft.AspNet.Web.Optimization package via NuGet. The problem can be solved by disconnecting and then reconnecting your git repository to the Azure portal. * Go to the Azure portal website * Click "Disconnect from GitHub" in the "quick glance" section * After a short wait, "Set up deployment from source control" will appear in place of the mentioned link. Click it. * Re-authorise with GitHub. Similar steps apply for other repo types.
52,328,440
I am trying to make a GET request with some custom headers from a react application. This is the code for the axios interceptor: ``` addCaptchaHeaders(captcha, sgn, exp) { // remove the old captcha headers if (this.captchaHeadersInterceptor !== undefined) { this.removeCaptchaHeader(); } // Sign new captcha headers this.captchaHeadersInterceptor = this.httpClient.interceptors.request.use( config => { // Add headers here config.headers.common._captcha = captcha; config.headers.common._sgn = sgn; config.headers.common._exp = exp; return config; }, error => { // Do something with request error return Promise.reject(error); } ); } ``` These are the response headers for the preflight request: ``` Access-Control-Allow-Headers: origin, content-type, accept, authorization, _captcha, _sgn, _exp Content-Length: 0 Server: Jetty(9.3.24.v20180605) ``` These are the request headers for the preflight request: ``` Accept: */* Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9,sl;q=0.8 Access-Control-Request-Headers: _captcha,_exp,_sgn Access-Control-Request-Method: GET Connection: keep-alive Host: localhost:8086 Origin: http://localhost:3000 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.92 Safari/537.36 ``` The headers for the actual request after the preflight one are the same. So `Access-Control-Request-Headers: _captcha,_exp,_sgn` instead of custom request headers. Thinking it was an axios configuration issue I made the same request using fetch: ``` fetch( "http://localhost:8086/podatki/parcela/search?parcela=1727&count=50&offset=0", { method: "GET", headers: { _captcha: res, _sgn: sgn, _exp: exp } } ); ``` The result is the same. Is this an issue with the browser-server communication? If so are there some things missing from the response headers? Doing the same request with postman works.
2018/09/14
[ "https://Stackoverflow.com/questions/52328440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4341439/" ]
Better to use `DataTable` and load contents of `SqlDataReader` with `DataTable.Load()` instead of assigning the reader contents directly to `GridView` instance: ``` DataTable dt = new DataTable(); using (SqlConnection con = new SqlConnection(strConnString)) { using (SqlCommand cmd = new SqlCommand(query, con)) { cmd.CommandType = CommandType.Text; con.Open(); SqlDataReader reader = cmd.ExecuteReader(); if (reader.HasRows) // check if the reader contains rows { dt.Load(reader); // load to Datatable GridView1.DataSource = dt; // assign data source from DataTable GridView1.DataBind(); } } } ``` Note that `SqlDataReader` is [forward-only stream](https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/dataadapters-and-datareaders), you need to use `DataTable` or other collections which able to perform both backward and forward lookups.
remove the line- `if (reader.Read())` because DataReader.Read method advances the SqlDataReader to the next record. Here is the code- ``` public partial class DisplayGrid : System.Web.UI.Page { string strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["PostbankConnectionString"].ConnectionString; string query = "SELECT * FROM tbl_user"; protected void Page_Load(object sender, EventArgs e) { //query SqlConnection con = new SqlConnection(strConnString); SqlCommand cmd = new SqlCommand(query, con); cmd.CommandType = CommandType.Text; SqlDataReader reader; con.Open(); reader = cmd.ExecuteReader(); GridView1.DataSource = reader; //Bind the data GridView1.DataBind(); reader.Close(); con.Close(); } } ```
14,462,855
In Fatwire, there are two asset types which contain code: CSElement and Template. From what I've found, Template is a combination of a CSElement and a SiteEntry. Currently, I use Templates as a wrapper for a set of CSElements, but I'm not totally sure this is the best way to structure my sites. Is there any rule of thumb as to when a Template or CSElement is preferable over the other>? Or does it not really matter?
2013/01/22
[ "https://Stackoverflow.com/questions/14462855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/125342/" ]
The conversion is to use minimum logic part in templates and all cs elements should be called from the template. The logic should be coded in CSElements. For example, if a page is rendered using one template. The navigation part will be done using one CSElement, Header logic will be in one template , logic to load body will be in another CSElement. all these CSelements will be called from the template. In short all these pagelets are rendered using CSElemtents. But it is called from Template. The only plus point in template is that you can associate template with any asset. In all other cases CSElements are used.
A modular strategy is strongly preferred when designing your pages. Templates can be typed or typeless.With typed templates, you could write the rendering logic per asset type/sub type thereby containing the data & presentation logic within the asset type boundary. Coding this way has multiple benefits as given below 1. Helps you design your caching model. You can cache the templates as pagelets with different cache expiry settings. 2. Dictates how the assets are wired to each other so that modifying the asset data or logic is contained within the pagelet. 3. Templates can be swapped at an asset level using the template picker to produce a combination of different layouts. A typeless template is not always preferred as it does not clearly define what asset it is trying to render or what sets of assets it is dependent on. So, a page rendered through typeless template may not live longer in the cache. On the other hand, a CSElement is used to write common business logic and re-used across templates.
34,232,492
First array ``` var danu = ["nu", "da", "nu", "da", "da", "da", "da", "da", "da", "nu", "nu"]; ``` Second array ``` var abc2 = ["2", "3", "2", "3", "3", "2", "2"]; ``` I want to replace all "da" from first array with the values from the second array 1 by 1 so i will get ``` ["nu", "2", "nu", "3", "2", "3", "3", "2", "2", "nu", "nu"]; ``` I want the fix only in Javascript. I tried using the loop metod ``` for (i=0; i<danu.length; i++) { if (danu[i] == "da") { danu[i] = abc2[i]; } } ``` But i end up getting the array to this ``` ["nu", "3", "nu", "3", "3", "2", "2", undefined, undefined, "nu", "nu"] ```
2015/12/11
[ "https://Stackoverflow.com/questions/34232492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5670420/" ]
You can use `.map` to apply changes on each item in the `danu` array. Then have a `c` count which increments when `"da"` was found. ``` danu = ["nu", "da", "nu", "da", "da", "da", "da", "da", "da", "nu", "nu"]; abc2 = ["2", "3", "2", "3", "3", "2", "2"]; c = 0; newArr = danu.map(function(e,i){ if(e == 'da') return abc2[c++]; return e; }); console.log(newArr); ```
Assuming that the second array is equal in length to the number of "da" in the first array, the code would look like: ``` var j = 0; for(int i; i<danu.length; i++){ if(danu[i] === "da"){ danu[i] = abc2[j]; j = j + 1; } } ``` However, if the second array is of different length, incrementing j could put abc2 out of bounds. You would need a different strategy based on what you are actually trying to accomplish with this.
14,647,006
Is there a module for Python to open IBM SPSS (i.e. .sav) files? It would be great if there's something up-to-date which doesn't require any additional dll files/libraries.
2013/02/01
[ "https://Stackoverflow.com/questions/14647006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1725303/" ]
As a note for people findings this later (like me): `pandas.rpy`has been deprecated in the newest versions of pandas (>0.16) as noted [here](http://pandas.pydata.org/pandas-docs/stable/r_interface.html#rpy-updating). That page includes information on updating code to use the `rpy2` interface.
Perhaps you may find this useful: <http://code.activestate.com/recipes/577811-python-reader-writer-for-spss-sav-files-linux-mac-/>
5,583,266
Is classic ADO.NET still widespread and in use with many developers out there inserting, reading data etc? Even though we now have LINQ and EF.
2011/04/07
[ "https://Stackoverflow.com/questions/5583266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/595577/" ]
Yes it is still used in some situations. At my day job we have a couple cases where we use SQL Bulk Copy which requires good ole' Connections and Commands. Additionally, there are some new datatypes in SQL 2008 R2 (Geography, Geometry, Hierarchy) that don't have support in Entity Framework. In those cases, one approach is to go back to the actual Ado.Net. Is there a specific case that you're interested in, or is this a more general question? **EDIT** Another case would be performance. There is a higher ability to fine tune the SQL for optimal performance that tools such as EF don't get you. This case is rarer than the other reasons for using Ado.Net, but it is still a valid case.
Yes, absolutely! EF and Linq-to-SQL are great for most line-of-business apps and operations - but they both don't work very well for e.g. bulk operations (like bulk inserts etc.), where using "straight" ADO.NET is your best bet. Also, certain things aren't supported by EF/L2S - like new SQL Server 2008 datatypes such as the spatial datatypes. Also, neither EF nor L2S support dealing with stored procedures that return more than one result set at once. So yes: there's definitely still room for "classic" ADO.NET to "fill the gaps" where EF/L2S or other technologies don't really offer anything useful.
778
I work in an open plan office that houses about 50 to 60 people. It is mostly engineers at their desks working away, so it is a typical office environment. As you can imagine, sometimes, the noise and the distractions (visual and physical) can get in the way of focusing and doing work. Sometimes, I try to get back focus by putting a set of headphones in and listening to some music, or booking a meeting room for about an hour to work in private. However, these are sub-optimal. What strategies can I use to get focus back?
2012/04/19
[ "https://workplace.stackexchange.com/questions/778", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/89/" ]
One thing no one else seems to mention when discussing the issue of noise in an open office environment is: **Management chose to put you into a sub-optimal situation. They are therefore choosing less productivity.** Therefore the first thing to do is to stop worrying about the fact that you could do more under better circumstances. When circumstances aren't going to change, sometimes it is best just to accept that there will always be noise and it is always going to be disruptive to some extent. Management knows you won't be as productive and they choose to save money by putting in open offices. Management knows the sales team is loud and they chose to put them next to the accounting staff or developers who need to concentrate. So if management has decided the productivity trade-off is worth the cost savings, there is nothing you can do to convince them. So stop worrying about it and, next time you get a new job, weed out the places with open offices from consideration. Once they can't hire new people, these stupid open office plan offices will start to go away. I expect the trend will take 5-10 years to reverse though because the alternatives are expensive so the hit to productivity will have to be really large. And many people won't realize the problem until they work in one and even then, well, working in an open office is better than being unemployed. Once you stop fighting it, it becomes more possible to ignore the noise. **It is your irritation with the noise that is affecting you more than the actual noise much of the time.** Once you learn to accept what can't be changed, you are less irritated, and thus less distracted. For instance, if I happen to notice the air conditioning, I am usually distracted for less than a second and then back to work (unless it sounded like it blew up!). That is because I don't attribute any malice to the air conditioner and it doesn't make me mad that it is running (I like it working actually). You will notice in these types of questions that people are most upset about what they consider to be inappropriate noise like having a conversation that is not work related (or not related to their work) or someone who they think is deliberating trying to annoy them by, say, typing too loud. I've noticed that the less the person likes the person making the noise, the more distracting it seems to be. That is because it is your response to the noise not the noise itself that is the the real distraction. Next you need to practice getting back into the groove after being distracted and letting yourself get distracted less and less. The only way to do this is to practice it and gradually, you will find yourself less and less distracted. So the thing is every time you get distracted, you say mentally to yourself, "Oh a noise, back to work" and then turn back to your task. Soon you will get faster at noticing you are distracted and returning to work. The less time you are distracted for, the easier it is to get back into the groove of where you were. Meditation techniques will help you develop concentration in the face of distractions. When you first start to meditate, you are distracted almost continuously. But as you practice noticing the distraction and deliberately returning to the meditation, you find that you are distracted less and less and that the time to return to task take less and less time. Consider your concentrated work as the meditation and just keep returning to task quietly, without emotional baggage. You can also consider having a pen and paper next to you and noting down what you are doing at the time of the distraction if it looks to be a major one. A quick reminder will help you get back on track.
I have a nice set of [custom in-ear headphones](http://www.logitech.com/en-us/ue/custom-in-ear-monitors#). Noise isolation without resorting to full-on noise-cancellation. The visual of employees wearing big headphones when visitors/clients come through is not a good thing (in some organizations). To keep focus, I work in [25-minute blocks](http://www.focusboosterapp.com/) using a modified [Pomodoro technique](http://en.wikipedia.org/wiki/Pomodoro_Technique). It's an easy way to keep focus on specific tasks.
111,693
So I work for a small financial technology business in the UK, not quite startup size but close. We have a dozen staff on site and usually 5-10 remote contractors working for us. There isn't really a hierarchy so to speak, but I'm generally considered to be the owner's second in command although in practical terms this doesn't mean much. Around 60% our work is based in the EU, and as such prior to the Brexit referendum the owner sent an email to all staff and contractors informing them that, if they wanted to guarantee their employment past the next 2 years, they should vote to remain. This isn't unusual; the owner of the biggest pub chain in the UK asked his employees to vote to leave for similar reasons. As everyone knows, the leave side won the vote and the UK is exiting the EU. Without going into too much detail, it has recently become clear that the Brexit process isn't working quite as intended and a degree of economic pain looks to be a likely outcome. The company 'will probably fold inside the next 18 months' according to the owner, and he is visibly distraught. This Monday, he called me into a meeting as he usually does, and told me quite simply to research the social media accounts, internet histories and company emails of all staff and contractors to look for evidence of support for Brexit, and to supply him with the list of names. I pointed out the ethical and potential legal issues with this and he shot me down, saying these people had destroyed the company and he'd happily fudge their performance metrics to give him a solid reason to fire them. Moralising aside, the most talented engineer in the company, the de facto tech lead, is an ardent Brexiteer. Suddenly losing him at this point along with several well-regarded contractors will almost certainly result in the catastrophic loss of at least two big contracts, which will sink the company unless a lot more staff are let go. Is there any point in trying to salvage this or should I leave my resignation on his desk this afternoon and contact the police?
2018/05/04
[ "https://workplace.stackexchange.com/questions/111693", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/83404/" ]
> > Is there any point in trying to salvage this or should I leave my > resignation on his desk this afternoon and contact the police? > > > Neither. 1. Polish up your resume and start looking for jobs now. If your boss has lost faith in the company, than it's unlikely to survive, regardless of this matter 2. Putting a resignation on his desk is just passive aggressive. However you can and should tell him "What you ask me to do is in my opinion morally wrong and it may actually be illegal. I think it's also counterproductive and will gravely harm our company. Sorry, but I can't do this". There is a minuscule chance that this wakes him up, but I wouldn't count on it. There is a good chance you will be fired, so be prepared for that. "I'm sorry you feel this way, but I can't compromise my moral integrity. Bye". 3. Don't go to the police. No one has been harmed yet. If he starts firing people because of their Brexit votes, these people may have legal recourse (as you might have if you get fired). But any legal action has be to tied to a specific case and person and it's up to each affected individual what to do about it.
Whether due to Brexit or not, if the owner believes that the company will fold inside of the next 18 months, there is a good possibility that it will, so is probably a good idea to start looking around for another job. That said, to solve your current dilemma, is there any reason why you cannot simply "do" what the owner asks: > > research the social media accounts, internet histories and company > emails of all staff and contractors to look for evidence of support > for Brexit > > > And just report that you could not find anything? Many would say that this is too passive-aggressive, but the owner has asked you to perform a task that you find unethical and that he has no right to expect you to do. To my mind, this is a lesser problem than a confrontation that, from your description, seems unlikely to have a positive effect.
268,564
I was trying to emulate python's `timeit` in C++. My main aim for this is to measure the performance of small functions of C++ code that I write and print some basic stats like avg., min, max. ### Code: `ctimeit.h`: ``` #ifndef CTIMEIT_H #define CTIMEIT_H #include <chrono> #include <cmath> #include <iostream> #include <limits> namespace ctimeit { using GetTime = std::chrono::high_resolution_clock; using std::chrono::duration_cast; std::string format_time(int64_t); template <size_t N = 1000, typename Callable, typename... Args> void timeit(Callable func, Args&&... Funcargs) { /* * Measure the average execution time of `func` which takes `Funcargs` * after `N` executions. */ double total_time{0}; int64_t min_exec_time{std::numeric_limits<int64_t>::max()}, max_exec_time{0}; for (size_t i = 0; i < N; ++i) { auto start = GetTime::now(); func(std::forward<Args>(Funcargs)...); auto end = GetTime::now(); auto run_time = duration_cast<std::chrono::nanoseconds>(end - start).count(); min_exec_time = std::min(min_exec_time, run_time); max_exec_time = std::max(max_exec_time, run_time); total_time += run_time; } std::cout << "Average time taken : " << format_time(total_time / N) << " (" << N << " runs)\n" << "Max time taken : " << format_time(max_exec_time) << "\n" << "Min time taken : " << format_time(min_exec_time) << "\n"; } std::string format_time(int64_t run_time) { /* * For setting the scale of execution time. */ std::string formats[]{"ns", "µs", "ms", "s"}; float scaling[]{1, 1e3, 1e6, 1e9}; int pow = std::floor(std::log10(run_time)); int idx = std::max(0, pow / 3); return std::to_string(run_time / scaling[idx]) + formats[idx]; } } // namespace ctimeit #endif // CTIMEIT_H ``` --- **Output:** ```none std::cout<<"-------SomeFunc---------\n"; timeit(SomeFunc, v); //default N i.e 1000 std::cout<<"-------anotherFunc with N arg---------\n"; timeit<100>(anotherFunc, 10, 20, 40.f); -------SomeFunc--------- Average time taken : 904.073975µs (1000 runs) Max time taken : 4.574131ms Min time taken : 834.716003µs -------anotherFunc with N arg--------- Average time taken : 45.000000ns (100 runs) Max time taken : 137.000000ns Min time taken : 39.000000ns ``` Any suggestions to improve my code or if there's anything wrong I'm doing in measuring the execution time?
2021/10/01
[ "https://codereview.stackexchange.com/questions/268564", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/233346/" ]
I'm guessing `int64_t` is intended to be `std::int64_t`? Don't assume that all compilers declare these types in the global namespace as well as `std`. If `std::int64_t` is present, it's declared in `<cstdint>`, so be sure to include that. Your code could be more portable if you used e.g. `std::uint_fast64_t` - or in this case, `std::chrono::nanoseconds::rep`. `std::size_t` is consistently misspelt, too. --- Accumulating values into a `double` is likely to lose precision. I'd be inclined to keep the total as a duration, rather than converting to numeric type. --- > > > ``` > int idx = std::max(0, pow / 3); > return std::to_string(run_time / scaling[idx]) + formats[idx]; > > ``` > > Although we've taken care here not to run off the beginning of the array, we haven't taken the same care with the end (kiloseconds). We probably want ``` const std::array formats = {"ns", "µs", "ms", "s"}; auto idx = std::clamp(pow / 3, 0, static_cast<int>(formats.size() - 1)); ``` Also, be careful using names such as `pow` which are also in the C standard library. That can hamper quick comprehension by your code's readers. This utility function `format_time()` probably deserves its own unit tests, to ensure that extremes are handled well.
There's a glaring bug in how you forward arguments ``` template <size_t N = 1000, typename Callable, typename... Args> void timeit(Callable func, Args&&... Funcargs) { // ... for (size_t i = 0; i < N; ++i) { // ... func(std::forward<Args>(Funcargs)...); // ... } ``` Consider this ``` timeit([](std::string s){ s += s; }, std::string("Lorem ipsum dolor sit amet")); ``` You move the string in the first iteration, and henceforth the string is in a valid but unspecified state, usually just empty. Either way, that's not what you want. A quick fix is ``` template <typename... Args, typename Callable, typename Tuple, size_t... Is> void forward_apply(Callable func, Tuple& args, std::index_sequence<Is...>) { func(std::forward<Args>(get<Is>(args))...); } template <size_t N = 1000, typename Callable, typename... Args> void timeit(Callable func, Args&&... Funcargs) { // ... for (size_t i = 0; i < N; ++i) { auto args = std::tuple(Funcargs...); // ... forward_apply<Args&&...>(func, args, std::index_sequence_for<Args...>{}); // ... } ``` where you make a copy of the arguments without timing them, and then forward them as specified by the argument types. At this point, `timeit` has rather convoluted semantics. What if the arguments aren't copyable? Should `Callable` be copied and forwarded similarly to the arguments? A solution provided by the standard library is to use `std::reference_wrapper` to opt *out* of copying. However, the complexity for both users and implementer gets even greater. You could limit the scope of what `timeit` is supposed to do ``` template <size_t N = 1000, typename Callable> void timeit(Callable&& func) { // ... for (size_t i = 0; i < N; ++i) { // ... func(); // ... } ``` The semantics is simple: `timeit` repeatedly calls `operator()` on the `func` object passed in, and it's up to the user to decide what to do with arguments. It is however impossible to omit argument copying time in such a design.
60,602
GnuPG (GPG) has the ability to both digitally sign and encrypt things (things being messages, documents, files, etc.). Is a public-key signature legally valid? If so, do the public keys need to be published on all key servers to remain legally effective? Or can they be posted on just one (some key servers such as the new keys.openpgp.org servers which use the Hagrid system don't propagate to older servers).
2021/01/28
[ "https://law.stackexchange.com/questions/60602", "https://law.stackexchange.com", "https://law.stackexchange.com/users/36495/" ]
This is a common issue when a contractor is hired to write a technical document. Under [united-states](/questions/tagged/united-states "show questions tagged 'united-states'") law, at least, the answer is clear. The contractor owns the copyright unless there is a written agreement transferring the copyright. This may or may not be a work-for-hire agreement, and there are some significant differences in the effects if it is, but an agreement in writing there must be. Otherwise the author (the contractor) retains the copyright. If you were an employee, the result would be the reverse. Even though you hold the copyright, I think you should, at a minimum, change any identifying details. There might be an invasion of privacy issue otherwise, and there surely would be an ethical issue. However, you do **not** hold the copyright of any original version that the client wrote. The client holds that, unless there was a written agreement giving you the copyright. If your final resume is sufficiently close to the original as to be a *derivative work* then you must have the client's permission before publishing it. If this is in the US, the issue of the client's copyright on the original version **might** be avoided via a claim of *Fair Use* (FU), as a comment mentions. This is a specifically US legal concept, although some other countries have a somewhat similar but narrower concept of *Fair dealing*. There is no automatic formula for what use will be considered a fair use -- the specific facts of the matter must always be considered. The statute lists four factors to consider, but the court may consider others as well, and caselaw says no one factor is dominant in all cases, they must be balanced The four factors as set out by [17 USC 17](https://www.copyright.gov/title17/92chap1.html#107) are: > > (1) the purpose and character of the use, including whether such use is of a commercial nature or is for nonprofit educational purposes; > > > > > (2) the nature of the copyrighted work; > > > > > (3) the amount and substantiality of the portion used in relation to the copyrighted work as a whole; and > > > > > (4) the effect of the use upon the potential market for or value of the copyrighted work. > > > Here as the writer would be using the whole work, factor (3) , the amount of the work used, would tilt against FU. The use is not educational or non-profit, nor transformative, so factor (1) also tilts against FU. There is probably no market for the original, which tilts factor (4) toward FU. The original is highly factual which tilts factor (2) toward FU. There is no telling where a court would come out, and the OP doesn't want to rely on a risky issue. If anyone were to relay on fair use for this sort of thing, consulting an attorney who could look at specifics would be a good idea.
It's not just copyright. My resume contains my private information. If you publish my resume, that's a violation of my privacy. If I find out, I'll come after you for that. And it will kill your business, because nobody will want you to write their resume and then see it published in a book. As far as copyright is concerned: First, you created a derivative work of my own resume, so you need my permission to copy it. Two, there is an implied contract between you and me, and if you assume you have the copyright, I can take you to court to get a decision what the implied contract is.
42,391,009
I am using Google Vision API, primarily to extract texts. I works fine, but for specific cases where I would need the API to scan the enter line, spits out the text before moving to the next line. However, it appears that the API is using some kind of logic that makes it scan top to bottom on the left side and moving to right side and doing a top to bottom scan. I would have liked if the API read left-to-right, move down and so on. For example, consider the image: [![enter image description here](https://i.stack.imgur.com/wk3t1.png)](https://i.stack.imgur.com/wk3t1.png) The API returns the text like this: ``` “ Name DOB Gender: Lives In John Doe 01-Jan-1970 LA ” ``` Whereas, I would have expected something like this: ``` “ Name: John Doe DOB: 01-Jan-1970 Gender: M Lives In: LA ” ``` I suppose there is a way to define the block size or margin setting (?) to read the image/scan line by line? Thanks for your help. Alex
2017/02/22
[ "https://Stackoverflow.com/questions/42391009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7604576/" ]
I get max and min y and iterate over y to get all potential lines, here is the full code ```py import io import sys from os import listdir from google.cloud import vision def read_image(image_file): client = vision.ImageAnnotatorClient() with io.open(image_file, "rb") as image_file: content = image_file.read() image = vision.Image(content=content) return client.document_text_detection( image=image, image_context={"language_hints": ["bg"]} ) def extract_paragraphs(image_file): response = read_image(image_file) min_y = sys.maxsize max_y = -1 for t in response.text_annotations: poly_range = get_poly_y_range(t.bounding_poly) t_min = min(poly_range) t_max = max(poly_range) if t_min < min_y: min_y = t_min if t_max > max_y: max_y = t_max max_size = max_y - min_y text_boxes = [] for t in response.text_annotations: poly_range = get_poly_y_range(t.bounding_poly) t_x = get_poly_x(t.bounding_poly) t_min = min(poly_range) t_max = max(poly_range) poly_size = t_max - t_min text_boxes.append({ 'min_y': t_min, 'max_y': t_max, 'x': t_x, 'size': poly_size, 'description': t.description }) paragraphs = [] for i in range(min_y, max_y): para_line = [] for text_box in text_boxes: t_min = text_box['min_y'] t_max = text_box['max_y'] x = text_box['x'] size = text_box['size'] # size < max_size excludes the biggest rect if size < max_size * 0.9 and t_min <= i <= t_max: para_line.append( { 'text': text_box['description'], 'x': x } ) # here I have to sort them by x so the don't get randomly shuffled para_line = sorted(para_line, key=lambda x: x['x']) line = " ".join(map(lambda x: x['text'], para_line)) paragraphs.append(line) # if line not in paragraphs: # paragraphs.append(line) return "\n".join(paragraphs) def get_poly_y_range(poly): y_list = [] for v in poly.vertices: if v.y not in y_list: y_list.append(v.y) return y_list def get_poly_x(poly): return poly.vertices[0].x def extract_paragraphs_from_image(picName): print(picName) pic_path = rootPics + "/" + picName text = extract_paragraphs(pic_path) text_path = outputRoot + "/" + picName + ".txt" write(text_path, text) ``` This code is WIP. In the end, I get the same line multiple times and post-processing to determine the exact values. (paragraphs variable). Let me know if I have to clarify anything
Based on Borislav Stoilov latest answer I wrote the code for c# for anybody that might need it in the future. Find the code bellow: ``` public static List<TextParagraph> ExtractParagraphs(IReadOnlyList<EntityAnnotation> textAnnotations) { var min_y = int.MaxValue; var max_y = -1; foreach (var item in textAnnotations) { var poly_range = Get_poly_y_range(item.BoundingPoly); var t_min = poly_range.Min(); var t_max = poly_range.Max(); if (t_min < min_y) min_y = t_min; if (t_max > max_y) max_y = t_max; } var max_size = max_y - min_y; var text_boxes = new List<TextBox>(); foreach (var item in textAnnotations) { var poly_range = Get_poly_y_range(item.BoundingPoly); var t_x = Get_poly_x(item.BoundingPoly); var t_min = poly_range.Min(); var t_max = poly_range.Max(); var poly_size = t_max - t_min; text_boxes.Add(new TextBox { Min_y = t_min, Max_y = t_max, X = t_x, Size = poly_size, Description = item.Description }); } var paragraphs = new List<TextParagraph>(); for (int i = min_y; i < max_y; i++) { var para_line = new List<TextLine>(); foreach (var text_box in text_boxes) { int t_min = text_box.Min_y; int t_max = text_box.Max_y; int x = text_box.X; int size = text_box.Size; //# size < max_size excludes the biggest rect if (size < (max_size * 0.9) && t_min <= i && i <= t_max) para_line.Add( new TextLine { Text = text_box.Description, X = x } ); } // here I have to sort them by x so the don't get randomly enter code hereshuffled para_line = para_line.OrderBy(x => x.X).ToList(); var line = string.Join(" ", para_line.Select(x => x.Text)); var paragraph = new TextParagraph { Order = i, Text = line, WordCount = para_line.Count, TextBoxes = para_line }; paragraphs.Add(paragraph); } return paragraphs; //return string.Join("\n", paragraphs); } private static List<int> Get_poly_y_range(BoundingPoly poly) { var y_list = new List<int>(); foreach (var v in poly.Vertices) { if (!y_list.Contains(v.Y)) { y_list.Add(v.Y); } } return y_list; } private static int Get_poly_x(BoundingPoly poly) { return poly.Vertices[0].X; } ``` Calling ExtractParagraphs() method will return a list of strings which contains doubles from the file. I also wrote some custom code to treat that problem. If you need any help processing the doubles let me know, and I could provide the rest of the code. **Example:** Text in picture: *"I want to make this thing work 24/7!"* Code will return: *"I" "I want" "I want to " "I want to make" "I want to make this" "I want to make this thing" "I want to make this thing work" "I want to make this thing work 24/7!" "to make this thing work 24/7!" "this thing work 24/7!" "thing work 24/7!" "work 24/7!" "24/7!"* I also have an implementation of parsing PDFs to PNGs beacause Google Cloud Vision Api won't accept PDFs that are not stored in the Cloud Bucket. If needed I can provide it. Happy coding!
4,185,521
I need some way to get the Name of a Type, when `type.IsGenericType` = `true`. ``` Type t = typeof(List<String>); MessageBox.Show( ..?.. ); ``` What I want, is a message box to pop up with `List` showing... how can I do that?
2010/11/15
[ "https://Stackoverflow.com/questions/4185521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/481702/" ]
``` Type t = ...; if (t.IsGenericType) { Type g = t.GetGenericTypeDefinition(); MessageBox.Show(g.Name); // displays "List`1" MessageBox.Show(g.Name.Remove(g.Name.IndexOf('`'))); // displays "List" } ```
My take on yoyo's approach. Ensures more friendly names for primitives, handles arrays and is recursive to handle nested generics. Also unit tests. ``` private static readonly Dictionary<Type, string> _typeToFriendlyName = new Dictionary<Type, string> { { typeof(string), "string" }, { typeof(object), "object" }, { typeof(bool), "bool" }, { typeof(byte), "byte" }, { typeof(char), "char" }, { typeof(decimal), "decimal" }, { typeof(double), "double" }, { typeof(short), "short" }, { typeof(int), "int" }, { typeof(long), "long" }, { typeof(sbyte), "sbyte" }, { typeof(float), "float" }, { typeof(ushort), "ushort" }, { typeof(uint), "uint" }, { typeof(ulong), "ulong" }, { typeof(void), "void" } }; public static string GetFriendlyName(this Type type) { string friendlyName; if (_typeToFriendlyName.TryGetValue(type, out friendlyName)) { return friendlyName; } friendlyName = type.Name; if (type.IsGenericType) { int backtick = friendlyName.IndexOf('`'); if (backtick > 0) { friendlyName = friendlyName.Remove(backtick); } friendlyName += "<"; Type[] typeParameters = type.GetGenericArguments(); for (int i = 0; i < typeParameters.Length; i++) { string typeParamName = typeParameters[i].GetFriendlyName(); friendlyName += (i == 0 ? typeParamName : ", " + typeParamName); } friendlyName += ">"; } if (type.IsArray) { return type.GetElementType().GetFriendlyName() + "[]"; } return friendlyName; } [TestFixture] public class TypeHelperTest { [Test] public void TestGetFriendlyName() { Assert.AreEqual("string", typeof(string).FriendlyName()); Assert.AreEqual("int[]", typeof(int[]).FriendlyName()); Assert.AreEqual("int[][]", typeof(int[][]).FriendlyName()); Assert.AreEqual("KeyValuePair<int, string>", typeof(KeyValuePair<int, string>).FriendlyName()); Assert.AreEqual("Tuple<int, string>", typeof(Tuple<int, string>).FriendlyName()); Assert.AreEqual("Tuple<KeyValuePair<object, long>, string>", typeof(Tuple<KeyValuePair<object, long>, string>).FriendlyName()); Assert.AreEqual("List<Tuple<int, string>>", typeof(List<Tuple<int, string>>).FriendlyName()); Assert.AreEqual("Tuple<short[], string>", typeof(Tuple<short[], string>).FriendlyName()); } } ```
36,583,296
I would like to do a page like this : <https://www.dropbox.com/s/5qwht1q96idtc22/hf.png?dl=0> with this parameters : ``` Background: red header: 70px tall, black background, is always at the top of your browser (fixed position), total width Content: 500px wide, centered in height matches the contents of a blue background, the browser scrolljának top position 30px from the header Left column: 300px wide (including frame), 550px high and 25px from the container to containing a yellow background, black border 5px Right column: 125px wide, 200px high, white background, 25px on the container to contain' ``` I just did this : <https://www.dropbox.com/home?preview=hazikep.jpg> With this code : ``` *{ margin:0; padding:0; } html, body { height: 100%; width: 100%; background-color: red; } #fejlec{ height: 70px; width: 100%; background-color: black; background-position:top; background-attachment:fixed; position: fixed; } #kek{ background-color: blue; width: 500px; height: 100%; position: absolute; top:170px; bottom: 0; left: 0; right: 0; margin: auto; } #sarga{ background-color: yellow; width:260px; height: 550px; padding:20px; border:5px solid black; position: absolute; top:-25px; bottom: 0; left: 0; right: 0; margin: auto; float: left ; } #feher { background-color: white; width:125px; height: 200px; padding:25px; } ``` I don't know who to do arrange divs with css, so it could be very useful, if somebody could help me.
2016/04/12
[ "https://Stackoverflow.com/questions/36583296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4862198/" ]
This should get you started: <https://jsfiddle.net/hex8xsbs/> html: ``` <div class="header"></div> <div class="container"> <div class="content"></div><div class="sidebar"></div> </div> ``` css: ``` html { background: red; } .header { height: 70px; width: 100%; position: fixed; top: 0; left: 0; background: black; } .container { width: 500px; margin: 100px auto; background: blue; } .content { width: 300px; height: 550px; margin: 25px; display: inline-block; vertical-align: top; background: yellow; } .sidebar { width: 125px; height: 200px; margin: 25px 0 25px 0; display: inline-block; vertical-align: top; background: white; } ```
there are many ways of achieving that layout. another (similar) solution to switz's one could be: the HTML ``` <div id="fejlec"></div> <div id="kek"> <div id="sarga"></div> <div id="feher"></div> <div class="clear"> </div> </div> ``` and the css: ``` *{ margin:0; padding:0; } html, body { height: 100%; width: 100%; background-color: red; } .clear { clear: both; } #fejlec { height: 70px; width: 100%; background-color: black; position: fixed; top: 0 } #kek { background-color: blue; width: 500px; margin: 100px auto 0; padding: 20px; } #sarga { background-color: yellow; width:260px; height: 550px; padding:20px; float: left; border:5px solid black; } #feher { background-color: white; width:26%; height: 200px; padding:25px; float: right; } ``` <https://jsfiddle.net/njb9aj5z/>
74,130,038
I have two controllers (FirstController, SecondController) that use the same functions, to avoid rewriting them I thought of creating another controller (ThirdController) and subsequently calling the functions through it. the problem is that if in ThirdController there are relationship query they give me the error that "they don't exist". example: > > User Model > > > ``` class User extends Authenticatable implements AuthenticatableUserContract { use HasFactory, Notifiable; public function comments(){ return $this->hasMany('App\Models\Comment'); } ``` > > ThirdController > > > ``` class ThirdController extends Controller { public static function example($id){ $comments = Comment::find($id)->comments(); return $comments; } } ``` > > FirstController/SecondController > > > ``` public function example2(Request $request){ return ThirdController::example($request->id); ``` When call the route it give me error: BadMethodCallException: Method Illuminate\Database\Eloquent\Collection::comments does not exist. my questions are: 1. Is there any better method instead of creating a third controller? 2. Is there a solution to this? p.s. I know I could very well build the queries without exploiting the relationship, but where's the beauty of that? :D
2022/10/19
[ "https://Stackoverflow.com/questions/74130038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18365403/" ]
One approach without regex. First, we cut the text by `\n`, because all the numbers we need start on a new line. Then we discard those elements that do not start with a number. Next, we cut the remaining elements by spaces and get numbers. ``` text = "[' \n\na)\n\n \n\nFactuur\nVerdi Import Schoolfruit\nFactuur nr. : 71201 Koopliedenweg 33\nDeb. nr. : 108636 2991 LN BARENDRECHT\nYour VAT nr. : NL851703884B01 Nederland\nFactuur datum : 10-12-21\nAantal Omschrijving Prijs Bedrag\nOrder number : 77553 Loading date : 09-12-21 Incoterm: : FOT\nYour ref. : SCHOOLFRUIT Delivery date :\nWK50\nD.C. Schoolfruit\n16 Watermeloenen Quetzali 16kg 4 IMPERIAL BR I € 7,70 € 123,20\n360 Watermeloenen Quetzali 16kg 4 IMPERIAL BR I € 7,70 € 2.772,00\n6 Watermeloenen Quetzali 16kg 4 IMPERIAL BR I € 7,/0 € 46,20\n75 Watermeloenen Quetzali 16kg 4 IMPERIAL BR I € 7,70 € 577,50\n9 Watermeloenen Quetzali 16kg 4 IMPERIAL BR I € 7,70 € 69,30\n688 Appels Royal Gala 13kg 60/65 Generica PL I € 5,07 € 3.488,16\n22 Sinaasappels Valencias 15kg 105 Elara ZAI € 6,25 € 137,50\n80 Sinaasappels Valencias 15kg 105 Elara ZAI € 6,25 € 500,00\n160 Sinaasappels Valencias 15kg 105 FVC ZAI € 6,25 € 1.000,00\n320 Sinaasappels Valencias 15kg 105 Generica ZAI € 6,25 € 2.000,00\n160 Sinaasappels Valencias 15kg 105 Noordhoek ZA I € 6,25 € 1.000,00\n61 Sinaasappels Valencias 15kg 105 Noordhoek ZA I € 6,25 € 381,25\nTotaal Colli Totaal Netto Btw Btw Bedrag Totaal Bedrag\n€ 12.095,11 1.088,56\nBetaling binnen 30 dagen\nAchterstand wordt gemeld bij de kredietverzekeringsmaatschappij\nVerDi Import BV ING Bank NV. Rotterdam IBAN number: NL17INGB0006959173 ~~\n\n \n\nKoopliedenweg 38, 2991 LN Barendrecht, The Netherlands SWIFT/BIC: INGBNL2A, VAT number: NL851703884B01 i\nTel, +31 (0}1 80 61 88 11, Fax +31 (0)1 8061 88 25 Chamber of Commerce Rotterdam no. 55424309 VerDi\n\nE-mail: sales@verdiimport.nl, www.verdiimport.nl Dutch law shall apply. The Rotterdam District Court shall have exclusive jurisdiction.\n\nrut ard wegetables\n\x0c']" a = text.split('\n') b = list(filter(lambda x: x[0].isdigit() if len(x) > 0 else False, a)) c = [x.split()[0] for x in b if x.split()[0].isdigit()] print(c) ``` ```none ['16', '360', '6', '75', '9', '688', '22', '80', '160', '320', '160', '61'] ```
removing Regex as no longer need ``` text = "[' \n\na)\n\n \n\nFactuur\nVerdi Import Schoolfruit\nFactuur nr. : 71201 Koopliedenweg 33\nDeb. nr. : 108636 2991 LN BARENDRECHT\nYour VAT nr. : NL851703884B01 Nederland\nFactuur datum : 10-12-21\nAantal Omschrijving Prijs Bedrag\nOrder number : 77553 Loading date : 09-12-21 Incoterm: : FOT\nYour ref. : SCHOOLFRUIT Delivery date :\nWK50\nD.C. Schoolfruit\n16 Watermeloenen Quetzali 16kg 4 IMPERIAL BR I € 7,70 € 123,20\n360 Watermeloenen Quetzali 16kg 4 IMPERIAL BR I € 7,70 € 2.772,00\n6 Watermeloenen Quetzali 16kg 4 IMPERIAL BR I € 7,/0 € 46,20\n75 Watermeloenen Quetzali 16kg 4 IMPERIAL BR I € 7,70 € 577,50\n9 Watermeloenen Quetzali 16kg 4 IMPERIAL BR I € 7,70 € 69,30\n688 Appels Royal Gala 13kg 60/65 Generica PL I € 5,07 € 3.488,16\n22 Sinaasappels Valencias 15kg 105 Elara ZAI € 6,25 € 137,50\n80 Sinaasappels Valencias 15kg 105 Elara ZAI € 6,25 € 500,00\n160 Sinaasappels Valencias 15kg 105 FVC ZAI € 6,25 € 1.000,00\n320 Sinaasappels Valencias 15kg 105 Generica ZAI € 6,25 € 2.000,00\n160 Sinaasappels Valencias 15kg 105 Noordhoek ZA I € 6,25 € 1.000,00\n61 Sinaasappels Valencias 15kg 105 Noordhoek ZA I € 6,25 € 381,25\nTotaal Colli Totaal Netto Btw Btw Bedrag Totaal Bedrag\n€ 12.095,11 1.088,56\nBetaling binnen 30 dagen\nAchterstand wordt gemeld bij de kredietverzekeringsmaatschappij\nVerDi Import BV ING Bank NV. Rotterdam IBAN number: NL17INGB0006959173 ~~\n\n \n\nKoopliedenweg 38, 2991 LN Barendrecht, The Netherlands SWIFT/BIC: INGBNL2A, VAT number: NL851703884B01 i\nTel, +31 (0}1 80 61 88 11, Fax +31 (0)1 8061 88 25 Chamber of Commerce Rotterdam no. 55424309 VerDi\n\nE-mail: sales@verdiimport.nl, www.verdiimport.nl Dutch law shall apply. The Rotterdam District Court shall have exclusive jurisdiction.\n\nrut ard wegetables\n\x0c']" ``` Your Input looks like an Invoice and most of the invoices have a start and end before the items are listed. In this case [Not sure, could answer better if I can get one more sample] "D.C. Schoolfruit" will be the start and "Totaal" will be the end. Putting in a loop after splitting it with "\n" and getting rows after the start till end should give you the list of all the items in the invoice. Hope this helps.
2,439,356
I am using a SQL Server database in my current project. I was watching the MVC Storefront videos (specifically the repository pattern) and I noticed that Rob (the creator of MVC Storefront) used a class called Category and Product, instead of a database and I have notice that using LINQ-SQL or ADO.NET, that a class is generated. Is there an advantage to using a class over a database to store information? Or is it the other way around? Or are they even comparable?
2010/03/13
[ "https://Stackoverflow.com/questions/2439356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/200477/" ]
I think in this case, the Category and Product classes are wrappers that persist their data to the database when something is changed. The [Entity Framework](http://msdn.microsoft.com/en-us/library/aa697427(VS.80).aspx) is a perfect example of that.
A class is an object in .NET, a class may or may not contain methods for data access to a database. However they are not comparable or related. Read hear about classes: <http://www.devarticles.com/c/a/C-Sharp/Introduction-to-Objects-and-Classes-in-C-Sharp-Part-2/>
96,370
The WiFi interface won't turn on when i press "Activate wifi" from the preferences neither from the status bar. I tried restarting the mac,and reset the pram. The Ethernet works fine and this is the result of ifconfig in the terminal: ``` en0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500 options=2b<RXCSUM,TXCSUM,VLAN_HWTAGGING,TSO4> ether a8:20:66:37:81:d9 inet6 fe80::aa20:66ff:fe37:81d9%en0 prefixlen 64 scopeid 0x4 inet 192.168.1.131 netmask 0xffffff00 broadcast 192.168.1.255 media: autoselect (100baseTX <full-duplex,flow-control>) status: active en1: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500 ether 5c:96:9d:89:fe:09 media: autoselect (<unknown type>) status: inactive ``` Is there anything I can try before initialize OSX?
2013/07/14
[ "https://apple.stackexchange.com/questions/96370", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/53262/" ]
Cycling the network setup has worked for me. Run the following in Terminal: ``` networksetup -setairportpower en0 off networksetup -setairportpower en0 on ```
Found [this](http://dioisme.blogspot.com/2012/05/solving-wifi-wont-turn-on-lion-osx.html): * Restart your mac. * Open "Network Preferences". On the left tab, look for wifi connection (usually named Wi-Fi). * Select the wifi connection, and disable that. To disable a connection, choose gear icon below the tab, and choose "Make Service Inactive". * After disabled, delete the connection. To delete a connection, choose minus (-) icon below the tab, left of gear icon. * Now that the original connection has been deleted, we must create a new wifi connection. Choose plus (+) icon, select "Wi-Fi" as interface, and you can name it anything as you want, it doesn't matter thought. * Apply the change. Once again, restart your mac. * After system reboot, voila ! your wifi should be working properly by now
17,784
I recently went on a 2 week holiday and I took about 3,000 photos (I'm a sucker for taking photos in bursts of 3 or so to catch motion) I'm looking for some software that will let me sift through these images in full screen and mark the ones that I want to keep. Being able to tag them and specify a folder that they go in by tag would also be useful. Does anyone have any suggestions for a software package that will allow me to do this? **EDIT:** I'd prefer free open source software or at least software that is quite cheap. **EDIT** To answer comments OS of Choice is Windows Cheap is less than £30 UK ($45?)
2011/12/07
[ "https://photo.stackexchange.com/questions/17784", "https://photo.stackexchange.com", "https://photo.stackexchange.com/users/2680/" ]
I use FastPictureViewer 64 to sift through my images after shooting. It lets me scroll using my mouse *fast* and add star ratings with 1-5 number keys. I can delete jpg and raw with one keystroke as well. Since the application displays using accelerated video hardware, it's really fast. You can set up keystrokes to save to folders, etc. Helps me cull images off the card before I do the import. Since the images then have star ratings, it helps the next processing steps. Not free, but there are trials available.
I have the same problem and I never get down to wading through all those shots, no matter what the software is. So here's my current strategy: I use [Wallpaper Slideshow Pro](http://www.gphotoshow.com/wallpaper-slideshow-pro.php) to have my windows desktop cycle through all those shots and when I see one, I note down the picture number on a list (yes, old school paper and pencil, but I've asked the developer to add a feature that speaks to that need). That list is slowly but surely getting longer and at one point, I think I will sit down and at least work on those selected shots. I know this is not exactly what you are trying to do, but at least it's a fun way to handle all those shots that you otherwise never look at unless you sit down and wade through them, as you say.
6,745,751
**EDIT:** OK, I believe I've found a way around the issue using the info posted by @ManseUK along with @Johan's comment. As a n00b I can't answer my own question but I've added an explanation below the question in case it helps anyone else out. > > I am re-writing part of an e-commerce solution which was written by > another development team some years ago. In the new version, we are > experimenting with shortening the user journey using Ajax but doing so > gives JavaScript errors and causes some functions to fail. Dev URL is > here: > > > <http://cognition.thelightbulb.co.uk/type-18/general-purpose-lamps-and-bulbs/craftlight-daylight> > > > The errors appear once the dropdowns have been selected and the > product displays. > > > The errors are displaying most notably in IE7: > > > > ``` > Error: 'frm.qty' is null or not an object > Error: 'qty.value' is null or not an object > > ``` > > I believe this is where the problem is coming from: > > > > ``` > var frm = document.frmOrder; > var qty = frm.qty; > > ``` > > In the lines above, `frmOrder` is the name of the form and `qty` is > the name of the input for product quantity. > > > Compare that to <http://cognition.thelightbulb.co.uk/product-54> where > the product loads without the Ajax selection process and you'll see > that the functions work correctly. > > > I suspect that the problem is to do with the fact that `var frm = > document.frmOrder;` is not working due to the way it relates to the > DOM when loaded with Ajax. > > > I am using `innerHTML=xmlhttp.responseText` as the Ajax method. Is > there an alternative way to define `var frm` so that it will function > properly when loaded with Ajax? > > > **EDIT:** Using the info posted by @ManseUK along with @Johan's comment, I added another argument to `CheckMinQty(minorder)` so that it now looks like this... `function CheckMinQty(minorder,qty)` ...where `qty` is passed to the function on an `onclick` event as `document.forms['frmOrder'].qty.value` I then moved the whole function out into a separate .js file. It's maybe not the best approach but it still feels tidier for the Ajax call to just return workable HTML which `CheckMinQty` can use rather than bringing in a whole load of `<script>` and then trying to run it. Thanks for all the suggestions and I'd welcome any comments about the approach/solution outlined above.
2011/07/19
[ "https://Stackoverflow.com/questions/6745751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/851683/" ]
You need to treat both files as iterators and zip them. Izip will allow you to read the files in a lazy way: ``` from itertools import izip fa=open('file1') fb=open('file2') for x,y in izip(fa, fb): print x,y ``` Now that you've got pairs of lines, you should be able to parse them as you need and print out the correct formula.
Python's built-in [`zip()`](http://www.python.org/doc//current/library/functions.html#zip) function is ideal for this: ``` >>> get_values = lambda line: map(float, line.strip().split(',')[1:]) >>> for line_from_1,line_from_2 in zip(open('file1'), open('file2')): ... print zip(get_values(line_from_1), get_values(line_from_2)) ... print '--' ... [] -- [(53.0, 0.6), (45.0, 0.9), (23.0, 0.4)] -- [(65.0, 8.6), (45.0, 1.0), (32.0, 2.3)] -- >>> ``` From that, you should be able to use the values as you wish. Something like this: ``` print sum([x * y for x,y in zip(get_values(line_from_1), get_values(line_from_2))]) ``` I get this result: > > 81.5 > > > 677.6 > > >
45,964,584
I found [this](https://github.com/VladimirKulyk/SoundTouch-Android) on GitHub which is a wrapper for the great SoundTouch C++ library. I'm completely new to NDK though, so would any of you kindly explain to me how to set it up correctly? I downloaded the zip from GitHub and copied the directories into my existing project. Still, it couldn't find the native C++ functions. I tried compiling the library using `ndk-build` but I got two errors. This is my terminal log: ``` Android NDK: APP_PLATFORM not set. Defaulting to minimum supported version android-14. Android NDK: WARNING:/home/daniele/AndroidStudioProjects/Chords2/app/jni/Android.mk:soundtouch: non-system libraries in linker flags: -lgcc Android NDK: This is likely to result in incorrect builds. Try using LOCAL_STATIC_LIBRARIES Android NDK: or LOCAL_SHARED_LIBRARIES instead to list the library dependencies of the Android NDK: current module Android NDK: WARNING:/home/daniele/AndroidStudioProjects/Chords2/app/jni/Android.mk:soundtouch: non-system libraries in linker flags: -lgcc Android NDK: This is likely to result in incorrect builds. Try using LOCAL_STATIC_LIBRARIES Android NDK: or LOCAL_SHARED_LIBRARIES instead to list the library dependencies of the Android NDK: current module [armeabi-v7a] Compile++ thumb: soundtouch <= soundtouch-jni.cpp [armeabi-v7a] Compile++ thumb: soundtouch <= AAFilter.cpp [armeabi-v7a] Compile++ thumb: soundtouch <= FIFOSampleBuffer.cpp [armeabi-v7a] Compile++ thumb: soundtouch <= FIRFilter.cpp [armeabi-v7a] Compile++ thumb: soundtouch <= cpu_detect_x86.cpp [armeabi-v7a] Compile++ thumb: soundtouch <= RateTransposer.cpp [armeabi-v7a] Compile++ thumb: soundtouch <= SoundTouch.cpp [armeabi-v7a] Compile++ thumb: soundtouch <= TDStretch.cpp [armeabi-v7a] Compile++ thumb: soundtouch <= BPMDetect.cpp [armeabi-v7a] Compile++ thumb: soundtouch <= PeakFinder.cpp [armeabi-v7a] SharedLibrary : libsoundtouch.so [armeabi-v7a] Install : libsoundtouch.so => libs/armeabi-v7a/libsoundtouch.so [armeabi] Compile++ thumb: soundtouch <= soundtouch-jni.cpp /home/daniele/AndroidStudioProjects/Chords2/app/jni/soundtouch-jni.cpp:133:2: error: no matching function for call to 'convertInput16' convertInput16(ar, fBufferIn, BUFF_SIZE); ^~~~~~~~~~~~~~ /home/daniele/AndroidStudioProjects/Chords2/app/jni/soundtouch-jni.cpp:58:13: note: candidate function not viable: no known conversion from 'soundtouch::SAMPLETYPE *' (aka 'short *') to 'float *' for 2nd argument static void convertInput16(jbyte*, float*, int); ^ /home/daniele/AndroidStudioProjects/Chords2/app/jni/soundtouch-jni.cpp:210:16: error: no matching function for call to 'write' processed += write(fBufferIn, fBufferOut, nSamples * cha... ^~~~~ /home/daniele/AndroidStudioProjects/Chords2/app/jni/soundtouch-jni.cpp:56:12: note: candidate function not viable: no known conversion from 'soundtouch::SAMPLETYPE *' (aka 'short *') to 'const float *' for 1st argument static int write(const float*, queue<signed char>*, int, int); ^ 2 errors generated. make: *** [/home/daniele/AndroidStudioProjects/Chords2/app/obj/local/armeabi/objs/soundtouch/soundtouch-jni.o] Error 1 ```
2017/08/30
[ "https://Stackoverflow.com/questions/45964584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6427630/" ]
That's not possible because `Event` can't be referenced from within the template. (`as` is also not supported in template binding expressions) You need to make it available first: ``` class MyComponent { EventType = Event; ``` then this should work ``` [(ngModel)]="(event as EventType).acknowledged" ``` **update** ``` class MyComponent { asEvent(val) : Event { return val; } ``` then use it as ``` [(ngModel)]="asEvent(event).acknowledged" ```
* **Using my *TypeSafe* generics [answer](https://stackoverflow.com/a/69466380/1283715):** * **And inspired from [smnbbrv answer](https://stackoverflow.com/a/66154034/1283715) pass type explicitly as an optional argument when there is nowhere to infer the type from.** ``` import { Pipe, PipeTransform } from '@angular/core'; /** * Cast super type into type using generics * Return Type obtained by optional @param type OR assignment type. */ @Pipe({ name: 'cast' }) export class CastPipe implements PipeTransform { /** * Cast (S: SuperType) into (T: Type) using @Generics. * @param value (S: SuperType) obtained from input type. * @optional @param type (T CastingType) * type?: { new (): T } * type?: new () => T */ transform<S, T extends S>(value: S, type?: new () => T): T { return <T>value; } } ``` **Usage:** *template.html* ``` <input type="checkbox" *ngIf="event.end" [(ngModel)]="(event | cast: Event).acknowledged" [disabled]="(event | cast: Event).acknowledged" /> ``` *component.ts* ``` export abstract class AbstractEvent { end: boolean; } export class Event extends AbstractEvent { acknowledged: boolean; } export class MyComponent{ event: AbstractEvent; Event = Event; } ```
62,997,321
I have the below service and I am trying to inherit my service with an base class so I can put all the constant option data in the base class, > > Service class > > > ``` import { BaseNotification } from './baseNotification'; declare let toastr: any; @Injectable({ providedIn: 'root' }) export class NotificationService extends BaseNotification { constructor() { super(); toastr.options = this.options; } success(message: string, title?: string): void { toastr.success(message, title); } ``` > > BaseNotification Class > > > ``` export class BaseNotification { options = {}; constructor(){ this.options = { "closeButton": true, "positionClass": "toast-top-right", "preventDuplicates": false, "showDuration": "300", "hideDuration": "1000", "timeOut": "1000", "extendedTimeOut": "1000", "showEasing": "swing", "hideEasing": "linear", "showMethod": "fadeIn", "hideMethod": "fadeOut" } } } ``` But it does not recognize baseclass. I do not want to create an seperate child Service. Am I doing something wrong?
2020/07/20
[ "https://Stackoverflow.com/questions/62997321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7988437/" ]
`ex_dict.popitem()` it removes the last (most recently added) element from the dictionary
We can use: ``` dict.pop('keyname') ```
692,880
I am currently working on a program which sniffs TCP packets being sent and received to and from a particular address. What I am trying to accomplish is replying with custom tailored packets to certain received packets. I've already got the parsing done. I can already generated valid Ethernet, IP, and--for the most part--TCP packets. The only thing that I cannot figure out is how the seq / ack numbers are determined. While this may be irrelevant to the problem, the program is written in C++ using WinPCap. I am asking for any tips, articles, or other resources that may help me.
2009/03/28
[ "https://Stackoverflow.com/questions/692880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/59844/" ]
When a TCP connection is established, each side generates a random number as its initial sequence number. It is a strongly random number: there are security problems if anybody on the internet can guess the sequence number, as they can easily forge packets to inject into the TCP stream. Thereafter, for every byte transmitted the sequence number will increment by 1. The ACK field is the sequence number from the other side, sent back to acknowledge reception. [RFC 793](https://www.rfc-editor.org/rfc/rfc793), the original TCP protocol specification, can be of great help.
[RFC 793](http://www.faqs.org/rfcs/rfc793.html) section 3.3 covers sequence numbers. Last time I wrote code at that level, I think we just kept a one-up counter for sequence numbers that persisted.
102,305
I'm looking to migrate about 20 in-house researchers from their current XP workstations to thin-clients which connect to a VM running within our LAN. I'm planning on using HP thin-clients which use a linux based client os and the backend would be a dell rack server running Server 2008 Std. with Hyper-V. After talking to our software guy it seems as though I would have to purchase RDS cals for our users and VECD licenses on the client side. We currently have XP licenses for everyone and I'd hate to just throw those away. Can I not just set up 20 XP virtual machines (using our existing XP licenses) or is using RDS that much better? This licensing model is new to me so any and all help is greatly appreciated.
2010/01/13
[ "https://serverfault.com/questions/102305", "https://serverfault.com", "https://serverfault.com/users/9884/" ]
This entirely depends on what you're doing with your users. 20 VM's is going to be HARD on the server. A lot of memory, a lot of disk use, a lot of network use...I'd not try doing that. Terminal services are something we used to use. We could support on decent hardware about 15 to 20 sessions at a time. Problems...multimedia was crap, Office needs special consideration when installing on terminal services, and certain applications would spike the processor so that one user could hog the server and bog everyone down. This can be mitigated through resource provisioning, but still it's a management concern. We also had cases that were annoying to track down...we had a user that left a web browser open to a weather map loop, animated. There was some memory leak where that session BALLOONED until the server started thrashing. Users were disconnecting and reconnecting, sessions were abandoned with apps running, making the situation worse. When moving to a thin client solution you need to have some way of increasing availability. We had systems set up with Windows IP clustering, but that still had it's problems. And people would corrupt profiles because they don't understand that they're using a REMOTE system. Turning off their computer wasn't rebooting it. Multiple logins on different servers didn't help with this. And worse, we had one server that started rebooting with no rhyme or reason. Turned out someone was trying to run an intensive app that triggered a but in Windows that in turn rebooted the system and booted a dozen users off. You need to figure out if the applications are going to be *compatible* with this model of usage. Terminal services can do some weird things. Executables made from Director (a lot of shovelware comes like this for schools) ran like molasses on our terminals. Special niche software didn't like terminal services sometimes. For resources, you should definitely go terminal services. I think 20 VM's are hard unless you have multiple servers and have vmotion/vsphere/etc., plus you'd be essentially remodeling your environment to have an in-company cloud of sorts. I don't see the benefits to doing that over just having local desktops since you're essentially replicating your user desktops on a few big servers, minus the benefits of having local hardware to isolate issues and giving yourself a central point of failure. To have a really effective VM solution you need to invest quite a bit in the infrastructure so your users have enough reliability and availability to get their work done. Terminal services aren't a panacea either and you really need to test your applications to see if you're going to have a benefit. Also keep in mind that this is going to really push your network more. Terminal services may have improved since we used them many years ago. But if it tells you anything, we now use regular desktop machines for our users and use Deep Freeze to keep them intact and malware-free, especially after having to keep making "exceptions" for special software until it was useless to have terminal servers as people were more and more needing special case exceptions.
One extra thing to look out for on top of Bart's answer. It may not be possible for you to use your XP licenses in the VM. Some of these OEM copies of XP are locked onto specific vendor hardware and you may have some problems activating the VM. This problem won't exist with full retail versions of XP.
24,075,403
I know that, given a class, say, std::array, which has a member function, say, size(), we can call on that member function via a ".", that is, in the following code, ``` array<int,5> myarray; int s=myarray.size(); ``` s would be the integer representing the size of myarray. The tricky thing happens when member functions can also be called by the namespace operator "::". For example, I know that the following line of code is valid: ``` auto t=chrono::high_resolution_clock::now(); ``` Then, what's wrong with employing the syntax we originally used with array? ``` chrono::high_resolution_clock myclock; auto t=myclock.now(); ```
2014/06/06
[ "https://Stackoverflow.com/questions/24075403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3713167/" ]
`now()` is a `static` member function. This means that the function itself doesn't have a hidden `this` pointer. Instead, it's just like a regular function - just part of the class to avoid name collisions. (THe `high_resolution_clock` is a class, `chrono` is a namespace, in your example. Both use `::` to indicate "I want something from inside {namespace, class})
There is nothing *wrong* with the syntax you suggested. It works. However it creates an object, whereas the `::` version does not create any object. There doesn't seem to be much point in creating that object since it is not necessary to do so in order to call the static function. So it is simpler to just call the static function without creating the object.
61,121,201
so here is my auth.js code: ``` import locationHelperBuilder from 'redux-auth-wrapper/history4/locationHelper'; import { connectedRouterRedirect } from 'redux-auth-wrapper/history4/redirect'; import { createBrowserHistory } from 'history'; // import Spinner from '../components/layout/Spinner'; const locationHelper = locationHelperBuilder({}); createBrowserHistory(); export const UserIsAdmin = connectedRouterRedirect({ wrapperDisplayName: 'UserIsAdmin', // AuthenticatingComponent: Spinner, redirectPath: (state, ownProps) => locationHelper.getRedirectQueryParam(ownProps) || '/', allowRedirectBack: true, authenticatedSelector: state => state.user.isAuthenticated && state.user.isAdmin }); export const UserIsAuthenticated = connectedRouterRedirect({ wrapperDisplayName: 'UserIsAuthenticated', // AuthenticatingComponent: Spinner, redirectPath: (state, ownProps) => locationHelper.getRedirectQueryParam(ownProps) || '/', allowRedirectBack: true, authenticatedSelector: state => state.user.isAuthenticated }); export const UserIsNotAuthenticated = connectedRouterRedirect({ wrapperDisplayName: 'UserIsNotAuthenticated', // AuthenticatingComponent: Spinner, redirectPath: (state, ownProps) => locationHelper.getRedirectQueryParam(ownProps) || '/', allowRedirectBack: true, authenticatedSelector: state => !state.user.isAuthenticated }); ``` and here is where i need to make redux-auth-wrapper to wait until I update the state with the user data to send him wherever he was before refreshing the page: ``` const MainRoutes = ( { cookies } ) => { // state const { isAuthenticated } = useSelector( state => state.user ); // dispatch const dispatch = useDispatch(); const login = () => dispatch( loginAction() ); const logout = () => dispatch( logoutAction() ); // check if session is active ( cookie ) useEffect(() => { if( !isAuthenticated ) { const checkSession = async () => { const cookie = cookies.get('token'); if( cookie && cookie.trim() !== '' ) { axiosClient.defaults.headers.Authorization = `Bearer ${ cookie }`; login(); } else logout(); }; checkSession() } // eslint-disable-next-line react-hooks/exhaustive-deps }, [ cookies, isAuthenticated ]); return ( <Switch> <Route exact path="/" component={ Courses } /> <Route path="/admin" component={ UserIsAdmin( Admin ) } /> <Route path="/profile" component={ UserIsAuthenticated( Profile ) } /> <Route exact path="/login" component={ UserIsNotAuthenticated( Login ) } /> <Route exact path="/signin" component={ UserIsNotAuthenticated( Signin ) } /> <Route exact path="/send-email" component={ UserIsNotAuthenticated( Email ) } /> <Route exact path="/recover" component={ UserIsNotAuthenticated( Recover ) } /> <Route exact path="/policy" component={ Policy } /> <Route exact path="/usage" component={ Usage } /> <Route exact path="/faqs" component={ FAQS } /> </Switch> ); } export default withRouter(withCookies(MainRoutes)); ``` Here bassically I check if exists a session cookie, soy I auto log the user in. The problem is, that when I go to some route (for example: /admin, which is protected, and therefore is being supervised by redux-auth.wrapper), and I refresh the page, it always sends me back to '/', because the check of the isAuthenticated and isAdmin is done before my MainRoutes component can log the user in, which of course fails the check in the authenticated selector of the auth.js, and sends me to '/'. My first idea to solve this was to store those 2 flags in the localStorage, so I will be driven to the previous path even if my user didn't finished logging in. But I was wondering if there is any way to specificaly say to redux-auth-wrapper, to wait until my useEffect function has finished. Thank you.
2020/04/09
[ "https://Stackoverflow.com/questions/61121201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11926619/" ]
Variables have different types * the variable `rq` is a `str` * the attribut `answer` is an `int` Also, do not use an `elif` with the opposite condition of the `if` just use an `else` ``` def bst_q(question, answer): rq = input(str(question)) if rq == str(answer): print('Correct, Well done') else: print('wrong') ```
The mistake you are making here, is that you compare a `string` from `input()` with an `int` (26 in this case). So your comparison is: is 26 = "26"? Which fails, as the number 26 is not equal to the string 26. You could also add checks on the input type, if it is a sting and try to cast it to an int, but this should do the trick for the simple case. Your program just needs a little adjustment: ``` def bst_q(question, answer): rq = int(input(str(question))) if rq == answer: print ('Correct, Well done') elif rq != answer: print ('wrong') bst_q('What is 13 times 2?', 26) ``` The answer from @azro is right, in that you should not use the elif, but an else instead. Depending on what you want, you can either cast your answer to a string e.g.: `bst_q('What is 13 times 2?', "26")` or as I suggested, you cast the input into an int. Really depends on what you are trying to achieve here.
52,864,412
I have an input field like this: `<input myCurrencyFormatter type="text" [(ngModel)]="value" name="value">` The input value should be formatted to number such as: 1 024,50(this value should be only visible for input), but value in the ngModel should be stay not formated: 1024.05(dot instead a comma). How I can do it? This is my directive and pipe: <https://stackblitz.com/edit/angular-6smqvf?file=src%2Fapp%2Fapp.component.html> I don't know how I can input comma and save to model dot.
2018/10/17
[ "https://Stackoverflow.com/questions/52864412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7314051/" ]
This can be done by redefining getter and setter like so: ``` <input type="text" [(ngModel)]="displayValue" > ``` And in ts side: ``` get displayValue(){ return this.realValue + '$' ; } set displayValue(v){ this.realValue = v?.replace('$',''); } ```
There are probably several approaches. One solution is to use a custom property where you save the converted input to. Listen to input changes with `(change)` and do the conversions there. Find an example below: In the template: ``` <form (ngSubmit)="test(value)"> <input myCurrencyFormatter type="text" [ngModel]="value" (change)="storeMyValue($event)" name="value"> <button type="submit">Wtślij</button> </form> Custom value: {{ myCustomValue }} ``` And in the component: ``` myCustomValue: string; public storeMyValue(event) { // the following replacements are not very sophisticated, but they // show the idea this.myCustomValue = event.target.value.trim().replace(/\s+/g, '').replace(",","."); } ``` If you want to re-use this, you might want to consider to write a custom component for that case.
37,526,315
What is the best practice using ElasticSearch from Java? For instance one can easily find documentation and examples for delete-by-query functionality using [REST API](https://www.elastic.co/guide/en/elasticsearch/plugins/current/delete-by-query-usage.html). This is not the case for Java Transport Client. 1. Where can I find usage examples for Java Transport Client ? 2. Does Java Transport Client cover whole ElasticSearch functionality like HTTP client via REST API?
2016/05/30
[ "https://Stackoverflow.com/questions/37526315", "https://Stackoverflow.com", "https://Stackoverflow.com/users/418516/" ]
The best practice of using Elasticsearch from Java: [Follow This](http://elasticsearch-users.115913.n3.nabble.com/What-is-your-best-practice-to-access-a-cluster-by-a-Java-client-td4015311.html) Nexts: 1. You can follow the library : [JEST](https://github.com/searchbox-io/Jest/tree/master/jest) 2. Yes, in maximum time, Java Transport Client cover whole ElasticSearch functionality like HTTP client via REST API
To complete [@sunkuet02 answer](https://stackoverflow.com/questions/37526315/elasticsearch-http-client-vs-transport-client/37526762#37526762): As mentioned in [documentation](https://www.elastic.co/blog/found-interfacing-elasticsearch-picking-client), the `TransportClient` is the preferred way if you're using java (performance, serialization, ...). But the jar is quite heavy (with dependencies) and it requires that you use the same versions between client and server to work. If you want a very lightweight client, there is a new [Java REST client](https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/index.html) in Elastic 5.x. I don't know the differences with Jest, but it's compatible with last Elastic 5.x versions (but not with previous versions) and it's developed by the Elastic team. So it might be a good option to consider, according to your needs.
14,501,135
I want to compile following line of code through Eclipse but during built time i will get Error which i can not understand.. Is any one have a solution to solve it. ``` #include <boost/test/unit_test.hpp> #define BOOST_TEST_DYN_LINK #define BOOST_AUTO_TEST_MAIN #define BOOST_TEST_MODULE First_TestSuite BOOST_AUTO_TEST_CASE( First_TEst ) { BOOST_CHECK(2 == 2); } ``` --- Error > > 12:55:13 \*\*\*\* Incremental Build of configuration Debug for project > NewProject \*\*\*\* Info: Internal Builder is used for build g++ > "-IC:\boost\_1\_52\_0\boost\_1\_52\_0" -O0 -g3 -Wall -c -fmessage-length=0 > -o "src\NewProject.o" "..\src\NewProject.cpp" g++ -o NewProject.exe "src\NewProject.o" src\NewProject.o: In function > `ZN10First_TEst11test_methodEv': > C:\Users\sam\workspace1\NewProject\Debug/../src/NewProject.cpp:19: > undefined reference to` boost::unit\_test::unit\_test\_log\_t::set\_checkpoint(boost::unit\_test::basic\_cstring, unsigned int, boost::unit\_test::basic\_cstring)' > C:\Users\sam\workspace1\NewProject\Debug/../src/NewProject.cpp:19: > undefined reference to > `boost::test_tools::tt_detail::check_impl(boost::test_tools::predicate_result > const&, boost::unit_test::lazy_ostream const&, > boost::unit_test::basic_cstring<char const>, unsigned int, > boost::test_tools::tt_detail::tool_level, > boost::test_tools::tt_detail::check_type, unsigned int, ...)' > src\NewProject.o: In function` \_static\_initialization\_and\_destruction\_0': > C:\Users\sam\workspace1\NewProject\Debug/../src/NewProject.cpp:16: > undefined reference to > `boost::unit_test::ut_detail::auto_test_unit_registrar::auto_test_unit_registrar(boost::unit_test::test_case*, > unsigned long)' src\NewProject.o: In function` ZN5boost9unit\_test15unit\_test\_log\_tC1Ev': > C:/boost\_1\_52\_0/boost\_1\_52\_0/boost/test/unit\_test\_log.hpp:131: > undefined reference to `vtable for boost::unit_test::unit_test_log_t' > src\NewProject.o: In function` ZN5boost9unit\_test14make\_test\_caseERKNS0\_9callback0INS0\_9ut\_detail6unusedEEENS0\_13basic\_cstringIKcEE': > C:/boost\_1\_52\_0/boost\_1\_52\_0/boost/test/unit\_test\_suite\_impl.hpp:255: > undefined reference to > `boost::unit_test::ut_detail::normalize_test_case_name(boost::unit_test::basic_cstring<char const>)' > C:/boost_1_52_0/boost_1_52_0/boost/test/unit_test_suite_impl.hpp:255: > undefined reference to` boost::unit\_test::test\_case::test\_case(boost::unit\_test::basic\_cstring, > boost::unit\_test::callback0 > const&)' src\NewProject.o: In function > `ZN5boost9unit_test15unit_test_log_tD1Ev': > C:/boost_1_52_0/boost_1_52_0/boost/test/unit_test_log.hpp:93: > undefined reference to`vtable for boost::unit\_test::unit\_test\_log\_t' > c:/mingw/bin/../lib/gcc/mingw32/4.7.2/../../../libmingw32.a(main.o):main.c:(.text.startup+0xa7): > undefined reference to `WinMain@16' collect2.exe: error: ld returned 1 > exit status > > > 12:55:24 Build Finished (took 11s.567ms) > > >
2013/01/24
[ "https://Stackoverflow.com/questions/14501135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2005739/" ]
If you want to only use the header variant, you should include the following ``` #define BOOST_TEST_MODULE First_TestSuite #include <boost/test/included/unit_test.hpp> ``` instead of your ``` #include <boost/test/unit_test.hpp> ``` And you only need the `#define BOOST_TEST_MODULE First_TestSuite` with the header only variant.
You should use the `Single Header Variant of the UTF` from Boost. <http://www.boost.org/doc/libs/1_46_1/libs/test/doc/html/utf/user-guide/usage-variants/single-header-variant.html>
20,613,206
I have installed the PHP Cookbook from opscode and the chef-dotdeb cookbook found at [chef-dotdeb](https://github.com/ffuenf/chef-dotdeb) so that I can run **PHP 5.4** in the vagrant box. I would like to modify some of the default `php.ini` settings. According to the documentation for the chef php cookbook I can modify the settings using ``` node['php']['directives'] = {} ``` for example: ``` node['php']['directives'] = { :short_open_tag => 'Off' } ``` I have made the modification in the `webserver.rb` script I have created in my applications cookbook. When I provision or reload the vagrant box the `php.ini` settings remain unchanged. Any ideas what is wrong? The contents of the webserver.rb file are: include\_recipe "nginx" include\_recipe "php" node.default["php"]["directives"] = { :short\_open\_tag => 'Off' } Even when i remove the dotdeb cookbook so that the only php stuff comes from the official opscode php cookbook it still doesnt update any ini values. ADDITIONAL INFO I have looked at the code in the opscode php cookbook that actually injects the directives into it erb php.ini template: <https://github.com/opscode-cookbooks/php/blob/master/templates/ubuntu/php.ini.erb> The code that injects the appends the directives to the end of the file is: ``` <% @directives.sort_by { |key, val| key }.each do |directive, value| -%> <%= "#{directive}=\"#{value}\"" %> <% end -%> ``` this is always empty {} However.... if i modify it to... ``` <% node.default[:php][:directives].sort_by { |key, val| key }.each do |directive, value| -%> <%= "#{directive}=\"#{value}\"" %> <% end -%> ``` Then the directives ARE injected into the template. Im not a ruby expert. What is the fundamental difference between these 2 pieces of logic???
2013/12/16
[ "https://Stackoverflow.com/questions/20613206", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2361627/" ]
Had the same issue installing priestjims php with Apache. Installing Apache first and running apache2::mod\_php5 does not mean you can leave out php::apache2 that was the mistake for me. Solution is to include php::apache2 recipe and then it is writing it's php.ini to 'apache\_conf\_dir'. This way development ini settings like ``` default['php']['directives'] = { 'display_errors' => 'On', 'allow_url_fopen' => 'On', 'allow_url_include' => 'On', 'short_open_tag' => 'Off' } ``` will be correctly applied to apache's php.ini.
I know it's quite old question, but it's might help others. the `@` symbol meant it's a variable. Template resources have variables property and you can add the directives attribute there. More on the doc: ``` This attribute can also be used to reference a partial template file by using a Hash. For example: template "/file/name.txt" do variables :partials => { "partial_name_1.txt.erb" => "message", "partial_name_2.txt.erb" => "message", "partial_name_3.txt.erb" => "message" }, end where each of the partial template files can then be combined using normal Ruby template patterns within a template file, such as: <% @partials.each do |partial, message| %> Here is <%= partial %> <%= render partial, :variables => {:message => message} %> <% end %> ``` <https://docs.getchef.com/resource_template.html> If you see the `ini` recipe of cookbook php: ``` template "#{node['php']['conf_dir']}/php.ini" do source node['php']['ini']['template'] cookbook node['php']['ini']['cookbook'] unless platform?('windows') owner 'root' group 'root' mode '0644' end variables(:directives => node['php']['directives']) end ``` <https://github.com/opscode-cookbooks/php/blob/master/recipes/ini.rb> it's assigning the `node['php']['directives']` to variables in template.
26,163,856
I'd like to upload an app written in swift. Application loader delivers the app successfully, but after a few minutes I get a reply by apple telling: > > Invalid Swift Support - The bundle contains an invalid implementation of Swift. The app may have been built or signed with non-compliant or pre-release tools. Visit developer.apple.com for more information. > > > I use xCode Version 6.0.1 (6A317), Swift iOS SDK 8.0 and just build the app with xcode. Where can I find any information on how to get a valid implementation of swift? Apple does not say anything concrete. Thx
2014/10/02
[ "https://Stackoverflow.com/questions/26163856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1776548/" ]
OK, I have been working on this for many hours now and finally found a solution. To pre-frame the answer here is what I did: - tried everything in the previous answers - spent an hour on the phone with Apple Tech support. - read every Apple developer forum having to do with "invalid swift" in their developer network. Tried each of the proposed solutions. I finally uninstalled and reinstalled Xcode and what do you know, it works now. Sometimes I don't know why this isn't my first idea for a [solution](http://www.reddit.com/r/Jokes/comments/2wf5ge/a_mechanical_engineer_electrical_engineer/).
I actually just solved this with a completely different, unrelated and really weird fix. Had the above error, but did NOT change anything in the Project or build Environment. After a lot of Rebuild and Upload Cycles, it turned out that it was an Ad-Hoc certificate that was causing this issue. Using fastlane and setting the `gym` flag ad\_hoc to false as well as using a `Release` Config for the build (not sure which one fixed it) finally worked. Here is my `gym` line: ``` identifier = "de.xxx.yyy" config = "Release" ad_hoc = false scheme = "Schema" gym(verbose: false, scheme: scheme, codesigning_identity: "iPhone Distribution: YTB)", configuration: config) ```
25,276,919
I'm using snap.svg I have index.html ``` <!Doctype> <html> <head> <title>MAP_TEST</title> <meta charset="utf-8"> <script type = "text/javascript" src = "JS/jquery.js"></script> <script type = "text/javascript" src = "JS/init.js"></script> <script type = "text/javascript" src = "JS/snap.svg.js"></script> </head> <body> <div class="comm_cont"> <div id = "svgborder"> <svg id = 'svgmain'></svg> </div> </div> </body> </html> ``` And init.js ``` $( document ).ready(function() { var s = Snap("#svgmain"); var g = s.group(); Snap.load("SVGFILES/3k1e-test.svg",function(lf) { g.append(lf); //trying to load picture... Scale button in future $('<img />', { src: 'PNG/plus.png', width: '30px', height: '30px', id: 'buttoninrk' }).appendTo($('.comm_cont')); //this button must be on picture //but in front of the picture svg element //And i can't click the button }); }); ``` I played with z-indexes of **#svgborder** and **#buttoninkr** but it didn't help me. How to put button in front of svg element? ``` #buttoninkr, #svgborder { position: absolute; } #svgborder { border:5px solid black; z-index: 0; margin-left:auto; border-radius: 5px; display: inline-block; } #buttoninkr { z-index: 1; } ``` Added css code with z-indexes. There is a reason why i'm not using svg buttons instead jquery image button. **Ok, as you can see #svgmain in front of plus.png** <http://jsfiddle.net/3wcq9aad/1/> Any ideas? Solved ``` #svgborders { position: absolute; background-color: #535364; border:5px solid black; z-index: 0; margin-left:auto; border-radius: 5px; display: inline-block; } #buttoninrk, #buttondekr, #home_btn { position: inherit; top:0; margin:10px; z-index: 1; } #buttoninrk { right:0px; } #buttondekr { right:60px } ```
2014/08/13
[ "https://Stackoverflow.com/questions/25276919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3564452/" ]
``` $ brew install zbar ``` and after that ``` $ pip install zbar ``` The header files will then be found (zbar.h)
I encountered this issue recently while attempting to launch a service locally from Mac OS in a virtual environment, that imports zbar in the python application. The service was still running python2.7. Having the service running in a virtual environment I was unwilling to attempt anything that required global system changes. I solved it by having to install zbar through Homebrew (globally). Then exporting flags or implicit rules used in the C compiling "recipe" to the virtual environment. Finally I installed a similar library to the zbar dependancy in the virtual environment. ``` $ brew install zbar ``` Then when sourced in the virtual environment I do the following to change the implicit rules in the c compilation recipe: ``` $ export LDFLAGS="-L$(brew --prefix zbar)/lib" $ export CFLAGS="-I$(brew --prefix zbar)/include" ``` Finally I install a light version of zbar inside the venv: ``` $ pip install zbarlight ``` After the above, with the additional dependancy of pyzbar below included in my requirements.txt I am able to import zbar with python2.7 in the virtual environment. ``` pyzbar==0.1.7 ``` Testing the import in the virtual environment: ``` $ python >>> import zbar >>> ``` Hope this helps someone in the future. I struggled quite a bit in getting this to work and resources regarding zbar are fairly scarce.
8,560,320
``` >>> False in [0] True >>> type(False) == type(0) False ``` The reason I stumbled upon this: For my unit-testing I created lists of valid and invalid example values for each of my types. (with 'my types' I mean, they are not 100% equal to the python types) So I want to iterate the list of all values and expect them to pass if they are in my valid values, and on the other hand, fail if they are not. That does not work so well now: ``` >>> valid_values = [-1, 0, 1, 2, 3] >>> invalid_values = [True, False, "foo"] >>> for value in valid_values + invalid_values: ... if value in valid_values: ... print 'valid value:', value ... valid value: -1 valid value: 0 valid value: 1 valid value: 2 valid value: 3 valid value: True valid value: False ``` Of course I disagree with the last two 'valid' values. Does this mean I really have to iterate through my valid\_values and compare the type?
2011/12/19
[ "https://Stackoverflow.com/questions/8560320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/532373/" ]
The problem is not the missing type checking, but because in Python `bool` is a subclass of `int`. Try this: ``` >>> False == 0 True >>> isinstance(False, int) True ```
As others have written, the "in" code does not do what you want it to do. You'll need something else. If you really want a type check (where the check is for exactly the same type) then you can include the type in the list: ``` >>> valid_values = [(int, i) for i in [-1, 0, 1, 2, 3]] >>> invalid_values = [True, False, "foo"] >>> for value in [v[1] for v in valid_values] + invalid_values: ... if (type(value), value) in valid_values: ... print value, "is valid" ... else: ... print value, "is invalid" ... -1 is valid 0 is valid 1 is valid 2 is valid 3 is valid True is invalid False is invalid foo is invalid >>> ``` Handling subtypes is a bit more difficult, and will depend on what you want to do.
3,307,226
While working on a problem, i transformed a function into the following form: $$y=\frac{26+17x}{17-2x}$$ Is there an efficient way to find the positive integer solutions of this problem if the numbers in the function get bigger?
2019/07/29
[ "https://math.stackexchange.com/questions/3307226", "https://math.stackexchange.com", "https://math.stackexchange.com/users/692163/" ]
You want $\frac{26+17x}{17-2x}$ to be an integer, for some integer $x$. General idea is that for sufficiently large $|x|$ you will have $-9<\frac{26+17x}{17-2x}<-8$. So just solve this system of inequalities, get boundaries for $x$ and check them
As $17-2x$ idd $$(17-2x)\mid(26+17x)\iff(17-2x)\mid2(26+17x)$$ $$2y=\dfrac{2(26+17x)}{17-2x}=\dfrac{52+289}{17-2x}-17$$ $\implies17-2x$ must divide $52+289=11\cdot31$ $\implies17-2x$ must lie in $\in[\pm1,\pm11,\pm31,\pm341]$ But $y>0\implies(17x+26)(2x-17)<0\implies-\dfrac{26}{17}<x<\dfrac{17}2<9$ As $x$ is an integer, $-\dfrac{26}{17}> -2,-1\le x\le8$
51,757,837
The visual studio stopped sending my commits to the bitbucket and this error appears > > Error encountered while cloning the remote repository: Git failed with a fatal error. > HttpRequestException encountered. > There was an error submitting the request. > can not spawn > > > C / Program Files (x86) / Microsoft Visual Studio / 2017 / Community / > Common7 / IDE / CommonExtensions / Microsoft / TeamFoundation / Team > Explorer / Git / mingw32 / libexec / git-core / git-askpass.exe: No > such file or directory > > > could not read Password for 'https: //gustavobedsamarpes@bitbucket.org': terminal prompts disabled > The error occurs when I try to clone my repository or commit > > >
2018/08/09
[ "https://Stackoverflow.com/questions/51757837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10200626/" ]
I have added my password to remote URL. (Team Explorer > Repository Settings > Remotes) <https://username:password@bitbucket.org/username/myproject.git>. After that my problem has solved.
A better solution. ------------------ > > **After chatting with Chad Boles (who maintains Team Explorer in Visual Studio), we worked out another option. This is preferred over overwriting the files in the Visual Studio installation as this may break future updates and can cause hard to debug issues in the future.** > > > The trick is, until Visual Studio actually ships with Git credential Manager for Windows 1.18.4 or newer (it should after Visual Studio 2019 preview 4.0 or newer), to configure the specific installation location of the Git credential manager in your Git Global Config: 1. [Install the latest version of GCMW-1.xx.x.exe](https://github.com/Microsoft/Git-Credential-Manager-for-Windows/releases) in your system and/or update to the latest version of [Git for Windows](https://git-scm.com/download/win) which should include GCM. 2. Update your global git config to point to a specific implementation of the Git credential Manager: ``` c:\>git config --global --edit ``` Update the `[credential]` section to read: ``` [credential] helper = C:\\\\Program\\ Files\\\\Git\\\\mingw64\\\\libexec\\\\git-core\\\\git-credential-manager.exe ``` Ensure the path points to where the latest Git Credential Manager can be found on your system. Mind all of the escapes needed to make paths work in the global git config. An alternative that doesn't require config changes -------------------------------------------------- Another option is to install the latest version of Git for Windows (which already ships with the Git credential Manager for Windows 1.18.4) and perform the initial clone and authentication from the command line. This will store the credentials in the Windows Credential Store, after which Visual Studio will happily pick them up.
10,650,443
I have this error while trying to get the tokens the code to make the lexical analysis for the Minic langauge ! ``` document.writeln("1,2 3=()9$86,7".split(/,| |=|$|/)); document.writeln("<br>"); document.writeln("int sum ( int x , int y ) { int z = x + y ; }"); document.writeln("<br>"); document.writeln("int sum ( int x , int y ) { int z = x + y ; }".split(/,|*|-|+|=|<|>|!|&|,|/)); ``` I get error on the debugger for the last line Uncaught SyntaxError: Invalid regular expression: Nothing to repeat !!
2012/05/18
[ "https://Stackoverflow.com/questions/10650443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1241074/" ]
You need to escape special characters: ``` /,|\*|-|\+|=|<|>|!|&|,|/ ``` [See](http://www.fon.hum.uva.nl/praat/manual/Regular_expressions_1__Special_characters.html) what special characters need to be escaped:
You need to escape the characters `+` and `*` since they have a special meaning in regexes. I also highly doubt that you wanted the last `|` - this adds the empty string to the matched elements and thus you get an array with one char per element. Here's the fixed regex: ``` /\*|-|\+|=|<|>|!|&|,/ ``` However, you can make the it much more readable and maybe even faster by using a character class: ``` /[-,*+=<>!&]/ ``` Demo: ``` js> "int sum ( int x , int y ) { int z = x + y ; }".split(/[-,*+=<>!&]/); [ 'int sum ( int x ', ' int y ) { int z ', ' x ', ' y ; }' ] ```
71,209,830
I run a site that displays user-generated SVGs. They are untrusted, so they need to be sandboxed. I currently embed these SVGs using `<object>` elements. (Unlike `<img>`, this allows loading external fonts. And unlike using an `<iframe>`, the `<object>` resizes to the SVG's content size. [See this discussion.](https://stackoverflow.com/questions/4476526/do-i-use-img-object-or-embed-for-svg-files)) However, I don't know whether these SVGs are appropriately sandboxed when using `<object>`. The `<iframe>` permissions model is fairly clear, e.g. `<iframe sandbox="allow-scripts">` disallows everything except running scripts. But what is the sandbox/permission model for `<object>` elements? * When I embed a page using `<object>`, what can that page do by default? E.g. what cookies can it access? Is it the same as an `<iframe>` without the `sandbox` attribute? * What are the implications of hosting the user content SVGs on the same domain? Should I instead host them on `foobarusercontent.com`? * Does the `<object>` tag support an equivalent of the `sandbox` attribute? Is there another way to set permissions for an `<object>`? * What specifications describe the security model for `<object>`?
2022/02/21
[ "https://Stackoverflow.com/questions/71209830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/229792/" ]
First change the `RespData` field's type: ```golang type response struct { Status string `json:"status"` ErrorCode string `json:"error-code"` RespMessage string `json:"message"` RespData interface{} `json:"data"` } ``` Then, depending on what request you are making, set the `RespData` field to a pre-allocated instance of a pointer to the expected type: ```golang r, err := http.Get("https://some_api.com/loginData") if err != nil { return err } defer r.Body.Close() // check r.StatusCode and make sure it's correct data := loginData{} resp := response{RespData: &data} if err := json.NewDecoder(r.Body).Decode(&resp); err != nil { return err } fmt.Println(data) ```
@mkopriva as you said tried this suggestion it worked. ```golang package main import ( "encoding/json" "fmt" "strings" ) type loginData struct { Token string `json:"token"` RefreshToken string `json:"refresh-token"` } type userdata struct { FirstName string `json:"first-name"` LastName string `json:"last-name"` Age string `json:"age"` Phone string `json:"phone"` Address string `json:"address"` } type response struct { Status string `json:"status"` ErrorCode string `json:"error-code"` RespMessage string `json:"message"` RespData interface{} `json:"data"` } func main() { jsonresp_1 := `{ "status" : "success", "error-code" : "", "message" : "login successful", "data" : { "token" : "token value", "refresh-token" : "refresh token value" } }` jsonresp_2 := `{ "status" : "success", "error-code" : "", "message" : "user data fetched", "data" : { "first-name": "josh", "last-name" : "walter", "age" : "30", "phone": "1234567890", "address" : "x street, dc" } }` resp1 := strings.NewReader(jsonresp_1) data1 := loginData{} respdata1 := response{RespData: &data1} if err := json.NewDecoder(resp1).Decode(&respdata1); err != nil { fmt.Println(err) } fmt.Printf("token : %s \nrefreshtoken : %s \n", data1.Token, data1.RefreshToken) fmt.Println("-------------------") resp2 := strings.NewReader(jsonresp_2) data2 := userdata{} respdata2 := response{RespData: &data2} if err := json.NewDecoder(resp2).Decode(&respdata2); err != nil { fmt.Println(err) } fmt.Printf("firstname : %s \nlastname : %s ", data2.FirstName, data2.LastName) } ``` Output ====== ``` ⚡ ⇒ go run main.go token : token value refreshtoken : refresh token value ------------------- firstname : josh lastname : walter ```
4,149,374
I have a collection of objects (IQueryable). Each object has various properties, some string some datetime, I'm not concerned about the datetime properties. How can I iterate through each object and return a collection of those objects that maybe have null values in one or more fields For simplicity, consider a collection of Employees Each employee may have two properties: FirstName (string) LastName (string) I'd like to have a method that could iterate through all employees in the employee collection and return a collection of employees that either have first name or last name missing, i.e null or an empty string. using .NET 3.5 with C#
2010/11/10
[ "https://Stackoverflow.com/questions/4149374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/155992/" ]
``` Employees.Where(e => string.IsNullOrEmpty(e.FirstName) || string.IsNullOrEmpty(e.LastName)) ```
If I understand the question, the solution should be pretty trivial: ``` IEnumerable<Employee> collection = iQuaryable.AsEnumerable(); List<Employee> myCollection = new List<Employee>(); foreach(var emp in collection) { if(string.IsNullOrEmpty(emp.LastName) || string.IsNullOrEmpty(emp.FirstName)) myCollection.Add(emp); } ``` where the iQuaryable is the instance of your IQuaryable implementation.
15,966
Which one is the correct use? > > She judged him **wrong**. > > > She judged him **wrongly**. > > > Or, are both correct, but have slightly different meanings?
2011/03/11
[ "https://english.stackexchange.com/questions/15966", "https://english.stackexchange.com", "https://english.stackexchange.com/users/4744/" ]
> > She judged him wrong. > > > This means she decided he was wrong in something he did or said. > > She judged him wrongly. > > > This means the error was hers. Usually you would express that this way: > > She judged him unfairly. > > > But *wrongly* works as well.
There are two different structures. "Wrong" may be either the complement of the verb (what she judged him to be) or an adverb modifying the verb (how she did the judging). As others have said, "wrongly" can only be the adverb, but "wrong" can be either - though in more formal use, it would tend to be used only as the complement.
3,003,494
if $A = \begin{bmatrix} 1 &0 &0 \\i& \frac{-1+ i\sqrt 3}{2} &0\\0&1+2i &\frac{-1- i\sqrt 3}{2} \end{bmatrix}$.Then the find the trace of $A^{102}$? My attempt : i know that eigenvalue of A are $1,w$ and $w^2$ As im not able to proceed further pliz help me
2018/11/18
[ "https://math.stackexchange.com/questions/3003494", "https://math.stackexchange.com", "https://math.stackexchange.com/users/557708/" ]
The matrix $A$ has eigenvalues the cube roots of unity $1, j=\mathrm e^{\tfrac{2i\pi}3}$ and $\bar{\mkern-1muj\mkern2mu}$, and its characteristic polynomial is $X^3-1$. So, by *Hamilton-Cayley*, we have $\;A^3=I$, therefore $\;A^{102}=(A^3)^{34}=I$ and $$\operatorname{Tr}\bigl(A^{102}\bigr)=\operatorname{Tr}(I)=3.$$
In general, for any polynomial p(X) and any square matrix A, the eigenvalues of p(A) are p($\lambda$), where $\lambda$ are the eigenvalues of A. In your case, the polynomial is $X^{102}$ and therefore the eigenvalues of $A^{102}$ will be $1, w^{102} and (w^2)^{102}=w^{204}$ , since as you noted, the eigenvalues of A can be read off the main diagonal and are $1,w,w^2$ Since w is a third root of the unity, $w^3=1$ and so $w^{102}=w^{204}=1$ and therefore the trace is the sum of the three values namely $1+1+1=3$
52,970,047
Please could you help correct this code! It's for finding all perfect numbers below the set limit of 10,000, I've used comments to explain what I'm doing. Thanks! ``` #Stores list of factors and first perfect number facs = [] x = 1 #Defines function for finding factors def findfactors(num): #Creates for loop to find all factors of num for i in range(1, num + 1): if num % i == 0: #Stores factor in facs facs.append(i) #Activates loop while x < 10000: #Finds factors of x and appends them to list findfactors(x) #Finds sum of list facsum = sum(facs) #Makes decision based on sum of factors and original number if facsum == x: #Ouputs and increases x print(x) x += 1 else: #Increases x x += 1 ```
2018/10/24
[ "https://Stackoverflow.com/questions/52970047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10552237/" ]
Found the problem! Should have been: ``` for i in range(1, num - 1) ``` Rather than: ``` for i in range(1, num + 1) ``` Thanks to all contributors!
intialize list inside the def and return and the range should not include the original `num` so range would be from 1 to num which includes 1 but excludes orginal `num` so it will generate range from `1` to `num-1` ``` #Stores list of factors and first perfect number x = 1 #Defines function for finding factors def findfactors(num): facs = [] for i in range(1, num): if num % i == 0: #Stores factor in facs facs.append(i) return facs #Activates loop while x < 1000: #Finds factors of x and appends them to list facs=findfactors(x) #Finds sum of list facsum = sum(facs) #Makes decision based on sum of factors and original number if facsum == x: #Ouputs and increases x print(x) x+= 1 ``` Much faster than generating list Approach from [What is the most efficient way of finding all the factors of a number in Python?](https://stackoverflow.com/questions/6800193/what-is-the-most-efficient-way-of-finding-all-the-factors-of-a-number-in-python) ``` #Stores list of factors and first perfect number x = 1 #Defines function for finding factors from functools import reduce def factors(n): return set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))) #Activates loop while x < 10000: #Finds factors of x and appends them to list facs=factors(x) facs.remove(x) # remove original number as it is not required further #Finds sum of list facsum = sum(facs) #Makes decision based on sum of factors and original number if facsum == x: #Ouputs and increases x print(x) x+= 1 ```
55,140,674
I have two screens in my app. Screen A runs a computationally expensive operation while opened, and properly disposes by cancelling animations/subscriptions to the database when `dispose()` is called to prevent memory leaks. From Screen A, you can open another screen (Screen B). When I use `Navigator.pushNamed`, Screen A remains in memory, and `dispose()` is not called, even though Screen B is now shown. Is there a way to force disposal of Screen A when it is not in view? Example code where first route is never disposed: ``` import 'package:flutter/material.dart'; void main() { runApp(MaterialApp( title: 'Navigation Basics', home: FirstRoute(), )); } class FirstRoute extends StatefulWidget { @override _FirstRouteState createState() => _FirstRouteState(); } class _FirstRouteState extends State<FirstRoute> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('First Route'), ), body: RaisedButton( child: Text('Open route'), onPressed: () { Navigator.push( context, MaterialPageRoute(builder: (context) => SecondRoute()), ); }, ), ); } @override void dispose() { // Never called print("Disposing first route"); super.dispose(); } } class SecondRoute extends StatefulWidget { @override _SecondRouteState createState() => _SecondRouteState(); } class _SecondRouteState extends State<SecondRoute> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Second Route"), ), body: RaisedButton( onPressed: () { Navigator.pop(context); }, child: Text('Go back!'), ), ); } @override void dispose() { print("Disposing second route"); super.dispose(); } } ```
2019/03/13
[ "https://Stackoverflow.com/questions/55140674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9673174/" ]
I know it's a bit late but I think you should override the `deactivate` method. Since we are changing the page we are not actually destroying it, that's why the `dispose` isn't being called. If you'd like more information [this page lists](https://www.developerlibs.com/2019/12/flutter-lifecycle-widgets.html) the lifecycle of the stateful widgets. From the link: > > 'deactivate()' is called when State is removed from the tree, but it might be > reinserted before the current frame change is finished. This method exists basically > because State objects can be moved from one point in a tree to another. > > >
Not only to call 'deactivate()' but also to use 'Navigator.pushReplacement()' for page moving is necessary. Not working if you are using 'Navigator.push()'.
233,247
I've noticed that one of the cores on a four-core laptop is pegged, and the temp is very high. I found this in `top`: ``` PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 359 root 20 0 188684 147228 1552 R 99.4 5.0 111:19.91 systemd-udevd 20011 root 20 0 188320 147604 2076 S 11.0 5.0 0:00.33 systemd-udevd 11053 dotanco+ 20 0 3030036 918672 49608 S 9.6 31.2 280:40.65 firefox 3468 dotanco+ 20 0 3612776 136740 43484 S 1.7 4.6 57:02.52 plasma-desktop 20006 root 20 0 0 0 0 Z 1.0 0.0 0:00.37 systemd-udevd ``` Why might `systemd-udev` be hammering the CPU? This is a Kubuntu 14.10 system: ``` $ uname -a Linux loathe 3.16.0-44-generic #59-Ubuntu SMP Tue Jul 7 02:07:39 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux $ cat /etc/issue Ubuntu 14.10 \n \l ``` **EDIT:** I notice that in addition to the pegged CPU, there is an additional problem. Newly connected USB devices, such as a USB mass storage device or keyboard, will show up in `lsusb` but are unusable. The mass storage device is not auto mounted, and the USB keyboard does not work. I have not tried to manually mount the USB drive. As per Bratchley's suggestion, [here is the strace](http://pastebin.com/suBsiz4d) of the `systemd-udev` process with ID 359.
2015/10/01
[ "https://unix.stackexchange.com/questions/233247", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/9760/" ]
It looks like libmtp found a device, but it's unable to disconnect it properly and it's checking for it constantly. It happens with certain devices and can be disabled by editing **/lib/udev/rules.d/69-libmtp.rules** Look for a couple of lines that look like this (at the end of the file): ``` # Autoprobe vendor-specific, communication and PTP devices ENV{ID_MTP_DEVICE}!="1", ENV{MTP_NO_PROBE}!="1", ENV{COLOR_MEASUREMENT_DEVICE}!="1", ENV{libsane_matched}!="yes", ATTR{bDeviceCl ass}=="00|02|06|ef|ff", PROGRAM="/usr/lib/udev/mtp-probe /sys$env{DEVPATH} $attr{busnum} $attr{devnum}", RESULT=="1", SYMLINK+="li bmtp-%k", ENV{ID_MTP_DEVICE}="1", ENV{ID_MEDIA_PLAYER}="1" ``` Comment the second line by putting a # before ENV, so that it looks like: ``` #ENV{ID_MTP.... ``` Restart your computer or run `sudo systemctl restart systemd-udevd` and enjoy your free CPU cycles :)
There is a bug in the kernel that cause systemd-udevs 100% CPU usage. So, the work around is to reboot the system, press and hold Shift during loading Grub. Then select the older kernel listed in the bootloader list. This work fine for me.
270,391
I'm using MessageFormat to format some addresses with a template like this: ``` "{0}\n{1}\n{2}\n{3}, {4} {5}" ``` where * 0 = street 1 * 1 = street 2 * 2 = street 3 * 3 = city * 4 = state * 5 = zip Most of these fields are optional when captured. How do I avoid having an empty line when for instance, there is not street 3? I could use a template like this "{0}{1}{2}{3}{4}{5}" and then substitute either "street 3\n" or "" accordingly, but then the template doesn't provide much benefit toward formatting. Is there a way to include conditionals in the format string? Or is there another, preferably lightweight, templating tool available that supports conditional formatting?
2008/11/06
[ "https://Stackoverflow.com/questions/270391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21176/" ]
IMHO [Chunk Templating engine](http://www.x5software.com/chunk/) is the best. The jar file only has **180 KB**! and support **IF** and **iteration**. How cool is that !
Freemarker is pretty good. It's light, fast, has conditional formatting, and a tonne of other features.
8,080,496
I want to get an exclusive tail set of a SortedSet. The shortest method I can come up with is: ``` private void exclusiveTailSet(SortedSet<String> s, String start) { System.out.println(s); // [Five, Four, One, Six, Start, Three, Two] SortedSet<String> t = s.tailSet(start); System.out.println(t); // [Start, Three, Two] Iterator<String> i = t.iterator(); i.next(); SortedSet<String> u = t.tailSet(i.next()); System.out.println(u); // [Three, Two] } ``` The [javadoc for tailSet](http://download.oracle.com/javase/1.4.2/docs/api/java/util/SortedSet.html#tailSet%28java.lang.Object%29) suggests asking for the subset starting from the next element in the domain (i.e. for Strings calling `s.tailSet(start+"\0");`), however I'm actually working with objects such that it would be much more of an overhead to create it. **What is an efficient and clean general method to create an exclusive tail set?**
2011/11/10
[ "https://Stackoverflow.com/questions/8080496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/171296/" ]
is this helpful? (I just copy and paste your codes in question, and did some change: ``` private void exclusiveTailSet(SortedSet<String> s, String start) { SortedSet<String> t = s.tailSet(start); t.remove(t.first()); } ``` and if you have "start" element as parameter, it would also be ``` t.remove(start) ; ```
Guava version 11: ``` SortedSet exclusiveTailSet = Sets.filter(eSortedSet, Ranges.greaterThan(start)); ``` **p.s.** There is also a **hack** for SortedSet in case you couldn't use NavigableSet. The solution is to add for the search pattern a special symbol (start+"\0"). And this addition symbol will change the hashCode and thus the default tailset implementation of a SortedSet will work fine: ``` SortedSet<String> t = s.tailSet(start+"\0"); ``` It will be an equivalent of java.util.TreeSet#tailSet(E fromElement, boolean *inclusive*) with **false** value in a second parameter. --- God bless that the last com.google.common.collect.ImmutableSortedSet (since version 12) has an implementation of NavigableSet also.
68,876,845
So currently I am trying to make an app where when the player collides with the enemy, the enemy disappears. I have achieved this by writing this code; ``` func didBegin(_ contact: SKPhysicsContact) { var firstBody = SKPhysicsBody() var secondBody = SKPhysicsBody() if contact.bodyA.node?.name == "Player" { firstBody = contact.bodyA secondBody = contact.bodyB }else { firstBody = contact.bodyB secondBody = contact.bodyA } if firstBody.node?.name == "Player" && secondBody.node?.name == "Enemy" { } if contact.bodyA.categoryBitMask == 1 && contact.bodyB.categoryBitMask == 2 { self.enumerateChildNodes(withName: "Enemy") { (node:SKNode, nil) in if node.position.y < 550 || node.position.y > self.size.height + 550 { node.removeFromParent() } } } } ``` However, because I'm enumeratingChildNodes with the name "Enemy", every enemy disappears on screen. I only want the one I hit to disappear. Any help? Thanks!
2021/08/21
[ "https://Stackoverflow.com/questions/68876845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The reason for the init statement is to limit the scope of variable and allow the *reusing* of values returned by functions. C++17 introduced dedicated init statements for both `if` and `for-each` Sometimes you might want to check if a function failed by returing 0 or nullptr before using the value it returned and you don't want to polute the scope. ```cpp void foo() { if(int var = some_function(); var != 0) { // use var use_var(var); } else throw std::exception(); } ``` It may not be that common in the `if` statement but comes more in handy in the `for-each` statement. Look at this example. ```cpp struct test { std::vector<int> elements; auto& items() { return elements; } } test get_test() { return {}; } void foo() { // for(auto e : get_test().items()) - this would cause a new test struct element to be created per each iteration and would invalidate the iterator. for(auto obj = get_test(); auto e : obj) // test created only once, no iterator invalidation { std::cout << e << '\n'; } } ```
The condition expression you have put in `if` statement is an operation. If the operation is successful (meaning `n` is declared and is filled with 10), then it is valued as `true`. So it will compile and the `if` statement will be ran.
46,480
Is the contraction from *that will* to *that’ll* an actual word or not?
2011/10/27
[ "https://english.stackexchange.com/questions/46480", "https://english.stackexchange.com", "https://english.stackexchange.com/users/14251/" ]
Well, *that'll* is not a word but a contraction. Some dictionaries include it, some don't. *That'll* clearly exists, and is used to some degree. It's just a matter of whether it has been used enough to be widely understood. An example of its usage would be in the song [That'll be the day](http://en.wikipedia.org/wiki/That%27ll_Be_the_Day) (1957) by Buddy Holly.
The [Corpus of Contemporary American English](https://www.english-corpora.org/coca/) has 3221 uses of this contraction. Since MetaEd mentions this as a part of the phrase "that'll be the day", I'll mention that the phrase appears only 40 times in COCA, so 99% of the time it is used in other contexts. The Google n-gram viewer shows many uses back to the early 19th century: <http://books.google.com/ngrams/graph?content=that%27ll&year_start=1800&year_end=2000&corpus=0&smoothing=3> <http://www.google.com/search?q=%22that%20%27%20ll%22&tbs=bks:1,cdr:1,cd_min:1800,cd_max:1868&lr=lang_en>
35,849,763
Basically I want to do this: ``` Object obj; while (app->running) obj = update(obj) ``` Where update is a function that under some circumstances returns a new Object, and in others returns the same object, unchanged: ``` Object update(const Object& obj) { if (something) return Object{/*params*/}; else return obj; ``` My question is how do I make `Object` do all the copy assignment operations ONLY IF returning the new object, but don't perform any operations when returning the initial `obj`?
2016/03/07
[ "https://Stackoverflow.com/questions/35849763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6016319/" ]
One way would be to enable moves for your `Object` class and move your object in and out of the `update` function.
I would suggest something like `void update(Object& obj)`, as others have mentioned, or preferably a member `update` function that you can call on any object. ``` class Object { public: //other stuff bool update() { if (something) { //update stuff return true; else return false; } } ``` Note that checking for self assignment in `operator=` and returning a reference from `Object& update(const Object& obj)` does not work, due to a dangling reference when returning a new Object.
62,964,709
i am use OAuth 2.0 Flow to get Authorization code. but why after hit API appear docusign login screen. and after login we get Authorization code. we need Authorization code but can't login docusign again. please help me.
2020/07/18
[ "https://Stackoverflow.com/questions/62964709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9672022/" ]
``` for i in li: for j in li: print(f'{i} * {j} = {int(i)*int(j)}') print('') ``` I don't think this is efficient but it gets the result you want. ``` 1 * 1 = 1 1 * 2 = 2 1 * 3 = 3 1 * 4 = 4 1 * 5 = 5 1 * 6 = 6 1 * 7 = 7 1 * 8 = 8 1 * 9 = 9 1 * 10 = 10 2 * 1 = 2 2 * 2 = 4 2 * 3 = 6 2 * 4 = 8 2 * 5 = 10 2 * 6 = 12 2 * 7 = 14 2 * 8 = 16 2 * 9 = 18 2 * 10 = 20 .... ```
This worked for me: ``` my_list = list(map(int, ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"])) new_list = [number_n * number_m for number_n in my_list for number_m in my_list] print(new_list) ``` Output: ``` [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 7, 14, 21, 28, 35, 42, 49, 56, 63, 70, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 9, 18, 27, 36, 45, 54, 63, 72, 81, 90, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100] ```
50,239,502
I have an array serialNumbers. It can look like this. ``` lot: 1 Serial: 2 lot: 1 Serial: 3 lot: 1 Serial: 4 ``` ... and so on. or it may look like ``` lot: 1 Serial: 5 lot: 1 Serial: 9 lot: 8 Serial: 2 lot: 8 Serial: 4 ``` ``` var dictSerials = [] if (serialNumbers.length > 0) for (var i of serialNumbers) { dictSerials.push({ key: i.value.lot, value: i.value.serial }) } ``` This is what I was trying to use to get things working but this creates a key and value for each one listed. I want my outcome to be an object like: ``` Key: 1 Value: 2, 3, 4, 5, 9 Key: 8 Value: 2, 4 ``` Can anyone help me figure this out? Thank you!
2018/05/08
[ "https://Stackoverflow.com/questions/50239502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9760229/" ]
An alternative to accomplish your requirement, is using the function `reduce` to group the keys and values. ```js let array = [{lot: 1, Serial: 2},{lot: 1, Serial: 3},{lot: 1, Serial: 4},{lot: 1, Serial: 5},{lot: 1,Serial: 9},{lot: 8,Serial: 2},{lot: 8,Serial: 4}], result = Object.values(array.reduce((a, c) => { (a[c.lot] || (a[c.lot] = {Key: c.lot, Value: []})).Value.push(c.Serial); return a; }, {})); console.log(result); ``` ```css .as-console-wrapper { max-height: 100% !important; top: 0; } ```
``` function getDictSerials(serialNumbers) { var dictSerials = {}; if (serialNumbers.length > 0) { for (let i of serialNumbers) { let lot = i.lot; let serial = i.serial; if (!dictSerials[lot]) { // If the key isn't found - intiate an array dictSerials[lot] = []; } dictSerials[lot].push(serial) // push the serial to the corresponding lot } } return dictSerials; } let serialNumbers = [ {lot : 1, serial : 2}, {lot : 1, serial : 3}, {lot : 1, serial : 4}, {lot : 1, serial : 5}, {lot : 1, serial : 9}, {lot : 8, serial : 2}, {lot : 8, serial : 4} ]; let desiredObj = { dictSerials: getDictSerials(serialNumbers) } JSON.stringify(desiredObj); // {"dictSerials":{"1":[2,3,4,5,9],"8":[2,4]}} ```
37,910,766
I'm building my first iOS application, and I am using Firebase to handle authentication, database, etc. I added a sign up screen and used the following code to create a new user: ``` FIRAuth.auth()?.createUserWithEmail(emailAddress.text!, password: password.text!, completion: { (user, error) in }) ``` When the user taps on the sign up button, there is a segue that should take them back to the original login view controller. However, when I got to run the app, it hangs on the launch screen. Here is the debugger output: ``` 2016-06-19 14:35:05.402 unitaskr[4386:82981] Configuring the default app. 2016-06-19 14:35:05.413 unitaskr[4386:] <FIRAnalytics/INFO> Firebase Analytics v.3200000 started 2016-06-19 14:35:05.414 unitaskr[4386:] <FIRAnalytics/INFO> To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled (see ...) 2016-06-19 14:35:05.419: <FIRInstanceID/WARNING> FIRInstanceID AppDelegate proxy enabled, will swizzle app delegate remote notification handlers. To disable add "FirebaseAppDelegateProxyEnabled" to your Info.plist and set it to NO 2016-06-19 14:35:05.418 unitaskr[4386:] <FIRAnalytics/INFO> Successfully created Firebase Analytics App Delegate Proxy automatically. To disable the proxy, set the flag FirebaseAppDelegateProxyEnabled to NO in the Info.plist 2016-06-19 14:35:05.430 unitaskr[4386:82981] *** Terminating app due to uncaught exception 'com.firebase.core', reason: 'Default app has already been configured.' *** First throw call stack: ( 0 CoreFoundation 0x00000001100a8d85 __exceptionPreprocess + 165 1 libobjc.A.dylib 0x00000001108e7deb objc_exception_throw + 48 2 CoreFoundation 0x00000001100a8cbd +[NSException raise:format:] + 205 3 unitaskr 0x000000010b58844d +[FIRApp configureDefaultAppWithOptions:sendingNotifications:] + 102 4 unitaskr 0x000000010b588238 +[FIRApp configure] + 302 5 unitaskr 0x000000010b541f1a _TFC8unitaskr11AppDelegate11applicationfTCSo13UIApplication29didFinishLaunchingWithOptionsGSqGVs10DictionaryCSo8NSObjectPs9AnyObject____Sb + 266 6 unitaskr 0x000000010b542204 _TToFC8unitaskr11AppDelegate11applicationfTCSo13UIApplication29didFinishLaunchingWithOptionsGSqGVs10DictionaryCSo8NSObjectPs9AnyObject____Sb + 180 7 UIKit 0x000000010e5bf9ac -[UIApplication _handleDelegateCallbacksWithOptions:isSuspended:restoreState:] + 272 8 UIKit 0x000000010e5c0c0d -[UIApplication _callInitializationDelegatesForMainScene:transitionContext:] + 3415 9 UIKit 0x000000010e5c7568 -[UIApplication _runWithMainScene:transitionContext:completion:] + 1769 10 UIKit 0x000000010e5c4714 -[UIApplication workspaceDidEndTransaction:] + 188 11 FrontBoardServices 0x00000001127b78c8 __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 24 12 FrontBoardServices 0x00000001127b7741 -[FBSSerialQueue _performNext] + 178 13 FrontBoardServices 0x00000001127b7aca -[FBSSerialQueue _performNextFromRunLoopSource] + 45 14 CoreFoundation 0x000000010ffce301 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17 15 CoreFoundation 0x000000010ffc422c __CFRunLoopDoSources0 + 556 16 CoreFoundation 0x000000010ffc36e3 __CFRunLoopRun + 867 17 CoreFoundation 0x000000010ffc30f8 CFRunLoopRunSpecific + 488 18 UIKit 0x000000010e5c3f21 -[UIApplication _run] + 402 19 UIKit 0x000000010e5c8f09 UIApplicationMain + 171 20 unitaskr 0x000000010b542a42 main + 114 21 libdyld.dylib 0x00000001113b692d start + 1 ) libc++abi.dylib: terminating with uncaught exception of type NSException (lldb) ``` I can provide additional information as needed, any help/advice would be greatly appreciated as I am just starting out and looking to learn as much as possible. Have a great day!
2016/06/19
[ "https://Stackoverflow.com/questions/37910766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6486383/" ]
If you're using Scene delegate from and you have **different iOS versions like 9, 10 up to 13**, you must call in **AppDelegate.swift** in this way: ``` if #available(iOS 13.0, *) { } else { FirebaseApp.configure() } ``` And in **SceneDelegate.swift** this way: ``` if #available(iOS 13.0, *) { FirebaseApp.configure() } ``` These settings will exclude error like: \* > > \*\*\* Terminating app due to uncaught exception 'com.firebase.core', reason: 'Default app has already been configured.' > > >
Here is my code for `AppDelegate.swift` ``` import UIKit import Flutter import Firebase @UIApplicationMain @objc class AppDelegate: FlutterAppDelegate { override func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { GeneratedPluginRegistrant.register(with: self) FirebaseApp.configure() return super.application(application, didFinishLaunchingWithOptions: launchOptions) } } ``` You can remove this this `FirebaseApp.configure()` or add ``` if #available(iOS 13.0, *) { } else { FirebaseApp.configure() } ``` both are working for me
31,939,030
**Restated my Question, old Text Below** As I am still hoping for an answer I would like to restate my question. Image I have a GUI with two lists, one that shows a List of all entries to a database `tblOrders` and another one that shows the items in each order. I can use Linq2sql or EF to get all orders from the database, like so: ``` using (DataClasses1DataContext DataContext = new DataClasses1DataContext()) ListOfOrders = DataContext.tblOrder.ToList(); ``` I can display these order in a list or `datagridview`. Then on a selection of one of the jobs I want to access the collection of entities from the table `tblItems`. I can do this like so: ``` ListOfOrders.First().tblItems.toList(); ``` Except I can not, because I need the `DataContext` which has been disposed. This makes sense in a way, since I can not guarantee that there is not a new items that has been added to that order since I retrieved the `ListOfOrders. So ideally I would like to check if there has been an addition to a tblOrder.tblItems` collection and only newly retrieve that collection from the server if required. The background is, that my model is a bit more complex: It consists of Orders, which consist of Parts, which consist of Tasks. So to assess the progress of each order I have to retrieve all parts that belong to an order and for each of them I have to see how many of the tasks have been completed. In a database with 200 job, each with 1 to 10 parts this simply makes my program to slow in terms of responsiveness ... Can anyone help me? **Original Question** I found a lot of questions concerning `DataContext`, but I have not found a solution to my problem yet. If I do the following: ``` using (DataClasses1DataContext DataContext = new DataClasses1DataContext()) ListOfOrders = DataContext.tblOrder.ToList(); ``` This gives me a list of the entities in the `tblOrder` table. But now I want to do this: ``` DataTable Orders = new DataTable(); Orders.Columns.Add("Order-ID", typeof(int)); Orders.Columns.Add("Order-Name", typeof(string)); Orders.Columns.Add("Order-Items", typeof(string)); dataGridView1.DataSource = Orders; foreach (tblOrder Order in ListOfOrders) { var newRow = Orders.NewRow(); newRow["Order-ID"] = Order.orderID; newRow["Order-Name"] = Order.orderName; newRow["Order-Items"] = string.Join(", ", Order.tblItem.Select(item=> item.itemName).ToList()); // System.ObjectDisposedException (dataGridView1.DataSource as DataTable).Rows.Add(newRow); } ``` And I can not because accessing all entities in the `tblItem` table that are related to orders by foreign key don't seem to be stored. What which is working: ``` DataClasses1DataContext DataContext = new DataClasses1DataContext(); ListOfOrders = DataContext.tblOrder.ToList(); DataTable Orders = new DataTable(); Orders.Columns.Add("Order-ID", typeof(int)); Orders.Columns.Add("Order-Name", typeof(string)); Orders.Columns.Add("Order-Items", typeof(string)); dataGridView1.DataSource = Orders; foreach (tblOrder Order in ListOfOrders) { var newRow = Orders.NewRow(); newRow["Order-ID"] = Order.orderID; newRow["Order-Name"] = Order.orderName; newRow["Order-Items"] = string.Join(", ", Order.tblItem.Select(item=> item.itemName).ToList()); (dataGridView1.DataSource as DataTable).Rows.Add(newRow); } DataContext.Dispose(); ``` But as I understand this is not desirable. **EDIT** I extended my example into a Controller-View-Pattern. ``` using System.Collections.Generic; using System.Linq; namespace TestApplication { class Controller { private List<tblOrder> _orders; public IList<tblOrder> Orders { get { return _orders; } } public Controller() { using (var DataContext = new DataClasses1DataContext()) { _orders = DataContext.tblOrder.ToList(); } } } } ``` And the view now retrieves the Orders from the controller: ``` using System.Data; using System.Linq; using System.Windows.Forms; namespace TestApplication { public partial class Form1 : Form { public Form1() { InitializeComponent(); Controller controller = new Controller(); DataTable Orders = new DataTable(); Orders.Columns.Add("Order-ID", typeof(int)); Orders.Columns.Add("Order-Name", typeof(string)); Orders.Columns.Add("Order-Items", typeof(string)); dataGridView1.DataSource = Orders; foreach (tblOrder Order in controller.Orders) { var newRow = Orders.NewRow(); newRow["Order-ID"] = Order.orderID; newRow["Order-Name"] = Order.orderName; newRow["Order-Items"] = string.Join(", ", Order.tblItem.Select(item=> item.itemName).ToList()); (dataGridView1.DataSource as DataTable).Rows.Add(newRow); } } } } ``` Sadly the problem remains the same ...
2015/08/11
[ "https://Stackoverflow.com/questions/31939030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3907299/" ]
Entity Framework lazy-loads object data, meaning it loads the minimum amount of data it has to as late as possible. Take your query: ``` ListOfOrders = context.tblOrder.ToList(); ``` Here you are requesting all of the records in the `tblOrder` table. Entity Framework doesn't read ahead in your program and understand that you will be looking at the `tblItem` table after the context has been disposed, so it assumes it can load the `tblItem` data later. Being lazy, it loads the bare minimum requested: The list of records in `tblOrder`. There ~~are two ways~~ is a way around this: ~~Disable lazy loading~~ ``` using (var context = new DataClasses1DataContext()) { data.Configuration.LazyLoadingEnabled = false; _orders = context.tblOrder.ToList(); } ``` With `LazyLoadingEnabled=false` Entity Framework will select the entire contents of the `tblOrder` table and all tables connected with it via a foreign key. This may take a while and use a lot of memory, depending on the size and number of related tables. (Edit: My mistake, [disabling LazyLoading does not enable eager loading](https://stackoverflow.com/a/18920095/3320402), and [there is no default configuration for eager loading](https://stackoverflow.com/questions/6042023/entity-framework-4-1-default-eager-loading/6042079#6042079). Apologies for the misinformation. The `.Include` command below looks like the only way to go.) **Include additional tables** ``` using (var context = new DataClasses1DataContext()) { data.Configuration.LazyLoadingEnabled = false; _orders = context.tblOrder.Include("tblItems").ToList(); } ``` This tells Entity Framework to load all related data from `tblItems` up front while it's loading the `tblOrders` table data. EF still doesn't load any data from other related tables, so that other data will be unavailable after the context is disposed. However, this does not solve the problem of stale data -- that is, over time the records in `dataGridView1` will no longer be up-to-date. You could have a button or timer that triggers a refresh. The simplest method of refreshing would be to do the entire process over again -- reload `_orders`, then selectively repopulate `dataGridView1`.
Just an answer to the first question. Like EF says, you disposed the context after the [unit of] work (a must in ASP, a good practice in WinForm/WPF). ``` using (DataClasses1DataContext DataContext = new DataClasses1DataContext()) ListOfOrders = DataContext.tblOrder.ToList(); ``` after this, if you try to run this statement ``` ListOfOrders.First().tblItems.toList(); ``` EF works in this way: - get the first element of ListOfOrders that is a proxy to your object. - try to get the tblItems related with LazyLoad. At this point, to retrieve the tblItems needs a database access with a context that is retrieved from the proxy of the ListOfOrder first element BUT the context is disposed. So you can't use this approach. There are 2 solutions and some variations on them: - You can read all the tblItems before disposing the context (you can see it in another answer) but is a not scalable approach. - When you need to access to tblItems you retrieve the Order from a new context and do what you need before disposing it. In your case ``` using (DataClasses1DataContext DataContext = new DataClasses1DataContext()) { int Id = ListOfOrders.First().Id; var myListOftblItems = DataContext.tblOrder.Find(Id).tblItems.ToList(); } ``` A variation on this approach is to read only tblItems. You can do this if tblItems has exposed also the foreign key field and not only the navigation property (usually I don't). ``` using (DataClasses1DataContext DataContext = new DataClasses1DataContext()) { int Id = ListOfOrders.First().Id; var myListOftblItems = DataContext.tblItems.Where(t => t.IdOrder == Id).ToList(); } ```
30,372,586
We wish to avoid an excessive class usage on our code. We have the following html structure: ``` <div id='hello'></div> <div></div> <div></div> <div></div> <div></div> <div id='hello2'></div> <div></div> <div></div> <div></div> <div></div> <div id='hello3'></div> <div></div> <div></div> ``` How can we select, for example, all divs after `#hello`, but just until `#hello2`? Is this possible using a mere css selector? Can we achieve this using a script language (jquery) ? **Update:** Despite needing a selector, that indeed work, I need this to be placed inside a javascript conditional... Sorry for not mention it up front and more clearly.
2015/05/21
[ "https://Stackoverflow.com/questions/30372586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/378170/" ]
You don't need JS (nor jQuery framework), it's CSS task. Use siblings selectors: ``` <style> #hello ~ div {background: red} /* four divs after #hello will be red */ #hello2, #hello2 ~ div {background: white} /* reset red background to default, #hello2 and all next will be white */ </style> ``` <https://jsfiddle.net/sgdedg9z/>
OK, you can use `nextUntil`. But, since you want that for a conditional. You should find a way to get a boolean from this. For **example** adding to it, `.hasClass()`
47,770,186
I’m working on a project in Xcode 9.1 and a very strange problem occurs with my Table View Controller. I need to have a table view with static cells and Xcode tells me that I can achieve this only with a TableViewController (doesn’t work with a TableView in a ViewController. Gives me errors). I’ve embedded my TableViewController inside a Navigation Controller, but when I run the project, the table View scrolls and it’s visible under the status bar (on every iPhone, from X to SE). I wanted to make the status bar opaque but didn’t find a way to do it. Am I doing something wrong? My steps are: 1) Dragged a TableViewController on the storyboard 2) Embed the TableViewController into a Navigation Bar (I’ve tried also to drag the Navigation Bar directly and it comes already connected to a TableViewController). 3) Set the Cells to Static 4) Run on device or simulator. [Screenshot of my problem](https://i.stack.imgur.com/Goilg.jpg)
2017/12/12
[ "https://Stackoverflow.com/questions/47770186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4952674/" ]
Solved it! The problem was the code I wrote to hide the navigation bar hairline (the 1px line under the bar). Commenting the code make everything work fine.
To fix your issue I think your Navigation Bar is set to hidden. 1. In your storyboard click on the navigationBar in the navigation controller. 2. Then look for the attributes section "Drawing" 3. Check to see if hidden is true. 4. If it is uncheck it. My setup has it set to false as default. to hide navigation you need to write below code in viewDidLoad self.navigationController?.isNavigationBarHidden = true
39,170,556
Fetch is the new Promise-based API for making network requests: ``` fetch('https://www.everythingisawesome.com/') .then(response => console.log('status: ', response.status)); ``` This makes sense to me - when we initiate a network call, we return a Promise which lets our thread carry on with other business. When the response is available, the code inside the Promise executes. However, if I'm interested in the payload of the response, I do so via methods of the response, not properties: * arrayBuffer() * blob() * formData() * json() * text() These methods return promises, and I'm unclear as to why. ``` fetch('https://www.everythingisawesome.com/') //IO bound .then(response => response.json()); //We now have the response, so this operation is CPU bound - isn't it? .then(entity => console.log(entity.name)); ``` Why would processing the response's payload return a promise - it's unclear to me why it should be an async operation.
2016/08/26
[ "https://Stackoverflow.com/questions/39170556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/980799/" ]
> > Why are these fetch methods asynchronous? > > > The naïve answer is ["because the specification says so"](https://fetch.spec.whatwg.org/#dom-body-arraybuffer) > > * The `arrayBuffer()` method, when invoked, must return the result of running [consume body](https://fetch.spec.whatwg.org/#concept-body-consume-body) with ArrayBuffer. > * The `blob()` method, when invoked, must return the result of running [consume body](https://fetch.spec.whatwg.org/#concept-body-consume-body) with Blob. > * The `formData()` method, when invoked, must return the result of running [consume body](https://fetch.spec.whatwg.org/#concept-body-consume-body) with FormData. > * The `json()` method, when invoked, must return the result of running [consume body](https://fetch.spec.whatwg.org/#concept-body-consume-body) with JSON. > * The `text()` method, when invoked, must return the result of running [consume body](https://fetch.spec.whatwg.org/#concept-body-consume-body) with text. > > > Of course, that doesn't really answer the question because it leaves open the question of "Why does the spec say so?" And this is where it gets complicated, because I'm certain of the reasoning, *but I have no evidence from an official source to prove it*. I'm going to attempt to explain the rational to the best of my understanding, but be aware that everything after here should be treated largely as outside opinion. --- When you request data from a resource using the fetch API, you have to wait for the resource to finish downloading before you can use it. This should be reasonably obvious. JavaScript uses asynchronous APIs to handle this behavior so that the work involved doesn't block other scripts, and—more importantly—the UI. When the resource has finished downloading, **the data might be enormous**. There's nothing that prevents you from requesting a monolithic JSON object that exceeds 50MB. What do you think would happen if you attempted to parse 50MB of JSON synchronously? It would block other scripts, and—more importantly—the UI. Other programmers have already solved how to handle large amounts of data in a performant manner: *Streams*. In JavaScript, streams are implemented using an asynchronous API so that they don't block, and if you read the [consume body](https://fetch.spec.whatwg.org/#concept-body-consume-body) details, it's clear that streams are being used to parse the data: > > Let stream be body's stream if body is non-null, or an empty ReadableStream object otherwise. > > > Now, it's certainly possible that the spec could have defined *two* ways of accessing the data: one synchronous API meant for smaller amounts of data, and one asynchronous API for larger amounts of data, but this would lead to confusion and duplication. Besides [Ya Ain't Gonna Need It](https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it). Everything that can be expressed using synchronous code can be expressed in asynchronous code. The reverse is not true. Because of this, a single *asynchronous* API was created that could handle all use cases.
Looking at the implementation [here](https://github.com/github/fetch/blob/master/fetch.js) the operation of fetching `json` is CPU bound because the creation of the response, along with the body is done once the response promise is done. See the implementation of the [`json` function](https://github.com/github/fetch/blob/master/fetch.js#L245) That being said, I think that is mostly a design concept so you can chain your promise handlers and only use a single error handler that kicks in, no matter in what stage the error happened. Like this: ``` fetch('https://www.everythingisawesome.com/') .then(function(response) { return response.json() }) .then(function(json) { console.log('parsed json', json) }) .catch(function(ex) { console.log('parsing or loading failed', ex) }) ``` The creation of the already resolved promises is implemented with a pretty low overhead. In the end it is not required to use a promise here, but it makes for better looking code that can be written. At least in my opinion.
59,691,851
my HTML is ``` <form method="POST" action="{% url 'lawyerdash' %}"> {% csrf_token %} username<input type="text" name="username"><br> password<input type="password" name="password" ><br> <input type="button" value="sign in" > ``` my view is ``` def lawyerdash(request): if request.method == 'POST': if Lawyer.objects.filter(username=request.POST['username'], password=request.POST['password']).exists(): lawyer = Lawyer.objects.get(username=request.POST['username'], password=request.POST['password']) return render(request, 'lawyerpage.html', {'lawyer': lawyer}) else: return HttpResponse("<h1>Not found.........</h2>") ``` my URL is ``` url(r'^lawyerdash/$',views.lawyerdash,name="lawyerdash"), ``` after clicking sign in it should go to the following page(lawyerpage.html) ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>welcome {{lawyer.name}}</h1> </body> </html> ```
2020/01/11
[ "https://Stackoverflow.com/questions/59691851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11345613/" ]
You need to set `c = 1` to begin with, so that `++c` will work: (some programmers like to toggle between `0` and `1`, while your original code toggled between `1` and `2`. Both work and it is up to you.) Toggling between `0` and `1`: (I also might have used `prop()` instead of `attr()`, but to keep it close to your original version:) ```js let c = 0; setInterval(function() { if (c === 0) { imgExt = 'https://i.imgur.com/GCPeHoX.png'; ++c; } else { imgExt = 'https://i.imgur.com/J2wgZZb.png'; --c; } // document.querySelector('#floorImgId').src = imgExt; $('#floorImgId').attr('src', imgExt); }, 1000); ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <img id="floorImgId"> ``` If it is just toggle, I tend to just use: ```js let toggle = true; setInterval(function() { if (toggle) { imgExt = 'https://i.imgur.com/GCPeHoX.png'; } else { imgExt = 'https://i.imgur.com/J2wgZZb.png'; } toggle = !toggle; // document.querySelector('#floorImgId').src = imgExt; $('#floorImgId').attr('src', imgExt); }, 1000); ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <img id="floorImgId"> ``` To hide the `toggle` so that it won't contaminate the outer scope, simply wrap the whole thing in an IIFE, or you can also use: ```js setInterval((function() { let toggle = true; return function() { if (toggle) { imgExt = 'https://i.imgur.com/GCPeHoX.png'; } else { imgExt = 'https://i.imgur.com/J2wgZZb.png'; } toggle = !toggle; // document.querySelector('#floorImgId').src = imgExt; $('#floorImgId').attr('src', imgExt); }; }()), 1000); ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <img id="floorImgId"> ```
```html <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> </head> <body> <img id="floorImgId" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/60/Hamiltonian_path.svg/440px-Hamiltonian_path.svg.png" /> <script> var c = 1,imgExt = ""; setInterval(function(){ if(c == 1){ imgExt = 'https://upload.wikimedia.org/wikipedia/commons/thumb/6/60/Hamiltonian_path.svg/440px-Hamiltonian_path.svg.png' ++c; } else{ imgExt = 'https://buffer.com/library/wp-content/uploads/2016/06/giphy.gif'; --c; } $('#floorImgId').attr('src', imgExt); }, 3000); </script> </body> </html> ```
21,205,963
How can I use select if I have 3 tables? **Tables:** ``` school_subject(ID_of_subject, workplace, name) student(ID_of_student, firstName, surname, adress) writing(ID_of_action, ID_of_sbuject, ID_of_student) ``` I want to write the student's name and surname (alphabetically) who have `workplace=home`. Is this possible? And how to alphabetize? ``` SELECT s.firstName, s.surname FROM student S, school_subject P, writing Z WHERE P.workplace = 'home' AND P.ID_of_subject = Z.ID_of_subject AND Z.ID_of_student = s.ID_of_student; ```
2014/01/18
[ "https://Stackoverflow.com/questions/21205963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2881818/" ]
``` SELECT s.firstName, s.surname FROM student S INNER JOIN writing Z ON Z.ID_of_student = s.ID_of_student INNER JOIN school_subject P ON P.ID_of_subject = Z.ID_of_subject WHERE P.workplace = 'home' ORDER BY S.firstName, S.surname // Sort the list ```
To order alphabetically the result it is possible to use **ORDER BY** keyword. So your query becomes: ``` SELECT DISTINCT S.firstName, S.surname FROM student S, school_subject P, writing Z WHERE P.workplace = 'home' AND P.ID_of_subject = Z.ID_of_subject AND Z.ID_of_student = S.ID_of_student ORDER BY S.surname, S.firstName ``` The **DISTINCT** keyword is necessary, because in writing table there are eventually more tuples given keys ID\_of\_subject and ID\_of\_student. So this is necessary to avoid repeating firstName and surname many times.
4,495,864
I use `genstrings` to generate `.strings` files from source code files in my project. Though the project is technically a [Cappuccino](http://cappuccino.org/) app, this question should apply equally to any project that uses `.strings` files. I have a format string that I'd like to be localized: `@"%d:%02d %@"`. It is for displaying time values. If this were a OSX/iOS app, I'd use the built-in datetime formatting, but since it's Cappuccino I have to roll my own. When I run `genstrings` it produces this value for that key: `"%1$d:%2$d %3$@"`. This is as it appears in the `Localizable.strings` file: ``` /* ShortLocalTimeFormat */ "%d:%02d %@" = "%1$d:%2$d %3$@"; ``` by running this command: `genstrings -o Resources/en.lproj -s CPLocalizedString *.j */*.j` Again, ignore that I'm using `CPLocalizedString` instead of `NSLocalizedStrings` and `*.j` instead of `*.m`, as these values are appropriate for Cappuccino. Notice that the `02` in `%02d` is discarded in the resulting format string. If I run it again with the `-noPositionalParameters` option, it just leaves the string as is: `genstrings -o Resources/en.lproj -noPositionalParameters -s CPLocalizedString *.j */*.j`. ``` /* ShortLocalTimeFormat */ "%d:%02d %@" = "%d:%02d %@"; ``` Is this a bug in `genstrings`, or is it not possible to use flags/width in format strings while keeping positional parameters?
2010/12/21
[ "https://Stackoverflow.com/questions/4495864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/549363/" ]
``` $('acronym').each(function() { var $this = $(this); $this.before('<abbr>' + $this.html() + '</abbr>'); $this.remove(); }); ```
``` $('acronym').each(function() { $(this).replaceWith('<abbr>' + $(this).html() + '</abbr>'); }); ```
10,032,361
I have an App which stores images to Custom Library in Photo Album in iphone. I called the following Function of ALAssetLibrary ``` -(void)saveImage:(UIImage*)image toAlbum:(NSString*)albumName withCompletionBlock:(SaveImageCompletion)completionBlock { //write the image data to the assets library (camera roll) [self writeImageToSavedPhotosAlbum:image.CGImage orientation:(ALAssetOrientation)image.imageOrientation completionBlock:^(NSURL* assetURL, NSError* error) { //error handling if (error!=nil) { completionBlock(error); return; } //add the asset to the custom photo album [self addAssetURL: assetURL toAlbum:albumName withCompletionBlock:completionBlock]; }]; } ``` in my SaveImage IBAction ``` -(IBAction)saveToLib:(id)sender { UIImage *savedImage = imgPicture.image; NSLog(@"Saved Image%@",savedImage); [self.library saveImage:savedImage toAlbum:@"Touch Code" withCompletionBlock:^(NSError *error) { if (error!=nil) { NSLog(@"Big error: %@", [error description]); } }]; } ``` but my application keep getting Crashed Help me out Thanks in Advance
2012/04/05
[ "https://Stackoverflow.com/questions/10032361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1503985/" ]
First of all, there is an open ticket on the [PrimeFaces Issue Tracker](http://code.google.com/p/primefaces/issues/detail?id=3887), which targets this question but was recently labeled as "won't fix". Nevertheless, I found a nice workaround. The sorting of PrimeFaces tables can be triggered by calling an undocumented JavaScript method on the datatable's widget. The following might not work for future releases of PrimeFaces, but it does for 3.4.2: Just add the following to your component, which triggers the update: ``` oncomplete="myTableWidget.sort($(PrimeFaces.escapeClientId('#{p:component('sortColumnId')}')), 'ASCENDING')" ``` The table might look like this: ``` <p:dataTable id="myTable" widgetVar="myTableWidget" value="#{myArticles}" var="article" sortBy="#{article.price}" sortOrder="ASCENDING"> ... <p:column id="price" sortBy="#{article.price}"> <f:facet name="header"> <h:outputText value="Price" /> </f:facet> <h:outputText value="#{article.price}" /> </p:column> </p:dataTable> ``` So updating the table could work like this. ``` <p:commandButton value="refresh" action="#{tableController.refreshPrices}" update="myTable" oncomplete="myTableWidget.sort($(PrimeFaces.escapeClientId('#{p:component('price')}')), 'ASCENDING')" /> ```
**EDIT:** Solution posted below (LazyTable) works for the p:dataTable backed with LazyDataModel. Overriden **load** method is called after every update/refresh on the desired table and it handles sort properly. The problem with simple p:dataTable is that it performs predefined sort only on the first load, or after the click on sort column. This is a normal behaviour of a simple table. So what are your possibilities for simple table : * Don't sort the table after update, but remove the sort column so end user is not missinformed. Add this to your action listener or action method for your update button : ``` UIComponent table = FacesContext.getCurrentInstance().getViewRoot().findComponent(":dataTablesForm:dataTableId"); table.setValueExpression("sortBy", null); ``` * Update the sort of the table manually by script. This is not the best solution, but primefaces doesn't provide any client side function for "resorting" the table. Basically you know that only one column at a time can be sorted and this column has a .ui-state-active. You can use it in a script and trigger 2 clicks on that column (1. click - other sort order, 2. click - back to current sort order). ``` <h:form id="mainForm"> <div id="tableDiv"> <p:dataTable id="dataTable" var="item" value="#{testBean.dummyItems}"> . . . </p:dataTable> <p:commandButton value="Refresh" oncomplete="refreshSort();" update=":mainForm:dataTable"/> </div> ``` And script function : ``` function refreshSort(){ jQuery('#tableDiv').find('.ui-state-active').trigger('click'); jQuery('#tableDiv').find('.ui-state-active').trigger('click'); } ``` I know this is not the best workaround, but it works. You can use it as an inspiration to make something better. ### LazyTable IMHO the most proper way is to update directly the component you want. So for example : ``` <h:form id="dataTableForm"> <p:dataTable id="dataTableToUpdate"> . . . </p:dataTable> <p:commandButton value="Refresh" update=":dataTableForm:dataTableToUpdate" /> </h:form> ``` It should work fine in this scenario (I suppose it is your purpose) : Open the .xhtml with your p:dataTable, sort some column (keep the facelet opened), update dataTables data from another .xhtml for example, click on refresh button. The dataTable should show your added value in correct (previously chosen) sort order - sorting was performed after update. Hope it helped !
1,485,955
IE doesn't like the å character in an XML file to display. Is that an IE problem or are å and alike chars indeed invalid XML and do i have to create the &#xxx; values for all these letters? Michel by the way: the chars are inside a CDATA tag The declaration is this: hmm, can't seem to get the xml declaration pasted in my post, it gets deleted or hidden in the html of my post i think, tried the backtick, 4 spaces etc to mark it as code. However, it's the same as sais in the answers The declaration is this: ``` <?xml version="1.0" encoding="utf-8"?> ``` The snippet is ``` <resource key="erroraspx-errorDescription" value="cdata"> <![CDATA[Något gick fel. Klicka <a href=".">här</a> för att gå till webbsidan ]]> </resource> ```
2009/09/28
[ "https://Stackoverflow.com/questions/1485955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/103089/" ]
I am pretty sure that this is an encoding problem. You need to check that the encoding of your file is indeed something internationalised, like UTF-8, and that the xml header indicates this. The xml file should start with `<?xml version="1.0" encoding="UTF-8"?>`
Make sure that you actually save the file using the encoding that is specified in the XML. The Notepad for example by default saves files as ANSI rather than UTF-8. Use the "Save As..." option so that you can specify the encoding. I saved your XML as an UTF-8 file, and that shows up just fine in IE.
12,151,366
I'm already using a plugin to handle the CSS3 attribute. It works when clicking it, and rotates 45 deg, but when it is clicked again to hide the content it isn't rotated back. ANy thoughts on how to get this working? ``` $("#faq dt").click(function() { $(this).next('dd').slideToggle('fast'); if ($(this).next('dd').is(':visible')) { $(this).children('span').transition({ rotate: '45deg' }); } else { $(this).children('span').transition({ rotate: '-45deg' }); } }); ``` You can view the live site here: <http://www.revival.tv/lastdays/> WORKING SNIPPET: ``` $("#faq dt").click(function() { $(this).next('dd').slideToggle('fast', function() { if ($(this).is(':visible')) { $(this).prev('dt').children('span').transition({ rotate: '45deg' }); } else { $(this).prev('dt').children('span').transition({ rotate: '0deg' }); } }); }); ```
2012/08/28
[ "https://Stackoverflow.com/questions/12151366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1461204/" ]
Why don't you put the rotation on a class, then use javascript to add and remove the class, so it flicks back and forth?
Here's a [quick fiddle](http://jsfiddle.net/fAXn7/) with the basic rotation functionality. Implementation I leave to you :)
5,868,086
is it possible to repeat only right side of picture. If I have a menu button picture, there are border or stripe on left side and I only want to repeat right side(without border). When I'm just putting `repeat-x scroll right` or just `repeat-x`, the whole picture will repeat, but I only want right side to repeat, not left or whole picture. I hope you understand what I mean. ![button](https://i.stack.imgur.com/Qisqa.jpg) This is button example. When my button title is too long and it will need to repeat button picture. Can I only repeat that yellow part of picture? not together with red. PS! Cant repeat color, because button is made with cradient.
2011/05/03
[ "https://Stackoverflow.com/questions/5868086", "https://Stackoverflow.com", "https://Stackoverflow.com/users/581785/" ]
Not sure why you can't use a solid color, but why not simply use a wider image? ![enter image description here](https://i.stack.imgur.com/CUB7o.png)
just put "no-repeat top right" is that what your meaning
25,482,406
Hi guys this most be duplicate question, but i spent a day to search for the answer, and didn't find what i'm looking for. the question is simple: I have a simple HTML page, i want to set a background for it, to cover the whole screen at any time. and then, i want to put an image on the screen, to always be at center, and resize when i change the window size. like this: ![enter image description here](https://i.stack.imgur.com/KVXhe.jpg) my problem is that i cant fix the images by height, because my background image is wide,and can cover any screen, and "My Image" is tall, and i want it to always be shown in the screen. (note that the gray part is the overflow of the background image, because its wide and covered the whole screen ) tnx for the help.
2014/08/25
[ "https://Stackoverflow.com/questions/25482406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Edit this : ``` ball8 = new ImageView(this); ball8.setImageResource(R.drawable.ic_launcher8); rel.addView(ball9); ``` to ``` ball8 = new ImageView(this); ball8.setImageResource(R.drawable.ic_launcher8); rel.addView(ball8); ```
You can try with basic way ``` _ delete rel=(RelativeLayout) findViewById(R.id.rel2); ( I dont know what it did ? ) _ ball1 = (ImageView) findViewby(R.id.idOfImageview) ``` the same with Imageview remaining.. **Remember create imageview in layout.** , and sort all imageview in layout file.
256,087
I recently added a caption to my image in WordPress and now there is an empty `<p></p>` tag after `<img>` tag. It broke my style. Can anyone tell how to remove it? Thanks for the help. [![demo](https://i.stack.imgur.com/VYPiW.png)](https://i.stack.imgur.com/VYPiW.png)
2017/02/11
[ "https://wordpress.stackexchange.com/questions/256087", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/113088/" ]
It is not a good practice to override the WordPress native functionality. Instead you can hide the empty elements using CSS ``` p:empty { display: none; } ``` This will the empty elements.
You can do this on the `do_shortcode_tag` hook. ``` function remove_empty_wp_caption_text($output, $tag) { if ($tag === 'caption') { $output = str_replace('<p class="wp-caption-text"> </p>', '', $output); } return $output; } add_filter('do_shortcode_tag', 'remove_empty_wp_caption_text', 10, 2); ``` What's nice about this approach is that the function won't be ran unless the `[caption]` shortcode is called.
13,042,281
I have a struts Action Class with method searchUser() now I want to call this method. So i have following configuration in struts.xml ``` <action name="searchUser" method="searchUser" class="test.User"> <interceptor-ref name="validation"> <param name="excludeMethods">searchUser</param> </interceptor-ref> <result name="success">/jsp/userAdded.jsp</result> <result name="input">/jsp/user.jsp</result> <result name="error">/jsp/error.jsp</result> </action> ``` My test.User.java class ``` public class UserAction extends ActionSupport{ String loginId; //getter and setter method for loginId; public String searchUser(){ System.out.println(getLoginId()); return SUCCESS; } ``` } Now when I tried to access this action using URL :/app/searchUser.action?loginId=1 then as per my understanding console should display "1" but it is having null. I want to access action from URL not from struts form. If i remove validation interceptor then I am getting "1". I want to skip validation, so please help me how can I get value "1" with out validation, is there any other way. I want to get request parameters populated with out using validation.
2012/10/24
[ "https://Stackoverflow.com/questions/13042281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/743191/" ]
This is nothing to do with the validation interceptor behaviour per-se. By configuring your action with ``` <action name="searchUser" method="searchUser" class="test.User"> <interceptor-ref name="validation"> <param name="excludeMethods">searchUser</param> </interceptor-ref> <result name="success">/jsp/userAdded.jsp</result> <result name="input">/jsp/user.jsp</result> <result name="error">/jsp/error.jsp</result> </action> ``` you have told struts to use the Validation interceptor and ONLY the validation interceptor for this action. So all the other interceptors are ignored - including the Parameter interceptor which is responsible for passing HttpResponse parameters into your action. When you remove the validation interceptor from your configuration, then Struts uses the default stack - the Parameter interceptor is called again and hey presto your HttpResponses are returned to your action. What are you actually trying to achieve here?
The default intercepters meybe overwrited. Try this: ``` <action name="searchUser" method="searchUser" class="test.User"> <interceptor-ref name="defaultStack"> <param name="validation.excludeMethods">searchUser</param> </interceptor-ref> <result>...</result> </action> ```
21,789,778
Sorry for noob question, but, how i can print a values of cid1 and cid2 from array? Simple code here: ``` // Handle the parsing of the _ga cookie or setting it to a unique identifier function gaParseCookie() { if (isset($_COOKIE['_ga'])) { list($version,$domainDepth, $cid1, $cid2) = split('[\.]', $_COOKIE["_ga"],4); $contents = array('version' => $version, 'domainDepth' => $domainDepth, 'cid' => $cid1.'.'.$cid2); $cid = $contents['cid']; } else $cid = gaGenUUID(); return $cid; } echo "Welcome " . $contents['cid1'] . "!<br>"; ```
2014/02/14
[ "https://Stackoverflow.com/questions/21789778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2652888/" ]
This should do it ``` print_r(gaParseCookie()); ```
If I'm reading your question right, this is really what I think you want. ``` function gaParseCookie() { if (isset($_COOKIE['_ga'])) { list($version,$domainDepth, $cid1, $cid2) = split('[\.]', $_COOKIE["_ga"],4); $contents = array('version' => $version, 'domainDepth' => $domainDepth, 'cid' => $cid1.'.'.$cid2); $cid = $contents['cid']; echo "Welcome " . $cid1 . "!<br>"; } else $cid = gaGenUUID(); return $cid; } ``` $content[] doesn't have a cid1 index in it. If you want the value from the $cid1 variable, you need to call it from within that function.
159,009
So, my boss comes in, railing that "English is a stupid language!" Since this is pretty much a thrice-weekly occurrence 'round these parts, I barely raised an eyebrow, and waited for him to continue. "Mary just wrote to tell us that she's back from maternity leave, and I want to congratulate her and ask whether she had a girl or a boy, but I can't do it without calling the child an 'it'!" I blinked, then confirmed that yes, he believes the **it** in *"Is **it** a boy or a girl"* is the impersonal pronoun, the same word you'd apply to an apple or a house. Is it the 'thing' pronoun, really? Or is it just a placeholder of some sort? I used to believe the latter: I gave the boss a mini-lecture about ["it's raining"](https://english.stackexchange.com/questions/5758/what-does-it-refer-to-in-its-raining) and the [dummy subject pronoun](https://english.stackexchange.com/questions/73815/why-its-turtles-not-they-are-turtles/73821#73821). He wasn't convinced, however, and now he's got me doubting too. (Harumph. I really should know better than to listen to the boss.) I'm not asking about politeness, here; the former title was to be taken somewhat facetiously. I'm wondering about the grammar: **what role is that "it" playing in that sentence**? Is it a personal pronoun (and thus the infant has grounds for feeling offended) or a dummy pronoun (and thus those who perceive a politeness issue are just misunderstanding the grammar)?
2014/03/21
[ "https://english.stackexchange.com/questions/159009", "https://english.stackexchange.com", "https://english.stackexchange.com/users/1547/" ]
> > * "Is **it** a boy or a girl?" > > > I'm wondering about the grammar: what role is that "it" playing in that sentence? Is it a personal pronoun or a dummy pronoun? > > > 1.) The word "it" is the grammatical subject -- we know this because of the subject-auxiliary inversion in the interrogative clause. 2a.) Depending on the context, it could be reasonable for a person to consider that the word "it" is a dummy pronoun in a truncated *it*-cleft construction. (**note:** A dummy pronoun does NOT have an antecedent.) 2b.) Depending on the context, it could be reasonable for a person to consider that the word "it" is being used in an anaphoric relation to its antecedent which is the baby. LONG VERSION: **For #2a:** In some contexts, the word "it" could be considered to be a dummy pronoun in an *it*-cleft construction, one that has been truncated and is in the form of an interrogative clause. A dummy pronoun does not have an antecedent. (Note that a dummy pronoun doesn't have an antecedent because it is not in an anaphoric relation -- that's a reason why it is called a "dummy pronoun".) It is truncated because the *it*-cleft's relative clause has been omitted, and this is acceptable when that relative clause can be recovered from the context. This is what a non-truncated version could be: * "Is **it** a boy or a girl that she has given birth to?" A possible declarative clause version of that *it*-cleft could be: * "It is a boy/girl that she has given birth to." A non-*it-cleft* declarative version could be *"She has given birth to a boy/girl"*. Here's a related excerpt from the 2002 reference grammar by Huddleston and Pullum et al., *The Cambridge Grammar of the English Language*, page 1417: > > Truncated *it*-clefts: omission of relative clause > > > The relative clause of an *it*-cleft construction can be omitted if it is recoverable from the prior discourse: > > > [19] > > > A: *Who finished off the biscuits?* > > > B: *I don't know; [it certainly wasn't me].* > > > The underlined clause [*it is 'bracketed' -- f.e.*] here can be analyzed as a **truncated it-cleft**, equivalent to *It certainly wasn't me who finished off the biscuits*. > > > In the OP's post, there is this: > > *"Mary just wrote to tell us that she's back from maternity leave, and I want to congratulate her and ask whether she had a girl or a boy, but I can't do it without calling the child an 'it'!"* > > > I blinked, then confirmed that yes, he believes the **it** in *"Is* ***it*** *a boy or a girl"* is the impersonal pronoun, the same word you'd apply to an apple or a house. > > > From the above context, a third person (or the OP herself) could have asked the boss a non-trunctated *it*-cleft such as *"Was it a boy or a girl that she had?"*, though that version sounds awkward when compared to the truncated version *"Was it a boy or a girl?"* **For #2b:** In some contexts, the word "it" could be considered to be in an anaphoric relation, where its antecedent is the baby. For instance, if the baby was already the topic of discussion. Grammatically, the 3rd person singular neuter pronoun ("**it**") can sometimes be used to refer to a baby. Here is an excerpt from a 2005 textbook by Huddleston and Pullum, *A Student's Introduction to English Grammar*, page 103: > > The **neuter** pronoun ***it*** is used for inanimates, or for male or female animals (especially lower animals and non-cuddly creatures), and sometimes human infants if the sex is unknown or considered irrelevant: *The baby grunted again, and Alice looked very anxiously into* ***its*** *face to see what was the matter with* ***it***. > > > The acceptability for either #2a or #2b as an explanation will usually depend on the specific context of the surrounding discourse. That's the way it is in today's standard English -- context is king. . MORE INFO: Perhaps some more general info about the 3rd person singular neuter pronoun ("**it**"). There are some special uses for ***it***, where those uses for "it" are not anaphoric (or at least not clearly so). These include: * Extrapositional and impersonal *it* -- e.g. *"It's ridiculous that they've given the job to Pat."; "It seemed as if things would never get any better."* * The *it*-cleft construction -- e.g. *"It was precisely for that reason that the rules were changed."* * Weather, time, place, condition -- e.g. *"It is raining."; "It is five o'clock."; "It is very noisy in this room."; "I don't like it when you behave like this."* * *It* as subject with other predicative NPs -- e.g *"It was a perfect day."* * *It* in idioms -- e.g. *"What's it to you?"; "Beat it, kid"; He made a go of it."* The above info and examples are borrowed from the 2002 *CGEL*, section "Special uses of *it*", pages 1481-3.
I think in this context 'it' is actually referring to the term of 'boy' or 'girl'. Similar to if someone said, "What is your name? Is it Joe?" The 'it' in this sentence is not calling the person an it but referring to their name. It in the context of the initial sentence is a place holder for the sex of the child. I think it is much more awkward when talking about the baby in utero whose sex is not yet known. Do you say 'they' or just pick a place holder sex of 'he' or 'she' until it becomes known?
11,839
I wrote the following question: [Can Ride be used to Push a mount/animal companion?](https://rpg.stackexchange.com/questions/192887/can-ride-be-used-to-push-a-mount-animal-companion) containing multiple questions. I was asked to separate them out, so I did. Once I separated out the question [When pushing an animal, how long will it perform the trick it doesn't know?](https://rpg.stackexchange.com/questions/192910/when-pushing-an-animal-how-long-will-it-perform-the-trick-it-doesnt-know/192912#192912), the separate question was answered. With that answer, I realized I did not need an answer to the original question. Since the original question is unanswered, is it OK for me to delete it? The answered question kind of makes the original question irrelevant for me.
2021/11/11
[ "https://rpg.meta.stackexchange.com/questions/11839", "https://rpg.meta.stackexchange.com", "https://rpg.meta.stackexchange.com/users/59003/" ]
I don’t think anyone’s going to undelete your question if you delete it. Even if they did, it’s not like you’d be “in trouble” for it or anything. You could even, if you wanted nothing more to do with it but folks insisted on keeping it undeleted, ask to have the question dissociated from your account. But I really doubt this is going to come to that. Yes, it is “OK” for you to delete it. On the other hand, it’s also a perfectly reasonable question. Maybe you no longer feel like you need the answer, but it could still be useful to someone. And even if the demands on your Handle Animal checks are less than you thought, if there’s an answer that’s cheap enough you still might end up using it. So at least if it were me, I wouldn’t choose to delete it. But if you do, I don’t think anyone’s going to cry foul.
Don't delete it - answer it --------------------------- You asked a question. That's good. You now know the answer. That's better. Armed with this knowledge, you now answer your original question so it is an ongoing benefit to others. That's best.
1,012,845
We're looking for a way to run a Docker container that needs a connection to an On-Premise database. This was previously done using a Hybrid Connection with a Web App. Does Azure Container Instances (suppose running on Windows) support Hybrid Connections similar to Web Apps?
2020/04/17
[ "https://serverfault.com/questions/1012845", "https://serverfault.com", "https://serverfault.com/users/570374/" ]
Yes you can, you need to deploy your container group into a VNet that has access to a VPN or ExpressRoute connection to your on premises systems. More details can be found here: <https://docs.microsoft.com/en-us/azure/container-instances/container-instances-vnet> At the time of writing, keep note this is only generally available in a small set of regions and in preview in others. Also take note of some of the other configuration limitations. Though I expect these will change over time.
Windows containers in web apps do not support hybrid connection. As Alex stated the only way to achieve this will be with ACI on a vNet and connecting to on prem through Express Route or VPN. This will only be possible with Linux containers, Windows ACI does not support vNet join.
21,639,128
I'm trying to make a tweak for iOS 7 so that when a device is ARM64 it runs one version and when it is not it runs another (since float is for 32 bit and double is for 64 (If you have a solution for that let me know.) So it would be like this ``` if ARM64 { \\run double code } else { \\run float code } ```
2014/02/07
[ "https://Stackoverflow.com/questions/21639128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2288341/" ]
You would do the following ``` #if __LP64__ \\You're running on 64 bit #else \\You're running on 32 bit #endif ```
On arm64 environment, the pointer take 8 bytes. ``` - (BOOL)isArm64 { static BOOL arm64 = NO ; static dispatch_once_t once ; dispatch_once(&once, ^{ arm64 = sizeof(int *) == 8 ; }); return arm64 ; } ```
41,057
Recently, I was reminded in Melvyn Nathason's first year graduate algebra course of a debate I've been having both within myself and externally for some time. For better or worse, the course most students first use and learn extensive category theory and arrow chasing is in an advanced algebra course, either an honors undergraduate abstract algebra course or a first-year graduate algebra course. (Ok, that's not entirely true, you **can** first learn about it also in topology. But it's really in algebra where it has the biggest impact. Topology can be done entirely without it wherareas algebra without it beyond the basics becomes rather cumbersome. Also, homological methods become pretty much impossible.) I've never really been comfortable with category theory. It's always seemed to me that giving up elements and dealing with objects that are knowable only up to isomorphism was a huge leap of faith that modern mathematics should be beyond. But I've tried to be a good mathematican and learn it for my own good. The fact I'm deeply interested in algebra makes this more of a priority. My question is whether or not category theory really should be introduced from jump in a serious algebra course. Professor Nathanson remarked in lecture that he recently saw his old friend Hyman Bass, and they discussed the teaching of algebra with and without category theory. Both had learned algebra in thier student days from van der Waerden (which incidently, is the main reference for the course and still his favorite algebra book despite being hopelessly outdated). Melvyn gave a categorical construction of the Fundamental Isomorphism Theorum of Abelian Groups after Bass gave a classical statement of the result. Bass said, "It's the same result expressed in 2 different languages. It really doesn't matter if we use the high-tech approach or not." Would algebracists of later generations agree with Professor Bass? A number of my fellow graduate students think set theory should be abandoned altogether and thrown in the same bin with Newtonian infinitesimals (nonstandard constructions not withstanding) and think all students should learn category theory before learning anything else. Personally, I think category theory would be utterly mysterious to students without a considerable stock of examples to draw from. Categories and universal properties are vast generalizations of huge numbers of not only concrete examples,but certain theorums as well. As such, I believe it's much better learned after gaining a considerable fascility with mathematics-after at the very least, undergraduate courses in topology and algebra. Paolo Aluffi's wonderful book *Algebra:Chapter 0*, is usually used by the opposition as a counterexample, as it uses category theory heavily from the beginning. However, I point out that Aluffi himself clearly states this is intended as a course for advanced students and he strongly advises some background in algebra first. I like the book immensely, but I agree. What does the board think of this question? Categories early or categories late in student training?
2010/10/04
[ "https://mathoverflow.net/questions/41057", "https://mathoverflow.net", "https://mathoverflow.net/users/3546/" ]
Categorical ideas should be certainly introduced early, as they are quite useful. On the other hand, as Andreas and Terry say, studying category theory at the beginning of your mathematical education is a waste of time, and could be a turnoff, like all unmotivated formalism. On the other hand, the formal language of category theory should be learned, and used, at *some* point. I have seen several interesting papers written by very good mathematicians, containing theorems with statements like "It is the same to give a regular thingamabob over $X$, and a von Neuman whatchamacallit with a seminormal connection over $X'$". What these statements usually mean, is that there is an equivalence of the category of regular thingamabobs over $X$ and that of von Neuman whatchamacallits with a seminormal connection over $X'$; but they could also simply mean that there is a bijection of isomorphism classes, and to know which is true you have to study the proof. This means, I suppose, that the authors, who must have seen the language of category theory at a certain point, have not interiorized it, and don't have a feeling for when its use is appropriate. In my opinion, the concept of equivalence of categories is a real turning point. Up to that point, one can probably get away without it (for example, universal properties, like that for the tensor product, are easily explained without the formal language); this is harder to do with equivalences. On the other hand, you don't see many examples of equivalences in the beginning of your mathematical studies. Maybe the first one is that between coverings of a space, with appropriate hypothesis, and sets on which its fundamental group acts. Stating the connection between these two classes of objects as an equivalence of categories clarifies things enormously; I wish someone had explained it to me when I was a student, instead of just telling me that there is a bijection between isomorphism classes of connected covers and conjugacy classes of subgroups, and other statements in this spirit, all descending very immediately from the "real" theorem, which is the existence of the equivalence.
I think that there are certain notions that are needed to "set the stage" for category theory. I don't think students are going to understand category theory unless they've already seen some of the following examples: * Galois Theory * Covering spaces and pi\_1 * The universal property of tensor product * The difference between direct sum and direct product If people have a very strong undergraduate background, then it seems to me that in graduate algebra they're ready to start seeing some category theory. On the other hand, I feel like (contrary to what AndrewL said) that category theory really finds its home in topology more than algebra, so I think an algebra course should introduce category theoretic language but that it should not be the main emphasis of the course (since people who haven't taken algebraic topology probably won't really grok the category theory anyway).
12,824,751
I have `MyContentProvider` in my app which works fine when I develop and run in debug mode. ``` <provider android:name=".MyContentProvider" android:authorities="com.contactcities" android:exported="false"> </provider> ``` But when I export the app, download it and run it, it crashes instantly : ``` 10-10 18:24:37.682 E/AndroidRuntime(10428): FATAL EXCEPTION: main 10-10 18:24:37.682 E/AndroidRuntime(10428): java.lang.RuntimeException: Unable to get provider com.contactcities.MyContentProvider: java.lang.ClassNotFoundException: com.contactcities.MyContentProvider in loader dalvik.system.PathClassLoader[/system/framework/com.google.android.maps.jar:/data/app/com.contactcities-1.apk] 10-10 18:24:37.682 E/AndroidRuntime(10428): at android.app.ActivityThread.installProvider(ActivityThread.java:4509) 10-10 18:24:37.682 E/AndroidRuntime(10428): at android.app.ActivityThread.installContentProviders(ActivityThread.java:4281) 10-10 18:24:37.682 E/AndroidRuntime(10428): at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4237) 10-10 18:24:37.682 E/AndroidRuntime(10428): at android.app.ActivityThread.access$3000(ActivityThread.java:125) 10-10 18:24:37.682 E/AndroidRuntime(10428): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2071) 10-10 18:24:37.682 E/AndroidRuntime(10428): at android.os.Handler.dispatchMessage(Handler.java:99) 10-10 18:24:37.682 E/AndroidRuntime(10428): at android.os.Looper.loop(Looper.java:123) ``` I can reproduce it on all my devices, 2.2, 4.0, 4.1 I have read through numerous threads today. Some of them blaming ProGuard for this. I have tried adding ``` -keep public class com.contactcities.MyContentProvider ``` but with no luck. When I disable proguard, by not putting `proguard.config=proguard.cfg` in my `project.properties`. It still gives the same error in release version. Debug is again fine. Maybe its not enough to disable proguard like that? Maybe the hint is that it refers to maps.jar in this crash. Im not sure why it does that ``` in loader dalvik.system.PathClassLoader[/system/framework/com.google.android.maps.jar ``` Any clues will be much appreciated
2012/10/10
[ "https://Stackoverflow.com/questions/12824751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/796414/" ]
I was getting the same error, turns out I had the wrong `android:name` attribute value for my provider tag in *AndroidManifest.xml*: ``` <provider android:authorities="com.example.ProviderClass" android:name=".ProviderClass" android:exported="false" > </provider> ``` So double check this value is as above `.ProviderClass` or whatever your class name is (prefixed with a dot). Then do Project > Clean and it will work.
You might have passed your class limit on older OS versions—before Android 5.0 (API level 21) replaced the DEX runtime with ART. If you're right on the edge of the limit, you can pass compilation but get this error during startup. Try enabling multi-dex as described in the Android [Enable Multidex for Apps with Over 64K Methods](https://developer.android.com/studio/build/multidex) documentation.
57,826,909
Help with R: I need to group by a column and count occurrences of values in a set of columns. Here is my data frame ``` ID Ob1 Ob2 Ob3 Ob4 3792 0 0 0 1 3792 0 0 -1 0 3792 1 -2 -1 0 3792 2 -2 -1 0 8060 -1 0 -2 2 8060 -1 0 -3 0 8060 0 0 0 0 13098 0 0 0 0 13098 -1 0 -1 0 13098 0 0 0 0 ``` I want to groupby ID and count the values of numbers in Ob1, Ob2, Ob3, Ob4. so my result should look like below; ``` Group -3 -2 -1 0 1 2 3792 2 3 8 2 1 8060 1 1 2 7 1 13098 2 10 ``` I tried ``` table(unlist(df)) ``` but I loose the groupby info. I get below ``` -3 -2 -1 0 1 2 46 3792 8060 13098 1 3 7 25 2 2 10 4 3 3 ```
2019/09/06
[ "https://Stackoverflow.com/questions/57826909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10709394/" ]
``` with(reshape2::melt(df1, id.vars = "ID"), table(ID, value)) # value #ID -3 -2 -1 0 1 2 # 3792 0 2 3 8 2 1 # 8060 1 1 2 7 0 1 # 13098 0 0 2 10 0 0 ```
Try using `dplyr`. Assume the datafame is called `df` ```r library(dplyr) df %>% group_by(ID) %>% summarise(Obs1 = sum(Obs1), Obs2 = sum(Obs2), Obs3 = sum(Obs3), Obs4 = sum(Obs4)) ```
7,016,288
thanks to help from stackoverflow posters I have set up some oop javascript. However, I have hit another snag. I have two different classes with the same inheritance. They then both have a function named the same, but doing different things. The trouble is, if ClassB is defined last, then even when I have a ClassA object, and write classAInstance.MyFunction(); it returns 2, ie ClassB's function of the same name. ``` BaseClass = function(){ ...init some stuff... }; ClassA = function(){ BaseClass.call(this); ...init some stuff... }; ClassA.prototype = BaseClass.prototype; // innherit ClassA.prototype.MyFunction(){ return 1; }; ClassB = function(){ BaseClass.call(this); ...init some stuff... }; ClassB.prototype = BaseClass.prototype; // innherit ClassB.prototype.MyFunction(){ return 2; } ```
2011/08/10
[ "https://Stackoverflow.com/questions/7016288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/886773/" ]
You are setting up the prototype of the new classes incorrectly ``` BaseClass = function(){ ...init some stuff... }; ClassA = function(){ BaseClass.call(this); ...init some stuff... }; ClassA.prototype = new BaseClass(); // innherit ClassA.prototype.MyFunction(){ return 1; }; ClassB = function(){ BaseClass.call(this); ...init some stuff... }; ClassB.prototype = new BaseClass(); // innherit ClassB.prototype.MyFunction(){ return 2; }; ```
Normally you wouldn't want to have two functions with the same name in any network of objects which nest into or inherit from eachother. Why not rename the second `MyFunction(){` to something else?
10,886,727
I need to remove the last part of the url from a span.. I have ``` <span st_url="http://localhost:8888/careers/php-web-developer-2" st_title="PHP Web Developer 2" class="st_facebook_large" displaytext="facebook" st_processed="yes"></span></span> ``` And I need to take the `st_url` and remove the `php-web-developer-2` from it so it is just `http://localhost:8888/careers/`. But I am not sure how to do that. `php-web-developer-2` will not always be that but it won't have any `/` in it. It will always be a `-` separated string. Any Help!!??
2012/06/04
[ "https://Stackoverflow.com/questions/10886727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/150062/" ]
``` $('span').attr('st_url', function(i, url) { var str = url.substr(url.lastIndexOf('/') + 1) + '$'; return url.replace( new RegExp(str), '' ); }); ``` **[DEMO](http://jsfiddle.net/LNW4V/229/)**
First you need to parse the tag. Next try to extract st\_url value which is your url. Then use a loop from the last character of the extracted url and omit them until you see a '/'. This is how you should extract what you want. Keep this in mind and try to write the code .
37,065,191
I'm brand new to C# and I couldn't figure out what to search for. I'm trying to print a list of strings in a "column" to the right of another list of strings. Two of the strings in the right "column" have multiple values that each need their own line. But when I try to do this, the values that need their own lines just end up all the way over on the left, instead of staying within their "column". Here's what I want to see: ![](https://i.stack.imgur.com/WwMB2.png) And here's what I get: ![](https://i.stack.imgur.com/aPw3e.png) And here's my code: ``` static void Main(string[] args) { string ut = "1Y, 4D, 01:23:45"; string met = "T+4D, 01:11:32"; string vesselName = "Saturn K"; string vesselModules = "Command/Service Module \nMunar Excursion Module"; string kerbals = "Valentina Kerman, Pilot; \nJebediah Kerman, Pilot; \nBill Kerman, Engineer; \nBob Kerman, Scientist"; string[] headerNames = { "UT:", "MET:", "Vessel:", "Modules:", "Crew:" }; string[] headerData = new string[5] { ut, met, vesselName, vesselModules, kerbals }; for (int index = 0; index < headerNames.Length; index++) Console.WriteLine("{0,-12} {1,-46}", headerNames[index], headerData[index]); } ```
2016/05/06
[ "https://Stackoverflow.com/questions/37065191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6298712/" ]
You are not set any text to JButton so it's not working, If you set text Text, then it will appear on the image, So you can do one thing 1. Set the `setName` Method and add text to that. 2. in `actionPerformed`, use `getName` rather than `getText`. For Example: ``` ImageIcon normalButtonImage = new ImageIcon("src/Images/normalIcon.png"); normalSetupButton = new JButton(); normalSetupButton.setIcon(normalButtonImage); normalSetupButton.setName("Normal Setup"); normalSetupButton.addActionListener(buttonHandler); normalSetupButton.setToolTipText("Set up simulation for normal execution"); ``` In Action performed : ``` public void actionPerformed(ActionEvent e) { // get the button that was pressed JButton b = (JButton) e.getSource(); // fire appropriate event if (b.getName().equals("Normal Setup")) { // set up for normal simulation fireSimulationEvent(SimulationEvent.NORMAL_SETUP_EVENT); } ...... ```
I think the best way to rework your code is to use client properties of a button. ``` private static final String EVENT_TYPE = "event_type"; // button creation normalSetupButton = new JButton(); // set appropriate event for this button normalSetupButton.putClientProperty(EVENT_TYPE, SimulationEvent.NORMAL_SETUP_EVENT); // other init button routine //next button queenTestButton = new JButton(); queenTestButton.putClientProperty(EVENT_TYPE, SimulationEvent.QUEEN_TEST_EVENT); // other init button routine // same way for other buttons public void actionPerformed(ActionEvent e) { // get the button that was pressed JButton b = (JButton) e.getSource(); SimulationEvent evt = (SimulationEvent) b.getClientProperty(EVENT_TYPE); fireSimulationEvent(evt); } ``` This looks better than "if-else if" cascade ;)
1,435,312
I wouldn't have asked this question if I hadn't seen this image: [![](https://i.stack.imgur.com/A9GOc.jpg)](https://i.stack.imgur.com/A9GOc.jpg) From this image it seems like there are reals that are neither rational nor irrational (dark blue), but is it so or is that illustration incorrect?
2015/09/14
[ "https://math.stackexchange.com/questions/1435312", "https://math.stackexchange.com", "https://math.stackexchange.com/users/252531/" ]
Irrational means not rational. Can something be not rational, and not not rational? Hint: no.
The set of irrational numbers is the complement of the set of rational numbers, in the set of real numbers. By definition, all real numbers must be either rational or irrational.
56,806,704
A simple problem in R using the For loop to compute partial sums of an infinite sequence is running into an error. ``` t <- 2:20 a <- numeric(20) # first define the vector and its size b <- numeric(20) a[1]=1 b[1]=1 for (t in seq_along(t)){ a[t] = ((-1)^(t-1))/(t) # some formula b[t] = b[t-1]+a[t] } b ``` > > Error in b[t] <- b[t - 1] + a[t] : replacement has length zero > > >
2019/06/28
[ "https://Stackoverflow.com/questions/56806704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11254108/" ]
You can also provide a .runsettings-file to the vstest.console-process, as indicated here. <https://learn.microsoft.com/visualstudio/test/configure-unit-tests-by-using-a-dot-runsettings-file?view=vs-2019>. In order to provide custom parameters modify the `TestRunParameters`-section, e.g: ``` <!-- Parameters used by tests at runtime --> <TestRunParameters> <Parameter name="executeAsserts" value="1,2,3" /> </TestRunParameters> ``` These parameters can now be accessed via this code: ``` TestContext.Properties["executeAsserts"]; ``` so that your final test-code may look like this: ``` [Test] public void MyTest() { var assertsToRun = TestContext.Properties["executeAsserts"].Split(",").Select(x => Convert.ToInt(x)).ToArray(); if(assertsToRun.Contains(1) Assert.That(...); if(assertsToRun.Contains(2) Assert.That(...); if(assertsToRun.Contains(3) Assert.That(...); } ``` You should be able to run the test using the following command: ``` vstest.console.exe MyTestAssembly.dll /Settings:MySettings.runsettings ```
Basically you should favour to have only a single `Assert` within your test, so that every tests checks for **one single thing**. So what you have is similar to this, I suppose: ``` [Test] public void MyTest() { Assert.That(...); Assert.That(...); Assert.That(...); } ``` When you want to exclude e.g. the second `Assert`, you have of course to provide some functionality **in your code** to execute or not to execute those lines, e.g.: ``` public void MyTest() { Assert.That(...); if(executeSecondAssert) Assert.That(...); Assert.That(...); } ``` You can introduce some compile-switch that sets the value for the above bool-flag: ``` #if(EXECUTE_ASSERT) bool executeSecondAssert = true; #else bool executeSecondAssert = false; ``` and now provide that compile-switch via an environment-variable.
112,311
During an internship for a small company, my boss created an account for me, so I generated a password and I used it. The next day, my boss told me to write down the password of my account on a piece of paper, put it in a letter and to sign the envelope. Then he took the letter and told me that if he needs to access my account and I am unreachable, he is authorized to open the envelope and read the password to use it. *He also told me that this is a common practice in all companies*. Now I don't know if every company does this (I don't think so) but, to me, it's not legal. Let's say that my boss is a bad person (**he's not**) and he wants to frame me for something that he did. He only has to open the letter and read my password (let's say that I'm unreachable) and do his nefarious activity with my account. Now **let's say that I can't prove my innocence**. How I can prevent all of this? I thought of writing down a wrong password, but if he really needs my account and I'm unreachable, I'll put him in a bad situation. So, **is there a way to protect myself** (without refusing to write down the password)?
2016/01/31
[ "https://security.stackexchange.com/questions/112311", "https://security.stackexchange.com", "https://security.stackexchange.com/users/42544/" ]
I don't think you are in a particularly worse situation than not disclosing your password. Your boss could: * Get the system administrator to make a copy of your (hashed) current password * Change it to something new * Do something evil in your name * Put the old password back (replace the hash back what it was) What *does* protect you is that there are, presumably, audit trails of things that are done. For example, tracking emails by IP addresses. If anything you are in a better situation than before. Now you can plausibly argue, if something bad is done in your name: "But my boss insisted on having my password, maybe he did it". If the audit trails can be used to prove your boss's innocence in this sort of situation, then it can also be used to prove yours. And if no audit trails exist there will be doubt as to who really did it - whatever "it" is.
Philipp is correct here. Let me restate something he said: > > In order to use your password, one needs to break the seal of the envelope you signed. When you think your password was abused, you can ask to see the envelope with your signature and check if it is still unopened. > > > To add to what he's saying, your company appears to have grossly incorrect IT management practices. What you should do at this point is make sure your password is not the same as the one you use elsewhere. Always assume your employer has access to whatever you're doing online. Even if they don't. Do not log into your social networking accounts at work. Do not log onto your bank accounts. Use your work computer for work-related tasks. If you have a cell phone, it's even easier. Your employer should be able to do whatever they want, within the confines of the law, to your work computer. You should not have any expectation of privacy.
69,190
So I am currently on the fence about my next bike, I have in the last year and a half taken up cycling more seriously. To give some background I mean I am probably doing around 50km (31 miles) a week. Bearing in mind that this is less now because it is winter here. When in summer when races start again I will probably be putting in longer distances when I can. I would say most of my rides I stick to the dirt and I am looking to buy a pass to use the mountain trails around us, I really enjoy it when I can mountain bike. My one gripe is always having to clean my bike thoroughly because of how harsh the conditions are around me. In South Africa we can also cycle all year around so I thought I would add that as it might affect answers given. My current bike is a real beginner bike, a GT Timberline Expert. I was given it as a beginner bike and I actually really enjoy riding it. I’ve gotten used to it’s quirks however after riding my dads mountain bike I know how much nicer a lighter bike can be with better components. I still have fun on mine however, I don’t think I’ve ever thought during a ride that I’m not having fun because it’s a beginner model. I do however notice in road races even with slick tires on that it’s a struggle. Every year I enter the 109km (67mile) race we have in the area and during training and the race I can say it is not fun having to push hard to keep a good pace. That’s where my problem comes in. I’m not sure whether to add a road bike to the mix and use it for interval training on the road and racing and continue to use my current mountain bike. Or do I upgrade my current mountain bike to a nice new one. I am concerned about how quickly a mountain bike gets wear and tear but I’m not really sure if that’s a real consideration even? I’ve done some research and on the road bike side the best deal I’ve found was this: [https://www.trekbikes.com/za/en\_ZA/bikes/road-bikes/performance-road-bikes/émonda/émonda-alr/émonda-alr-5/p/24166/](https://www.trekbikes.com/za/en_ZA/bikes/road-bikes/performance-road-bikes/%C3%A9monda/%C3%A9monda-alr/%C3%A9monda-alr-5/p/24166/) Good parts and not crazy priced. However for the same price I could get a mountain bike like this: <https://www.specialized.com/za/en/mens-chisel-expert/p/154335> which is also a very nice bike. What are your thoughts? I hope I haven’t bored you with too much background info? I know it’s a tricky question to ask too... My current mtb also has not done tons of mileage so it can still go for quite a long time.
2020/06/27
[ "https://bicycles.stackexchange.com/questions/69190", "https://bicycles.stackexchange.com", "https://bicycles.stackexchange.com/users/50349/" ]
Only you can decide if you "need or "want" a road bike. I would not upgrade your mountain bike in an attempt to make it a better road bike. As the saying goes a pig wearing lipstick is still a pig. If you want to road ride for a change of scenery or pace buy a used quality built bike. The used market should have lots of bikes suitable to the local roads. Your times will improve over the MTB on the road just from the gearing alone. If you shopped well, after a year you can decide if you want to upgrade or just sell it. You should be able to get 80% of what you paid for it. If you buy a new bike you might get 60% of the much higher new bike cost a year later. I would ride the mountain bike until the bike becomes the limiting factor in your race times or it breaks. If the races you ride are competitive just upgrading your MTB won't move you from 25th to 1st place conditioning and training has to come in to play.
Every bike is an engineering compromise, so you got to know what you want in order to get it. For example a road bike is optimized for speed, which means good aerodynamics, low rolling resistance and low weight at the expense of everything else, notably comfort, ability to ride on any road that isn't smooth enough, luggage carrying capacity, etc. A mountain bike is optimized for basically the complete opposite factors. MTB has a more upright position so you can shift your weight, look up and see the trail ahead, etc. Handlebars are wide, giving leverage to control the front wheel when it bumps into obstacles. All this means terrible aerodynamics. The race bike is the opposite, you ride in a scrunched position, leaning down with narrow handlebars for best aerodynamics which is the single most important factor for speed. However riding on a race bike is less fun because leaning down means most of the time you're looking at the front tyre or the butt of the guy in front of you. If you want to enjoy the landscape your neck will hurt after a while. Also race bikes are less safe to ride on open roads for several reasons. First, the brake levers are positioned in the most aerodynamic position, which means they're harder and slower to reach in an emergency situation. Second, they're uncomfortable on roads that aren't smooth, so you will tend to pick routes with smooth asphalt, which means roads with lots of automobile traffic. This is okay for riding in a group that can be easily seen by drivers from far away, but when riding alone I prefer small roads with little traffic. Anyway. If you want to race or ride with buddies who have road bikes, then get a road bike. On the road, even a very expensive MTB with slick tyres will be much slower than a cheap road bike because being a good MTB implies bad aerodynamics. It's mutually exclusive. If you want a more enjoyable/relaxed ride, get a touring bike with a rear rack so you don't have to sweat carrying a backpack, and semi-fat tyres to widen your choice of roads to small country roads with some bad asphalt but little traffic. Consider getting a frame with enough clearance to mount fatter tyres if you like a smooth ride over bad country roads. So basically, first decide on what type of cycling you want to do, what types of roads you prefer, and then pick a bike that goes with that. There's no better solution, but you need the bike that works well on the trips that you like.
426,484
The news that DeepMind had helped mathematicians in research (one in representation theory, and one in knot theory) certainly got many thinking, what other projects could AI help us with? See MO question [What are possible applications of deep learning to research mathematics?](https://mathoverflow.net/questions/390174/what-are-possible-applications-of-deep-learning-to-research-mathematics) Geordie Williamson has been giving talks on his experience with the DeepMind team (his lectures in [Machine Learning for the Working Mathematician](https://www.youtube.com/playlist?list=PLtmvIY4GrVv-SJfeyprwh7t3KUvTJHTdB) are also great), and his answer would be whenever we can produce lots of data or examples which we wish to look for patterns. He gave graphs and high-dimensional manifolds as examples. For high-dimensional manifolds, it would be great if AI could provide the kind of geometric intuition that we acquire “easily” for 2 and 3 dimensions (and struggle even for 4). But what would be a good task for AI to learn? Predicting the (co)homology of manifolds or CW-complexes? In fact, in the latest advances in natural language processing, they found that the vectors that certain words are assigned to satisfy some curious relations, like “queen - woman + man = king”. Maybe AI can learn that cycles can be added too. One task that I’m having in mind now: given the complement of a complex hypersurface in $\mathbb C^N$, decide if two cycles are homologous. That’s something we could just “see” in $\mathbb C^1$, but somehow it doesn’t feel like a “fundamental” question for geometric intuition, but what geometric intuition helps to answer (if there’s a difference). So, my question is, what tasks would be “fundamental” to forming our geometric intuition? And for those who acquired some intuition in higher dimensions (regular polytopes? sphere-packing? singular locus?), what would be a good dataset and task for acquiring that intuition, whether or not it’s feasible for current machine learning techniques?
2022/07/12
[ "https://mathoverflow.net/questions/426484", "https://mathoverflow.net", "https://mathoverflow.net/users/1189/" ]
At the interface of [topological data analysis](https://en.wikipedia.org/wiki/Topological_data_analysis) and AI (neural networks, machine learning) there is a variety of applications that help to visualize high-dimensional data. One application in this context is [Estimating Betti Numbers Using Deep Learning](https://ieeexplore.ieee.org/document/8852277) (2019) > > This paper proposes an efficient computational approach for estimating > the topology of manifold data as it may occur in applications. For > two- or three-dimensional point cloud data, the computation of Betti > numbers using persistent homology tools can already be computationally > very expensive. We propose an alternative approach that employs deep > learning to estimate Betti numbers of manifolds approximated by point > clouds. The approach could be generalised beyond estimating the > numbers of holes, cavities and tunnels in low-dimensional manifolds to > counting high-dimensional holes in high-dimensional data. > > >
The method ["UMAP"](https://umap-learn.readthedocs.io/en/latest/) comes to mind and uses a lot of mathematics from category theory, topology to reduce dimension. I have tried it on "real world" datasets and on "number theoretic datasets" with custom distances on natural numbers and it works as one would expect it. Here is a video I found and like on yt, created with UMAP about the first million integers: <https://www.youtube.com/watch?v=nCk8dyU7zUM> Maybe you can see something after reducing the dimension with umap...
7,661,104
My code is : ``` EditText edt edt.addTextChangedListener(new TextWatcher() { @Override public void afterTextChanged(Editable arg0) { final String number = edt.getText().toString(); int count = arg0.length(); edt.setSelection(count); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { final String number = edt.getText().toString(); } } ``` I have a dialpad too. When I click a particular number in the dial pad, I need to add that number to the current cursor position. Also, when I press delete, I need to delete the number from the current cursor position. Dialpad Image ![enter image description here](https://i.stack.imgur.com/0AQlE.jpg)
2011/10/05
[ "https://Stackoverflow.com/questions/7661104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/548218/" ]
Try the following code ``` int start =editText.getSelectionStart(); //this is to get the the cursor position String s = "Some string"; editText.getText().insert(start, s); //this will get the text and insert the String s into the current position ``` Here is the code to delete selected text from EditText ``` int start = t1.getSelectionStart(); //getting cursor starting position int end = t1.getSelectionEnd(); //getting cursor ending position String selectedStr = t1.getText().toString().substring(start, end); //getting the selected Text t1.setText(t1.getText().toString().replace(selectedStr, "")); //replacing the selected text with empty String and setting it to EditText ```
I currently use this solution: ``` public static void insertText(String text, EditText editText) { int start = Math.max(editText.getSelectionStart(), 0); int end = Math.max(editText.getSelectionEnd(), 0); editText.getText().replace(Math.min(start, end), Math.max(start, end), text, 0, text.length()); try { editText.setSelection(start + 1); } catch (final IndexOutOfBoundsException e) { } } ```
2,413
When frying food, what's a good alternative to paper towels for soaking up/draining excess oil?
2014/01/05
[ "https://sustainability.stackexchange.com/questions/2413", "https://sustainability.stackexchange.com", "https://sustainability.stackexchange.com/users/737/" ]
Personally I use a wire rack over a cookie sheet to drain fried or greasy foods. The oil drips to the pan below and I can pour the oil into a container or dispose of it however I need to.
Slices of stale bread are a good alternative. I keep crusts / the ends of loaves in the freezer and place 4 to 6 on a tray to cover the tray. You then just place your fried food on top to drain. The bread is fine to go in the compost afterwards.
2,965,626
The "[On the state of i18n in Perl](http://rassie.org/archives/247 "Rassie’s Doghouse » On the state of i18n in Perl")" blog post from 26 April 2009 recommends using [Locale::TextDomain](http://p3rl.org/Locale::TextDomain) module from libintl-perl distribution for l10n / i18n in Perl. Besides I have to use gettext anyway, and gettext support in Locale::Messages / Locale::TextDomain is more natural than in gettext emulation in [Locale::Maketext](http://p3rl.org/Locale::Maketext). The subsection "[15.5.18 Perl](http://www.gnu.org/software/gettext/manual/gettext.html#Perl)" in chapter "[15 Other Programming Languages](http://www.gnu.org/software/gettext/manual/gettext.html#Programming-Languages)" in GNU gettext manual says: > > **Portability** > > The `libintl-perl` package is platform independent but is not part of the Perl core. The programmer is responsible for providing a dummy implementation of the required functions if the package is not installed on the target system. > > > > However neither of two examples in [`examples/hello-perl`](http://git.savannah.gnu.org/cgit/gettext.git/tree/gettext-tools/examples/hello-perl/) in gettext sources (one using lower level Locale::Messages, one using higher level Locale::TextDomain) includes **detecting** if the package is installed on the target system, and providing **dummy implementation** if it is not. What is complicating matter (with respect to detecting if package is installed or not) is the following fragment of Locale::TextDomain manpage: > > **SYNOPSIS** > > > > ``` > use Locale::TextDomain ('my-package', @locale_dirs); > > use Locale::TextDomain qw (my-package); > > ``` > > **USAGE** > > > It is crucial to remember that you use Locale::TextDomain(3) as specified in the section "SYNOPSIS", that means you have to **use** it, not **require** it. The module behaves quite differently compared to other modules. > > > Could you please tell me how one should detect if libintl-perl is present on target system, and how to provide dummy fallthrough implementation if it is not installed? Or give examples of programs / modules which do this?
2010/06/03
[ "https://Stackoverflow.com/questions/2965626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46058/" ]
The gettext manual is wrong to suggest that it is not okay for you to [demand a CPAN prerequisite](http://p3rl.org/CPAN::Meta::Spec#prereqs). Everyone does this in the Perl world, and thanks to the CPAN infrastructure and toolchain, it works just fine. In the worst case you can bundle the dependencies you need. The straight answer to your question is: ``` use Try::Tiny; try { require Locale::TextDomain; Locale::TextDomain->import('my-package', @locale_dirs); } catch { warn 'Soft dependency could not be loaded, using fallback.'; require inc::Local::Dummy::Locale::TextDomain; } ``` Explanation: [`use` is just `require` at compile time followed by `import`](http://perldoc.perl.org/functions/use.html), and it is acceptable to split it in order to force this to execute at run time.
Create a directory "fallback/Locale" and create a module TextDomain.pm there with stub implementations for all functions that you need: ``` package Locale::TextDomain; use strict; sub __($) { return $_[0] } sub __n($$$) { return $_[2] == 1 ? $_[0] : $_[1] } # And so on, see the source of Locale::TextDomain for getting an # idea how to implement the other stubs. ``` Now insert a BEGIN block into the entry point of your application (that is typically a .pl script, not a .pm module): ``` BEGIN { push @INC, "fallback"; } ``` Now Perl will **always** find Locale/TextDomain.pm in @INC, in doubt the stub implementation in the fallback directory.
29,493,444
i hav confirmed that "apples.txt" do exist.what is wrong with my code? ``` def Loadfile(fileName): myfile=open(fileName,'r') next(myfile) for line in myfile: linesplit=line.split() print line print Loadfile('apples.txt') ```
2015/04/07
[ "https://Stackoverflow.com/questions/29493444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4759141/" ]
The file probably isn't in your [working directory](https://stackoverflow.com/questions/17359698/how-to-get-the-current-working-directory-using-python-3). Either change your working directory to where `apples.txt` is located, or provide a full path to the file such as `'C:\\folder\\subfolder\\apples.txt'`
``` arq = open('C:\\python2.6\\projetos\\test\\list.txt', 'r') texto = arq.readlines() for linha in texto: print(linha) arq.close() ```
61,679
This is one of a series of questions centered around how an isolated group of people would survive. Each question focuses on a single aspect of survival. Details about the peoples' situation are below: > > In a novel I am developing, a village's worth of people is living on a > peninsula. The isthmus connecting the peninsula to the mainland is > very narrow, and spanned by a wall, which prevents the people from > leaving (there are deterrents preventing them from climbing the wall > or otherwise circumventing it). They also cannot swim around the wall. This also means that no land-based > animals can cross onto the peninsual from the mainland. The > inhabitants have to live with what they have. For the sake of details, > assume the peninusla is roughly the size, shape, and location of [Mahia > Peninsula](https://en.wikipedia.org/wiki/Mahia_Peninsula). > > > This particular question deals with the resources available to the people, and how they could conceivably live there for *at least* several hundred years. Another user pointed out that since they are on a small piece of land, they will ultimately outgrow the resources available to them. **How can I ensure there are always enough resources?** It should be noted that I plan on regularly (year/6 months) killing off a portion of the population (my goal is to keep roughly the same amount of people on hand, no more). This will help with population control, but I do not know if this is enough to ensure there are always plenty of resources available.
2016/11/18
[ "https://worldbuilding.stackexchange.com/questions/61679", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/6620/" ]
**To survive in the long run, your population's diet will have to diversify in range, shrink in quality, and vary hugely in quantity** *Diversity*: Their diet on land will expand to encompass a wider definition of what animals count as food than most of your modern readers, 'pest' species included: rats, bushtail possums (if we're using the modern New Zealand example of Mahia as a baseline), dogs, deer, feral pigs (who will in turn eat the human's waste) and so on. If it moves on or near land, and it's not horribly poisonous or venomous, they will try to eat it. Being on a peninsula, they will have access to nesting or burrowing seabirds, their chicks and their eggs. Gull egg collection (for food) was a major activity for island populations who couldn't afford to be picky. Witness the annual muttonbird (shearwater) take still carried out in New Zealand today. St Kilda and other islands in the Hebrides were also known for eating gulls. 'Odd' seafood will also be a regular part of their diet - particularly in famine conditions. Seaweed, whelks, cockles, seaslugs etc. Whatever can be scraped off a rock at low tide will go in their stew pots. Depending on the climate of your peninsula, they may also have seasonal gluts of insects to eat: grubs, crickets, locusts, wasp larvae, bee honey comb (complete with bee larvae) and so on. Agriculture - whether farms or gardens - will rely heavily on human and animal waste as fertiliser. Given the size of the peninsula, I doubt that there will be many large domestic animals around. They need too much pasture. *Quality*: They cannot afford to be picky, especially when food gets scarce. On the one hand, this means they will likely eat carrion, sick or wounded creatures ("I can eat that staggering possum now, and get Tuberculosis in 10 years time, or I can not eat it now and be dead next week from hunger"), and plant food that's entering the 'slimy yet satisfying' stage: wormy apples have extra protein after all... This all carries some risk in terms of health, but as I implied earlier your people will have to choose between eating something rotten or starvation. On the other hand, this may also lead to an interesting food culture in terms of fermented things. They have access to salt (sea water) which can be boiled to brine to make a preservative. Fish, shellfish and vegetables can all be preserved in salt brine. Other fermentation methods do not use salt (eg [Kaanga pirau](http://www.teara.govt.nz/en/video/39145/kaanga-pirau-stinking-corn): rotten corn). Fermentation has the benefit of trapping valuable vitamins in some food, as well as preserving the food long term, which is vital when the quantity of food is not guaranteed. *Quantity* I mentioned gluts of insects above. However, they will also be absent as a or hard to find at some times of year, especially in a temperate climate. This goes for the majority of your food sources. Seabirds will likely nest only at certain times of year, plants grow slowly over winter if at all, and adverse weather conditions may prevent fishing during the equinox, to give a few examples. Your people, being cut off from the mainland and its food sources, cannot import food to balance out those cycles and will regularly face certain times of year when they have low food resources available. Late spring is a possibility. You have used up your winter stocks, crops are growing but haven't matured yet, the weather is too unpredictable to fish and so on. Then you have to think about famine. Sometimes, perhaps in those hungry times of year, your food resources will not renew themselves. Maybe your people anticipate seabirds to arrive and nest in early summer? Well this year they will not nest well at all, and the fishing is very poor too. Here, the local climate of the ocean and its currents has driven your food away from shore - as the currents move, the fish move away. As the water warms too much, the shellfish die. If this situation is combined with drought or flooding that removes another food source temporarily you have a serious problem on your hands. Famine will kill your young children and your elderly through starvation or diarrhea or any number of famine related causes. How they cope with starvation years will influence their culture in the long run, and will also serve to manage your population numbers, potentially allowing other food resources to bounce back in later years. Quick breeding animals like seabirds will recover their population levels faster than humans as a general rule as environmental conditions return to normal. **tl;dr: There will be years that your population crashes, but through a combination of eating whatever they can get, and not being fussy about the state that it's in, they should be ok in the mid-to-longer term**
I suggest putting a nice, steep, jagged mountain at the far end of the peninsula, made of nice hard flinty rocks which will make great tools and building materials. Let there be a robust population of fast-breeding goats on that mountain, and plenty of fast-growing trees or better yet, bamboo on its lower slopes. Further, let there be a large, clear, flowing spring on the mountainside, fed by rainwater and filtered through layers of rock. Now the people, provided their population doesn't outstrip the regenerative capacity of the bamboo or goat populations, will always have these valuable resources close at hand: stone, water, horns, fur, meat, and wood. I choose goats and bamboo because they're both highly utilitarian and damn hard to carelessly exterminate. I place them on a jagged mountain because the mountain, being difficult terrain for humans, will serve as an ecological reservoir, a place the goats and bamboo can retreat to if they're ever threatened by overuse. It also adds a bit of variety to the landscape, and the possibility of an adventurous goat-hunting expedition, maybe a rite of passage for the young villagers. It would even be possible to domesticate some of these goats, and keep them in pens nearer to the human settlement. 6-8 goats per acre is possible if you have good pasture, so Google tells me. Given plausible reproductive rates, a 1000-acre goat plantation could then supply about ten goats' worth of meat and leather per day, on only ~2% of the peninsula's total land area. There's also the possibility of milking them. Pigs and chickens are other good options for livestock, and both would be capable of surviving in wild populations on the mountain, as well. I notice you've placed this peninsula in the vicinity of New Zealand. What is New Zealand known for, agriculturally? That's right, apples. Apples are great because they're delicious, they can produce for many years, and they can be pressed into cider, stored underground, or otherwise made to last through the winter. They do require a degree of knowledge about pruning, and even more importantly, cloning (growing them from seeds doesn't usually produce good fruit trees - strange but true). Lots of other crops are possible... corn, beans, and squash would probably fare well. Leftovers can be fed to the goats. And of course, this beings a peninsula, there's also the neighboring ocean to consider. Cockles and mussels on the shore, maybe, occasional nesting turtles, and fish further out - if the [acid leeches](https://worldbuilding.stackexchange.com/a/61857/10408 "acid leeches") don't scare you off. So we've got food (goats, pigs, apples, corn, clams) shelter (wood and stone) and clothing (goat skin). Better throw in some medicinal herbs, some good clay beds for pottery, and some extra trees for firewood - you can never have too much firewood when winter comes. Humans have been known to deforest entire mountainsides in search of it, so be careful of that - insulate those houses well. (Straw works for that.) A strong culture of stewardship toward the land would help too. The resources are there - as long as the people don't overuse them, they'll survive easily.
19,857,824
Is it possible to specify custom filters like `'ABC*.pdf'` which means: "*Show all PDF which starts with ABC*"? I can only specify `*.pdf`, `*.doc`, `*.*`, etc. Thanks Florian
2013/11/08
[ "https://Stackoverflow.com/questions/19857824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2071938/" ]
Answer is straight forward : **NO** You can set the Filters to allow only specific File Types with property `Filter` asbelow : ``` fileOpenDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"; ``` but filtering file names is `NOT` Possible. You can create your own Custom `OpenFIleDialog` in that case. See this Link for more info : [How to create customized open file dialog in C#](https://stackoverflow.com/questions/7831432/how-to-create-customized-open-file-dialog-in-c-sharp)
Use this: ``` Microsoft.Win32.OpenFileDialog myDialog. = new Microsoft.Win32.OpenFileDialog(); myDialog..DefaultExt = ".pdf"; myDialog.Filter = "FilesIWant (ABC*.pdf)|ABC*.pdf ```