source
sequence
text
stringlengths
99
98.5k
[ "stackoverflow", "0019164124.txt" ]
Q: Constraints on bitemporal database Background: I'm designing a bitemporal database, where we have 1:N relations between bitemporal tables (we also have M:N relations, but they're just modeled with a connector table and two 1:N relations, so I consider them a special case of an 1:N relation). To illustrate things, let's consider a simple case with two tables: |===============| |==================| | tblOrder | | tblOrderItem | |============== | |==================| | - OrderId | | - OrderItemId | | - OrderNumber | | - FK_OrderId | |===============| | - Amount | |==================| FK_OrderId is a foreign key to tblOrder. To make this database model bitemporal, I've come up with the following design: |===============| |==================| |====================| | tblOrder | | tblOrderItem | | tblVersions | |============== | |==================| |====================| | - Id | | - Id | | - VersionId | | - OrderId | | - OrderItemId | | - VersionDate | | - OrderNumber | | - FK_OrderId | |====================| | - VersionId | | - Amount | | - IsDeleted | | - VersionId | | - StartDate | | - IsDeleted | | - EndDate | | - StartDate | |===============| | - EndDate | |==================| Explanations: The VersionId columns are foreign keys to the tblVersions table. For every change in the database, an entry in the tblVersions table is created. The current state of the data is then just the sum of all versions. This makes it possible to reconstruct previous states of the database (via a WHERE VersionDate < ... clause). This is the transaction time dimension of the bitemporality. The tblVersions table could also be avoided if we're just including theVersionDate` column into the two data tables. The StartDate and EndDate columns are the valid time dimensionality of the bitemporality. Yes, EndDate is kind of redundant, we could model the tables with just StartTime. The Id columns of the two tables are the new primary keys. Because we have multiple rows for the same entity (multiple versions, multiple date ranges in valid time), the ID of the entity cannot be the primary key of the table. The columns OrderId and OrderItemId are the IDs of the entity, but not anymore the primary key of the table. Instead of creating the new primary keys Id, we could also have defined the primary key as (OrderId, VersionId, StartDate). If an entity is deleted, we just create a new version entry, as well as an entry in the entity table with IsDeleted = 1. All other entries in the table (the inserts and updates) have IsDeleted = 0. The column FK_OrderId of tblOrderitem references the column OrderId of tblOrder. This is not anymore a real foreign key (in the sense of a database constraint), since OrderId is not anymore a primary key. But it still tells us which OrderItems are part of a certain Order. This seems to work well, we have created the necessary CRUD queries and are able to read and write bitemporal data. Question: What kind of constraints do I need for that to work consistently? I'm not interested in how to implement the constraints (whether to implement them as database constraints like FOREIGN KEYs or UNIQUE constraints, or TRIGGERs, or CHECKs, whatever). I just need to know what types of constraints I need. I figured out a bunch of constraints, which I'm gonna post as an answer. But maybe there are more? A: (I'm using the abbreviation PIVT = 'point in valid time'. This denotes a certain point in time on the valid time dimension) Here are the constraints I already thought of: FK_VersionId: Obviously, we need standard foreign key constraints on the VersionId columns. Bitemporal uniqueness: Also, the combination (OrderId, VersionId, StartDate) must be unique (and the same for tblOrderItem). Valid time serialization: We need to check that for each entity and each version, there are no overlaps in valid time, i.e. the columns StartDate and EndDate do not overlap, and StartDate is always earlier than EndDate. Deletion integrity: We need to make sure that for each entity and each PIVT, there is maximal one row with IsDeleted = 1, and if there is such a row, there must not be any version of the entity after that row. Referential integrity: We need to check that for each OrderItem entity, each version and each PIVT, the value of FK_OrderId is set to a value that identifies an Order entity which exists at the given PIVT, which has been inserted in an earlier version and which has not been deleted (by setting IsDeleted = 1).
[ "stackoverflow", "0003829487.txt" ]
Q: Datagridview to Clipboard with formatting For a VB.Net application needing to output the data to clipboard, with formatting, I am in need of some help. For now, I am exporting data from the clipboard using MainView.ClipboardCopyMode = Windows.Forms.DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText System.Windows.Forms.Clipboard.SetDataObject(MainView.GetClipboardContent()) Now I need to extend this with the formatting / style from the DataGridView. I have read several ExcelExporters, all writing to an Excel file directly, but I need to write to the Clipboard. The DataGridView exposes nothing other than the DataGridView.GetClipBoardContent() which just gives the raw data. I need to get some XML/HTML/RTF object. I have tried the following: Dim test As New DataObject test.SetData(DataFormats.EnhancedMetafile , True, DataGridView1.GetClipboardContent) Clipboard.SetDataObject(test) This does not work as of yet. Any tips to easily convert an unbound DataGridView to XML/HTML/RTF/Enhanced Metafile? A: If it does not support it natively (which you imply), the best would be to render the content to HTML or RTF. HTML tables would be more suited for Excel and it seems to interpret it fairly well.
[ "stackoverflow", "0008738635.txt" ]
Q: Delphi: RoundRect with Gradient How to draw a round rectangle and fill it with a gradient in a list view on Custom Draw Item using GDI or GDI+? For example, to draw a gradient we can use GradientFillCanvas from GraphUtil.pas A: GDI I found a way in Gradient v.2.71 procedure TForm1.FormPaint(Sender: TObject); var r: trect; bm: tbitmap; X, Y, W, H, S: Integer; Rgn: THandle; Org: TPoint; begin bm := tbitmap.Create; bm.Width := 1; bm.Height := 255; r.Create(0, 0, 1, 255); GradientFillCanvas(bm.Canvas, clred, clblue, r, gdVertical); r.Empty; X := 50; Y := 50; W := 200; H := 40; Rgn := CreateRoundRectRgn(X, Y, X + W, Y + H, 3, 3); GetWindowOrgEx(Canvas.Handle, Org); OffsetRgn(Rgn, -Org.X, -Org.Y); SelectClipRgn(Canvas.Handle, Rgn); Canvas.StretchDraw(Rect(X, Y, X + W, Y + H), bm); SelectClipRgn(Canvas.Handle, 0); DeleteObject(Rgn); bm.Free; end; GDI+ function CreateRoundRectangle(rectangle: TGPRect; radius: integer): TGPGraphicsPath; var path : TGPGraphicsPath; l, t, w, h, d : integer; begin path := TGPGraphicsPath.Create; l := rectangle.X; t := rectangle.y; w := rectangle.Width; h := rectangle.Height; d := radius div 2; // divide by 2 // the lines beween the arcs are automatically added by the path path.AddArc(l, t, d, d, 180, 90); // topleft path.AddArc(l + w - d, t, d, d, 270, 90); // topright path.AddArc(l + w - d, t + h - d, d, d, 0, 90); // bottomright path.AddArc(l, t + h - d, d, d, 90, 90); // bottomleft path.CloseFigure(); result := path; end; path:=CreateRoundRectangle(R,20); FillPath(lingrbrush,path)
[ "stackoverflow", "0032224930.txt" ]
Q: file decryption, encrypted with vim blowfish when i try to decrypt abc.json using command vim abc.json i got the following message E821: File is encrypted with unknown method please help. A: To use blowfish2 encryption in Vim, you need Vim version 7.4.399 or higher.
[ "stackoverflow", "0017081815.txt" ]
Q: Why would I ever use anything else than %r in Python string formatting? I occasionally use Python string formatting. This can be done like so: print('int: %i. Float: %f. String: %s' % (54, 34.434, 'some text')) But, this can also be done like this: print('int: %r. Float: %r. String: %r' % (54, 34.434, 'some text')) As well as using %s: print('int: %s. Float: %s. String: %s' % (54, 34.434, 'some text')) My question is therefore: why would I ever use anything else than the %r or %s? The other options (%i, %f and %s) simply seem useless to me, so I'm just wondering why anybody would every use them? [edit] Added the example with %s A: For floats, the value of repr and str can vary: >>> num = .2 + .1 >>> 'Float: %f. Repr: %r Str: %s' % (num, num, num) 'Float: 0.300000. Repr: 0.30000000000000004 Str: 0.3' Using %r for strings will result in quotes around it: >>> 'Repr:%r Str:%s' % ('foo','foo') "Repr:'foo' Str:foo" You should always use %f for floats and %d for integers. A: @AshwiniChaudhary answered your question concerning old string formatting, if you were to use new string formatting you would do the following: >>> 'Float: {0:f}. Repr: {0!r} Str: {0!s}'.format(.2 + .1) 'Float: 0.300000. Repr: 0.30000000000000004 Str: 0.3' Actually !s is the default so you don't need it, the last format can simply be {0}
[ "stackoverflow", "0014175024.txt" ]
Q: Peculiar effect when scrolling JScrollPane How can I deal with this weird effect when scrolling using the JScrollArea: The code: import java.util.*; import java.util.prefs.BackingStoreException; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.AdjustmentEvent; import java.awt.event.AdjustmentListener; import java.awt.image.BufferedImage; import java.io.*; import javax.swing.*; import javax.imageio.*; public class Main extends JFrame implements ActionListener, AdjustmentListener{ CustomComponent cc; JScrollPane jsp; public static void main(String[] args) { Main m = new Main(); } public Main(){ setTitle( "Diverse Testari 7"); setDefaultCloseOperation(EXIT_ON_CLOSE); setSize(600, 400); cc = new CustomComponent(); cc.setImage("rgbcmy.jpg"); jsp = new JScrollPane( cc, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED ); jsp.setPreferredSize( new Dimension( getWidth(), getHeight() ) ); jsp.setOpaque( true ); jsp.setBackground( Color.DARK_GRAY ); jsp.getVerticalScrollBar().addAdjustmentListener(this); jsp.getHorizontalScrollBar().addAdjustmentListener(this); setBackground( Color.red ); add( jsp ); setVisible( true ); } @Override public void actionPerformed(ActionEvent e) { System.out.println("EVENT: " + e.toString() ); } @Override public void adjustmentValueChanged(AdjustmentEvent arg0) { // TODO Auto-generated method stub } } class CustomComponent extends JPanel{ BufferedImage img = null; public void setImage( String str ){ try { img = ImageIO.read( new File( str ) ); System.out.println(img.getColorModel().toString()); System.out.println("SUCCESS!"); } catch (IOException e) { e.printStackTrace(); } } @Override public Dimension getPreferredSize() { // TODO Auto-generated method stub return new Dimension(img.getWidth(), img.getHeight() ); } @Override protected void paintComponent(Graphics g) { Graphics2D g2d = (Graphics2D) g; g2d.setClip(100, 100, 100, 100); System.out.println("paintComponent"); if( img != null ) { System.out.println("Obs: Imagine existenta!"); g2d.drawImage(img, null, 0,0); } else { System.out.println("Eroare: nu este imaginea!"); } }//*/ } A: try to call super.paintComponent(g) right at the beginning of the paintComponent overridden method. Like this: @Override protected void paintComponent(Graphics g) { super.paintComponent(g); // rest of the method's code Hope this helps! Good luck! A: this is common issue where paint code isn't optimized, part of side effect is possible to removing by disable flickering, have to set additonal parameters for JViewports ScrollMode JViewport viewPort = jsp.getViewport(); viewPort.setScrollMode(JViewport.BLIT_SCROLL_MODE); viewPort.setScrollMode(JViewport.BACKINGSTORE_SCROLL_MODE); viewPort.setScrollMode(JViewport.SIMPLE_SCROLL_MODE); and by notifying by super.paintComponent(g); too +1 for Óscar Gómez Alcañiz
[ "stackoverflow", "0050872985.txt" ]
Q: Google Actions sdk not playing audio using MediaObject I have tried to play audio using MediaObject, MediaObject is not playing given mp3 audio files, but i got below error message" MalformedResponse 'final_response' must be set." 'use strict'; const functions = require('firebase-functions'); const {WebhookClient} = require('dialogflow-fulfillment'); const {Card, Suggestion} = require('dialogflow-fulfillment'); const { dialogflow, BasicCard, BrowseCarousel, BrowseCarouselItem, Button, Carousel, LinkOutSuggestion, List, MediaObject, Suggestions, SimpleResponse, } = require('actions-on-google'); process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => { const agent = new WebhookClient({ request, response }); console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers)); console.log('Dialogflow Request body: ' + JSON.stringify(request.body)); function welcome(agent) { agent.add(`Welcome to my agent!`); } function fallback(agent) { agent.add(`I didn't understand`); agent.add(`I'm sorry, can you try again?`); } // // Uncomment and edit to make your own intent handler // // uncomment `intentMap.set('your intent name here', yourFunctionHandler);` // // below to get this function to be run when a Dialogflow intent is matched function yourFunctionHandler(agent) { agent.add(`This message is from Dialogflow's Cloud Functions for Firebase editor!`); let conv = agent.conv(); conv.ask(new Suggestions('Suggestion Chips')); conv.close(new MediaObject({ name: 'Jazz in Paris', url: 'https://storage.googleapis.com/automotive-media/Jazz_In_Paris.mp3', description: 'A funky Jazz tune', icon: new Image({ url: 'https://storage.googleapis.com/automotive-media/album_art.jpg', alt: 'Media icon', }), })); conv.ask(new Suggestions(['suggestion 1', 'suggestion 2'])); } // Run the proper function handler based on the matched Dialogflow intent name let intentMap = new Map(); //intentMap.set('Default Welcome Intent', welcome); //intentMap.set('Default Fallback Intent', fallback); intentMap.set('PlaySongIntents', yourFunctionHandler); // intentMap.set('your intent name here', googleAssistantHandler); agent.handleRequest(intentMap); }); I am getting below response "responseMetadata": { "status": { "code": 10, "message": "Failed to parse Dialogflow response into AppResponse because of empty speech response", "details": [ { "@type": "type.googleapis.com/google.protobuf.Value", "value": "{\"id\":\"ff0ee47a-9df3-46c9-97db-f6db6442179b\",\"timestamp\":\"2018-06-15T09:42:53.424Z\",\"lang\":\"en-us\",\"result\":{},\"status\":{\"code\":206,\"errorType\":\"partial_content\",\"errorDetails\":\"Webhook call failed. Error: Request timeout.\"},\"sessionId\":\"1529055750970\"}" } ] } } } A: The error message suggests that you're not including a message that should be said in addition to the audio that you want to play. It is required to include a SimpleResponse along with the audio. You're mixing Dialogflow responses and Actions on Google responses, which may be confusing the response parser. You should add a SimpleResponse to the conv object as part of your response. So that portion of the code might look something like this: function yourFunctionHandler(agent) { let conv = agent.conv(); conv.ask(new SimpleResponse("Here is a funky Jazz tune")); conv.ask(new Suggestions(['suggestion 1', 'suggestion 2'])); conv.close(new MediaObject({ name: 'Jazz in Paris', url: 'https://storage.googleapis.com/automotive-media/Jazz_In_Paris.mp3', description: 'A funky Jazz tune', icon: new Image({ url: 'https://storage.googleapis.com/automotive-media/album_art.jpg', alt: 'Media icon', }), })); } additionally, you don't import the Image object as part of your require('actions-on-google'), which is what is causing the error when the function runs. Make sure you get all the objects you need as part of the require.
[ "stackoverflow", "0033343058.txt" ]
Q: Is there any alternative to Apple ResearchKit for Android? Is there any alternative to Apple ResearchKit for Android? or Is there any medical related API and Library for Android smartphones? Thanks, A: The Android version of ResearchKit is being currently built. It's called ResearchStack and I believe the beta version will be released in January. Check http://researchstack.org/ for more information
[ "stackoverflow", "0045223501.txt" ]
Q: DynamoDB: KeyConditionExpression to check if an attribute exists or not null I am using boto3 to query DynamoDB. And I have heard that table.query() is more efficient that table.scan() I was wondering if there is a way to check if the value exists using query() method? response = table.scan( FilterExpression=Attr('attribute').exists() If it is not possible to check using query() is there any other method that is more efficient than scan()? This question is not a duplicate - I am looking for a way to optimize querying for existing/non existing attributes of query() or scan() A: It seems that query() is more efficient than scan() because it works with hash key only, and the query must match base table schema. That is the reason for it to be so efficient. Therefore it is not possible to scan() for attributes that are not in the base schema.
[ "opensource.stackexchange", "0000001668.txt" ]
Q: What are the limits of Libre when publishing open access controversial books? We're living in freedom of speech community. However when writing controversial books, are there any topics which are not allowed to write about in First World countries (even for educational purposes)? How do you know when you cross the line? One example could be Uncle Fester books or WikiLeaks which are the borderlines I think. Are there any other examples? A: FLO licenses take a legal, copyright-restricted-by-default work, and give you permission to copy, modify and/or distribute that work. They would not take precedence over criminal law in your country, including laws that criminalise or restrict publication and distribution of certain materials.
[ "stackoverflow", "0053437218.txt" ]
Q: Spring Boot @Async annotation and MockRestServiceServer I'm using Spring Boot 2.0.6 and Java 10. I did the following service that only hits an external rest api using RestTemplate. @Service @Slf4j public class DbApiClientImpl implements DbApiClient { private final String URL_DELIMITER = "/"; private RestTemplate restTemplate; private String url; public DbApiClientImpl( RestTemplateBuilder restTemplate, @Value("${dbapi.namespace}") String namespace, @Value("${dbapi.url}") String uri, @Value("${dbapi.username}") String username, @Value("${dbapi.password}") String password) { this.restTemplate = restTemplate.basicAuthorization(username, password).build(); this.url = namespace.concat(uri); } @Override @Async("asyncExecutor") public Merchant fetchMerchant(String id) { ResponseEntity<Merchant> response = restTemplate.getForEntity(url.concat(URL_DELIMITER).concat(id), Merchant.class); return response.getBody(); } } And the following test using MockeRestServiceServer: @RunWith(SpringRunner.class) @RestClientTest(value = {DbApiClient.class}) public class DbApiClientTest { private static final String TEST_NAME = "test"; private static final String TEST_NAME_BAD_REQUEST = "test- 1"; private static final String TEST_NAME_SERVER_ERROR = "test-2"; @Autowired DbApiClient dbApiClient; @Value("${dbapi.namespace}") private String namespace; @Value("${dbapi.url}") private String dbApiUrl; @Autowired private MockRestServiceServer mockServer; @Autowired private ObjectMapper objectMapper; @Test public void test() throws JsonProcessingException, IOException { Merchant mockMerchantSpec = populateFakeMerchant(); String jsonResponse = objectMapper.writeValueAsString(mockMerchantSpec); mockServer .expect(manyTimes(), requestTo(dbApiUrl.concat("/").concat(TEST_NAME))) .andExpect(method(HttpMethod.GET)) .andRespond(withSuccess(jsonResponse, MediaType.APPLICATION_JSON)); assertNotNull(dbApiClient.fetchMerchant(TEST_NAME)); } The thing is that I'm getting the following exception when I run the test "No further request expected HTTP GET http://localthost... excecuted" So seems that the @Async is borking MockerServerService response... Also, If I commented the @Async annotation everything works just fine and I get all test green. Thanks in advance for your comments. Update: As per @M.Deinum's comment. I removed the CompletableFuture from the service but I'm still getting the same exception. A: The problem is your code and not your test. If you read the documentation (the JavaDoc) of AsyncExecutionInterceptor you will see the mention that only void or Future is supported as a return type. You are returning a plain object and that is internally treated as void. A call to that method will always respond with null. As your test is running very quickly everything has been teared down already (or is in the process of being teared down) no more calls are expected to be made. To fix, fix your method signature and return a Future<Merchant> so that you can block and wait for the result. @Override @Async("asyncExecutor") public Future<Merchant> fetchMerchant(String id) { ResponseEntity<Merchant> response = restTemplate.getForEntity(url.concat(URL_DELIMITER).concat(id), Merchant.class); return CompletableFuture.completedFuture(response.getBody()); } Now your calling code knows about the returned Future as well as the Spring Async code. Now in your test you can now call get on the returned value (maybe with a timeout to receive an error if something fails). TO inspect the result.
[ "softwareengineering.stackexchange", "0000134651.txt" ]
Q: How can I get into C++ graphics library? I have been programming for a year so far and I know 2 languages: C and C++. I've covered the basics, I've written functional windows programs, and I've written complicated bits of code. When I was using Turbo C for learning the C language I noticed a library called "Graphics.h". I've looked it up and I received amazing examples of graphics manipulation. My question is straightforward. How can I get started with learning graphics in C++? Is there a good tutorial that covers it all up? A: graphics.h isn't relevant to anything. It's been 10-15 years since that header was useful. The same for the Turbo C compiler. You need to upgrade your compiler to, let's say, Visual Studio 2010 Express (free) for Windows. Then you can look at things like Direct2D and GDI+ for 2D graphics. A: Back in the graphics.h days each compiler had it's own limited graphics library. Now you program to either DirectX (Microsoft) or OpenGL (everywhere). After a few years of being sidelined to high-end Unix cad OpenGL/OpenGLEs is making a big splash on mobile devices For a list of books see https://stackoverflow.com/questions/5926357/c-opengl-books One warning - there are a lot of 20year old out of date opengl tutroials on the web - start here An intro to modern OpenGL. ps. Some of the maths of 3D graphics (matrix transformations etc) might be beyond what you have covered in school but it's very easy - you just have to sit down and work through it. But do go through all the math until you understand it, you will need it! A: Graphics typycally require some knowledge about platform specific interfaces, some general math, and eventually some typical pattern. You can start from the Widows GDI (and GDI+) and from the X Window system (for Unix/Linux) and move to 3d with openGL(every platform) or Direct3d(on Windows)
[ "aviation.stackexchange", "0000036668.txt" ]
Q: What does the word "boot" mean? I found this word "boot" in one book. The chapter was connected with ICING operations, and I found this word with little explanation: A tube bonded to a surface, e.g. wing edge. When pressurized with fluid, it breaks up ice. Please explain what is it? What aircraft equipped with it? Photos would be nice. A: Versalog already told the core of the thing. Most prop aircraft which are approved for flights into known icing conditions have such boots to remove the ice from the wings leading edge. Those boots are either inflated manually whenever you need them (by the press of a button of course), at regular intervals or automatically whenever ice is detected. Check this picture, the black thing is the boot on a Dash 8's wing: Link A: Find a picture of any WWII bomber or any modern Cessna Caravan and there should be a black stripe along the leading edge of the wing and tail surfaces. That is termed a boot. (Image source) Inflating it slightly will make the ice break and fall off the wing.
[ "travel.stackexchange", "0000129858.txt" ]
Q: Does travel to Iran void a existing US visa? I'm an Indian citizen that currently resides in Canada. I don't qualify for ESTA so I have an existing US B1/B2 visa instead that is valid for 10 years. I was looking to plan a trip to Iran since they opened it up to Indian citizens with visa on arrival. My question is, would a visit to Iran invalidate that US visa? I know that in the case of ESTA it gets cancelled and VWP citizens need to apply for the B1/B2 visa but in my case I already have that in my passport. I'm a Canadian permanent resident if that changes anything. Thanks! A: Visiting Iran does NOT invalidate an existing US visa. People that have visited Iran recently are not able to enter the US using the Visa Waiver Program, which is why an existing ESTA will be invalidated when visiting Iran. However this is not the case for someone entering the US using a visa, so your visa is still valid after such a visit. As is always the case, when entering the US you can be questioned and potentially refused entry to the country. It is very possible you will be questioned about your trip to Iran, but presuming it was for tourist or similar purposes then I would not expect you to have any issues, and countless people have done this before you without issue.
[ "ru.stackoverflow", "0000557498.txt" ]
Q: Не компилируется пример использующий библиотеку boost Установил библиотеку boost на свою ubuntu командой sudo apt-get install libboost-all-dev. Не компилируется пример из википедии: #include <boost/thread/thread.hpp> #include <iostream> using namespace std; void hello_world() { cout << "Здравствуй, мир, я - thread!" << endl; } int main(int argc, char* argv[]) { boost::thread my_thread(&hello_world); my_thread.join(); return 0; } Компилятор выдает ошибку: /tmp/ccq2zeuG.o: In function `__static_initialization_and_destruction_0(int, int)': ch.cpp:(.text+0xd4): undefined reference to `boost::system::generic_category()' ch.cpp:(.text+0xe0): undefined reference to `boost::system::generic_category()' ch.cpp:(.text+0xec): undefined reference to `boost::system::system_category()' /tmp/ccq2zeuG.o: In function `boost::thread_exception::thread_exception(int, char const*)': ch.cpp:(.text._ZN5boost16thread_exceptionC2EiPKc[_ZN5boost16thread_exceptionC5EiPKc]+0x23): undefined reference to `boost::system::system_category()' /tmp/ccq2zeuG.o: In function `boost::detail::thread_data_base::thread_data_base()': ch.cpp:(.text._ZN5boost6detail16thread_data_baseC2Ev[_ZN5boost6detail16thread_data_baseC5Ev]+0x1e): undefined reference to `vtable for boost::detail::thread_data_base' /tmp/ccq2zeuG.o: In function `boost::thread::start_thread()': ch.cpp:(.text._ZN5boost6thread12start_threadEv[_ZN5boost6thread12start_threadEv]+0x24): undefined reference to `boost::thread::start_thread_noexcept()' /tmp/ccq2zeuG.o: In function `boost::thread::~thread()': ch.cpp:(.text._ZN5boost6threadD2Ev[_ZN5boost6threadD5Ev]+0x15): undefined reference to `boost::thread::detach()' /tmp/ccq2zeuG.o: In function `boost::thread::get_id() const': ch.cpp:(.text._ZNK5boost6thread6get_idEv[_ZNK5boost6thread6get_idEv]+0x18): undefined reference to `boost::thread::native_handle()' /tmp/ccq2zeuG.o: In function `boost::thread::join()': ch.cpp:(.text._ZN5boost6thread4joinEv[_ZN5boost6thread4joinEv]+0x88): undefined reference to `boost::thread::join_noexcept()' /tmp/ccq2zeuG.o: In function `boost::detail::thread_data<void (*)()>::~thread_data()': ch.cpp:(.text._ZN5boost6detail11thread_dataIPFvvEED2Ev[_ZN5boost6detail11thread_dataIPFvvEED5Ev]+0x20): undefined reference to `boost::detail::thread_data_base::~thread_data_base()' /tmp/ccq2zeuG.o:(.rodata._ZTIN5boost6detail11thread_dataIPFvvEEE[_ZTIN5boost6detail11thread_dataIPFvvEEE]+0x10): undefined reference to `typeinfo for boost::detail::thread_data_base' collect2: error: ld returned 1 exit status Как компилировать программы, использующие boost ? A: Это ошибки линкера, а не компилера: линкер не знает где взять реализацию использующихся функций. Нужно указать линкеру какие библиотеки нужно подключать, где они лежат и так далее. Поскольку вы не указали как именно вы собираете программу, конкретные шаги по исправлению указать проблематично.
[ "stackoverflow", "0059688253.txt" ]
Q: ES6/ES7 extend class with same name Since conditional importing of modules is not yet implemented, how can I extend or override the same class: // I have a main class // main.js export default class Main {} // Main class is used by myClass class myClass { constructor(){ new Main() } } // I have an extended main class // main-extended.js export default class MainExtended extends Main {} // the MainExtended is now used by myClass export class myClass { constructor(){ new MainExtended() } } // third-class.js // now I need to do this with any class I can find, // preferably with the extended version of both, if both defined export default class ThirdClass { constructor(...args){ return new myClass(...args) } } // destinations // index.js import Main, {myClass} from main.js import ThirdClass from third-class.js // index-extended.js import MainExtended, {myClass} from main-extended.js import ThirdClass from third-class.js The problem was that, for some reason, index.js compiled also included myClass calling for MainExtended, so I decided to only include ThirdClass in index-extended, as a bonus feature of MainExtended. But I still want to know if there is another way around. A: Like VLAZ said in the comments, I'm not 100% sure on what you're asking, but could you do something like this? Solution 1 class MyClass { constructor(_main){ myMain = _main; } } const regularMain = new MyClass(new Main()); const extendedMain = new MyClass(new MainExtended());
[ "rpg.stackexchange", "0000036347.txt" ]
Q: What tools are available to help me create creatures and NPCs? I have only played Dungeons and Dragons 3.0 but was looking to upgrade to Dungeons and Dragons 3.5 and was wondering if there is any free or cheap (that is, a lot less than $50) software tools or websites that can help manage the game for a DM. I would like recommendations for both 3.0 and 3.5, but I kind of need it to be idiot-proof or at least have an instruction manual. Ideally, what I'm looking for helps the DM create fully-statted monsters and NPCs and includes enough information so that the DM doesn't have to flip through a stack of books constantly during play. A: I haven't used it for straight 3.x in quite some time, but PCGen is quite a fully-featured d20 system character builder. I use it mostly for Pathfinder these days, but I also used it for 3.x during my Living Greyhawk career. It is a free product, for both the good and the bad that comes with it - datafiles are built by volunteers, so are free, but may not be available for every option you want. You could build your own if you needed to, but it is complex. Herolab is a commercial option that supports multiple game systems (rather than just d20 systems). It will cost you $30 for the software, including one free set of core datafile. Further datafiles, either for expansions or for new game systems, can be bought for a variety of prices. I've never actually used Herolab myself, but I did use Army Builder for quite some time from the same development company.
[ "stackoverflow", "0010566064.txt" ]
Q: Streaming with JavaScript I want to stream real-time data from a server into a JavaScript webpage. For example, if the server receives meteorological data measurements every second, I want to visualize them as a moving graph on the webpage. Naturally, Ajax can be used for this. However, this is not what the HTTP protocol was built for. It would help to have a faster, more lightweight protocol. Ideally, a persistent TCP connection. Are there any such possibilites in modern browsers, without using additional plugins and applets? Or can this be only done with Flash, Java, etc...? A: I would check out Socket.IO. It tries to make use of WebSockets, but can fall back on standard AJAX.
[ "stackoverflow", "0025289463.txt" ]
Q: PHP Replace keyword from key-value in multidimension array using string_replace I have a multidimensional array like this Array ( [0] => Array ( [0] => Foo [1] => Bar [2] => I like foobar [3] => 09/09/2014 ) [1] => Array ( [0] => Foo2 [1] => Bar2 [2] => Very much [3] => 10/09/2014 ) ) keys array which looks like this Array ( [0] => From [1] => To [2] => Text [3] => Schedule Date ) and a message is a string variable $message = "Hi {To} message is from {From} come get {Text}. My question is how do I replace the keywords between {$key} for all the array values at the same time to produce a new $messages array containing the messages with keywords replaced? This has to be done dynamically and not hard coded because different values will be used every time. A: Here is some commented code for you. This should work for you as long as the number of keys matches the number of elements in your input array. This also assumes your placeholders match your key names. //input data $inputs = array(); $inputs[0][] = 'Foo'; $inputs[0][] = 'Bar'; $inputs[0][] = 'I like foobar'; $inputs[0][] = '09/09/2014'; $inputs[1][] = 'Foo2'; $inputs[1][] = 'Bar2'; $inputs[1][] = 'Very much'; $inputs[1][] = '10/09/2014'; //keys for the input data $keys = array('From', 'To', 'Text', 'Schedule Date'); //message template $message = "Hi {To} message is from {From} come get {Text}."; $messages = array(); //Loop through the input data foreach($inputs as $input) { $input = array_combine($keys, $input); //give input array our custom keys $userMessage = $message; //create a copy of the message template //Loop through the values replacing `{$key}` with $value foreach($input as $key=>$value) { $userMessage = str_replace('{'.$key.'}', $value, $userMessage); } //Do something with the message $messages[] = $userMessage; } print_r($messages); //Outputs: //Array //( // [0] => Hi Bar message is from Foo come get I like foobar. // [1] => Hi Bar2 message is from Foo2 come get Very much. //) Online demo here.
[ "mechanics.stackexchange", "0000037846.txt" ]
Q: Modern cars do not rust faster in coastal locations - Myth or truth? Someone warned me to never buy a second hand car from the coast because cars rust faster and you cannot always see which hidden parts are rusted. The expectation is that cars from the coast has a much shorter lifespan than cars from the inland. However, a sales person told us that since 2002 most car manufacturers switched to electrostatic coat painting to protect the cars against rust. He also added that most modern car's parts are made from aluminium, plastic and other materials that do not rust. For that reason he claims that it does not matter whether you buy a second hand car from the coast or from the inland as long as the car was never painted over by a panel beater and the car still has its original electrostatic paint coat. Is it true that modern cars rust equally fast at the coast and inland? A: Though each car is different, yes, they may tend to rust faster in coastal areas. This is even true for newer models. Newer models may resist corrosion (rust) better than older ones, but they are still susceptible. Anything that is prone to corrosion is going to be at a higher risk in coastal areas. Sea water gets aerosolized, which creates airborne salt content levels much higher than non-coastal areas. Rain and morning dew can leave salt water deposits on your vehicle. The higher salt content promotes corrosion. Sources - Does Living Near The Ocean Affect Your Car? Why Does a Car Rust Faster at the Seaside? - Vol.133
[ "stackoverflow", "0013711885.txt" ]
Q: AX 2009 Code Propagation with Load Balancing I'm curious how AX 2009 handles code propagation when operating in a load balanced environment. We have recently converted our AX server infrastructure from a single AOS instance to 3 AOS instances, one of which is a dedicated load balancer (effectively 2 user-facing servers). All share the same application files and database. Since then, we have had one user who has been having trouble receiving code updates made to the system. The changes generally take a few days before they can see it, and the changes don't seem to update all at once. For example, a value was added to an ENUM field, and they were not able to see it on a form where it was used (though others connected to the same instance were). Now, this user can see the field in the dropdown as expected, but when connected to one of the instances it will not flow onto a report as it should. When connected to the other instance it works fine, and for any other user connected to either instance it works properly. I'm not certain if this is related to the infrastructure changes, but it does seem odd that only one user is experiencing it. My understanding was that with this setup, code changes would propagate across the servers either immediately (due to sharing the Application Files), or at least in a reasonable amount of time (<1 day). Is this correct or have I been misinformed? A: As your cache problems seems to be per user, then go learn about AUC files. The files are store on the client computer and can be tricky to keep in sync. There are other problems as well. Start AX by a script, delete the AUC file before starting AX. There is no cache coherency between AOS instances: import an XPO on one AOS server, and it is not visible on the other. You will either have to flush the cache manually or restart the other AOS. The simplest thing is to import on each server, this is especially true for labels, as this is the only way to bring labels in sync to my knowledge.
[ "stackoverflow", "0050020552.txt" ]
Q: Chart X Axis wrong labels I have a chart and a datagridview, both of them are databound to a dictionary, for example: freqChart.Series[0].Points.DataBindXY(symCount.Keys, symCount.Values); And on the screenshot below you can see the difference in X-Axis label/key names. Datagridview shows it correctly, while chart flips char if it's punctuation char. What's the problem? How do I fix it? Screenshot (Chart and DataGridView): A: My comment was wrong; in fact this is a funny effect you get when you have a RightToLeft turned on. There are several values but this one is enough to reproduce: freqChart.RightToLeft = RightToLeft.Yes Either this is what you want, then you can turn it on for the DGV as well; or it isn't then simply turn it off.. freqChart.RightToLeft = RightToLeft.No As you can see it is a Control.Property so it will work on all controls. Also to be noted: The RightToLeft property is an ambient property, so it propagates to child controls. Why it acts so strangly I can't say, though. The docs basically talk about alignment, not punctuation. If you are interested you may want to read up on it in wikipedia
[ "electronics.stackexchange", "0000410710.txt" ]
Q: Run a 12 dc power through telephony cable I have a converter (120 AC to 12 DC) which is used for sending alert to outdoor through 30 meters telephony cable. My quistion is ( Is it harmful if someone touch the cable? the output can give up to 20 amp. A: THe 20A is just your supply which is irrelevant. What is the load? Let's see, Telephone cable which is AWG 24 which is 10 Ohms per hundred meters. If you use 4 wire as 2 + 2 then it becomes 5 Ohms/100m and then 10 both round trip. So loop resistance is 3 Ohms for 30 Meters so with a 10% tolerance on 12V or 1.2V /3 Ohms = 400mA and you have a 20A supply which has no added value unless you can adjust it higher or use a 19V laptop charger to get 12V at the other end then you have 7V drop/3 ohms to get 2.33 Amps A short circuit on 12V/3 Ohm produces 4 Amps and 48 Watts of heat which would make the wires hot. IN free air 3.5A is allowed. Enclosed only 2.1A is allowed for safe operation.
[ "stackoverflow", "0015640884.txt" ]
Q: JS: Scroll down after "unhide" div element I have a div element with lots of content inside: <div id="x" class="unhidden"> text and more divs </div> The CSS class 'unhidden' contains: display: block; When I click on a link, the element id='x' becomes class='hidden' trough javascript, which contains: display: none; The div element is now hidden. So far so good. Now I want to go back and show the full div='x' and scroll down to a certain div in div id='x'. So when I click on the back button, first the class becomes unhidden again trough javascript and after that I run this script in the same function: window.scroll(0, findPos(document.getElementById(GoTo))); GoTo is the ID of a certain div I want to scroll down to. With this function doing the scroll down: function findPos(obj) { var curtop = 0; if (obj.offsetParent) { do { curtop += obj.offsetTop; } while (obj = obj.offsetParent); return [curtop]; } } The script does find the position of where to go to, but doesn't scroll down. The scroll down script also works if it is separated from the hidden/unhidden part. But here it doesn't work, the hiding/showing part blocks something. Any solutions, or thoughts? A: I think this is due to the browser executing all of your JS code first, before it gives control back to the rendering engine – so changing the class has not actually made the element visible again at the point where your code to calculate the element position is executed (and elements that are not displayed do not have any position). If you wrap your whole window.scroll call into an anonymous function and execute that with a minimal delay using setTimeout, that should solve the problem: referenceToDivElement.className = "unhidden"; var targetElement = document.getElementById(GoTo); window.setTimeout(function() { window.scroll(0, findPos(targetElement)); }, 5);
[ "stackoverflow", "0031778038.txt" ]
Q: How to customize SQL query for entity associations in Sonata Admin edit view I have an entity 'Contact' which has a OneToMany association to another entity 'Invoice': // src/AppBundle/Entity/Contact.php /** * @var Collection * * @ORM\OneToMany(targetEntity="Invoice", mappedBy="contact", cascade={"persist", "remove"}, orphanRemoval=true) **/ private $invoices; // src/AppBundle/Entity/Invoice.php /** * @var Contacts * * @ORM\ManyToOne(targetEntity="Contact", inversedBy="invoices") * @ORM\JoinColumn(name="id_contact_fk", referencedColumnName="id_contact_pk") **/ private $contact; I then have a Sonata Admin class 'ContactAdmin' which displays this association in the edit view: // src/AppBundle/Admin/ContactAdmin.php protected function configureFormFields(FormMapper $formMapper) { $formMapper ->tab('Invoices') ->with('Invoices') ->add('invoices', 'sonata_type_collection', array( 'btn_add' => false, 'required' => false ), array( 'edit' => 'inline', 'inline' => 'table' )) ->end() ->end(); } That works fine except some contacts have hundreds of invoices going back for years. I need to display only invoices for the current year. It doesn't look like there's any way to use a dynamic value (something like YEAR(CURDATE() in mysql) in place of a join column when mapping an association in Doctrine. So it seems what I need to do is somehow override the query that Sonata Admin / Doctrine uses when the ContactAdmin edit view is being rendered. I know that the createQuery() method in a Sonata Admin class can be overridden but (correct me if I'm wrong here) this is only called for the query used to generate the list view. There is the sonata.admin.event.configure.form event that I could act on but I'm not sure if there is any way I could modify the query from that context? How can I go about this? A: After some digging I discovered that the sonata_type_collection form type accepts an undocumented parameter named 'data'. You can pass it a Collection of objects directly and it uses those.
[ "stackoverflow", "0048766655.txt" ]
Q: Eclipse Oxygen This compilation unit is not on build path of java project I have created a Kafka Streams Project using Maven Archetype: mvn archetype:generate \ -DarchetypeGroupId=org.apache.kafka \ -DarchetypeArtifactId=streams-quickstart-java \ -DarchetypeVersion=1.0.0 \ -DgroupId=streams.examples \ -DartifactId=streams.examples \ -Dversion=0.1 \ -Dpackage=myapps Compiling and running the program: > mvn clean package > mvn exec:java -Dexec.mainClass=myapps.Pipe The program works fine. However when I am editing the code and try Ctrl+Space I am getting Cannot perform operation error: This compilation unit is not on build path of java project. See the image below: A: Just run mvn eclipse:eclipse in the project directory and refresh your project in eclipse: File -> Refresh
[ "mathematica.stackexchange", "0000208732.txt" ]
Q: How to iterate through a lists of lists and delete a certain element? Say I have a list of lists such as l1 = {{a, 2}, {a, 5}, {b, 3}, {b, 9}} How would I iterate through the list and delete all the lists with the first element b so that i can get l2 = {{a,2}, {a, 5}} A: l1 = {{a, 2}, {a, 5}, {b, 3}, {b, 9}}; l2 = {{a, 2}, {a, 5}}; (*method 1*) DeleteCases[l1, {b, _}] (*method 2*) Select[l1, First@#1 =!= b &]; (*method 3*) Select[l1, FreeQ[#, b] &]; (*method 4*) Pick[l1, #1 =!= b & @@@ l1]; (*method 5*) (l1 /. {b, _} -> Sequence[]); (*method 6*) Reap[If[#[[1]] =!= b, Sow@#, Sequence[]] & /@ l1][[2, 1]]; SameQ @@ Out[-Range[6]] {{a, 2}, {a, 5}} True And a more procedural way/actually using iterators, and "deleting" the "b"s instead of picking out the not-"b"s, Block[ {list = l1, i = 0}, Do[ If[l1[[k, 1]] === b, list = Delete[list, k - i]; i++], {k, Length@l1} ]; list ] {{a, 2}, {a, 5}} A: Another way. l2 = l1 /. {b, _} -> Nothing (* {{a, 2}, {a, 5}} *}
[ "stackoverflow", "0040565455.txt" ]
Q: Adding pairs of numbers in array with reduce (javascript) Given a 2D array, I want to add the last number of the preceeding inner array to the first number of the next inner array. I managed to get up to the point where: var output= [[1,2,3],[4,5,6],[7,8,9],[1,2,3]] //this becomes... output = [3,4,6,7,9,1] (edited typo) I now would like to add the pairs up to return this array: output = [9, 11, 10] So far, this is what I have, and it returns [3,6,4,7,9,1]. I would like to see how reduced can be used for this, but also interested in how a for loop would accomplish the same thing. var output= [[1,2,3],[4,5,6],[7,8,9],[1,2,3]] output = output .reduce((newArr,currArr)=>{ newArr.push(currArr[0],currArr[currArr.length-1]) //[1,3,4,6,7,9] return newArr },[]) output.shift() output.pop() return output A: Can use index argument of reduce let output= [[1,2,3],[4,5,6],[7,8,9],[1,2,3]]; output = output .reduce((newArr, currArr, i, origArr) => { if (i > 0) { let prevArr = origArr[i - 1]; newArr.push(currArr[0] + prevArr[prevArr.length - 1]); } return newArr }, []) console.log(output)
[ "stackoverflow", "0041944014.txt" ]
Q: Convert flag into either 0xFF or 0, based on whether flag equals 1 or 0 I have a binary flag f, equal to either zero or one. If equal to one, I would like to convert to 0xFF, otherwise, to 0. Current solution is f*0xFF, but I would rather use bit twiddling to achieve this. A: How about just: (unsigned char)-f or alternately: 0xFF & -f If f is already a char, then you just need -f. This approach works because -0 == 0 and -1 == 0xFFFFF..., so the negation gets you want you want directly, perhaps with some extra high bits set if f is larger than a char (you didn't say). Remember though that compilers are smart. I tried all of the following solutions, and all compiled down to 3 instructions or less, and none had a branch (even the solution with a conditional): Conditional int remap_cond(int f) { return f ? 0xFF : 0; } Compiles to: remap_cond: test edi, edi mov eax, 255 cmove eax, edi ret So even the "obvious" conditional works well, in three instructions and a latency of 2 or 3 cycles on most modern x86 hardware, depending on cmov performance. Multiplication Your original solution of: int remap_mul(int f) { return f * 0xFF; } Actually compiles into nice code that avoids the multiplication entirely, replacing it with a shift and subtract: remap_mul: mov eax, edi sal eax, 8 sub eax, edi ret This will generally take two cycles on machines with mov-elimination, and the mov would often be removed by inlining anyway. Subtraction As corn3lius pointed out, you can do some subtraction from 0x100 and a mask, like so: int remap_shift_sub(int f) { return 0xFF & (0x100 - f); } This compiles to1: remap_shift_sub: neg edi movzx eax, dil ret So that's the best so far I think - a latency of 2 cycles on most hosts, and the movzx can often be eliminated by inlining2 - e.g., since it could use the 8-bit register in a subsequent consuming instruction. Note that the compiler has smartly eliminated both the masking operation (you could perhaps argue the movzx accounts for it), and the use of the 0x100 constant, because it understands that a simple negation does the same thing here (in particular, all the bits that differ between -f and 0x100 - f are masked away by the 0xFF & ... operation). That leads directly to the following C code: int remap_neg_mask(int f) { return -f; } which compiles down the exact same thing. You can play with all of this on godbolt. 1 Except on clang, which inserts an extra mov to get the result in eax rather than generating it there in the first place. 2 Note that by "inlining" I mean both real inlining the compiler does if you actually write this as a function, but also what happens if you just do the remapping operation directly at the place you need it without a function.
[ "astronomy.stackexchange", "0000013664.txt" ]
Q: What Are Some Good Southern Hemisphere 7x50 Binocular Targets? I've been interested in astronomy for a while but only recently purchased my first set of binoculars (7x50). I've been learning various constellations as well as spotting some other objects with the help of my planisphere. I live in the suburbs of a big Australian city, but far enough out that the light pollution isn't too bad. I've already been looking at objects like the Orion Nebula and Pleiades, but hoped some experts might be able to give me a list of objects that would be worth hunting down with my binoculars. Ideally some that would be visible now (it's Summer here), but some for other times of the year would also be fine. A: For anyone else who might be asking a similiar question, I found a great resource for this. The PDFs found at the URL below contain a good list of binocular, naked-eye and telescope targets for each month of the year in both hemispheres. http://www.skymaps.com/downloads.html A: Plaiedes - a jewel box Coal Sack - in Crucis, there's a globular cluster I recall there somewhere. Hours of fascination. Messier objects Jupiter moons Saturn's rings and moons, ? Lycrae Large and Small Magellanic Clouds - extra-galactic remnants on the southern pole of the Milky Way Just for starters. By the time you work through all these, you'll start to gain an appreciation of your own. Happy Hunting!!!
[ "stackoverflow", "0006792785.txt" ]
Q: Replace WCF default JSON serialization Is it possible to replace the default JSON serialization of WCF (I'm currently testing with the webHttp behaviour), and passing application/json as the MIME type. In particular, I don't like that by default every property is a key/value pair like: {"Key":"PropertyName", "Value":"PropertyValue"} I'm using the service only for JSON-enabled endpoints (requesting data with jQuery + WCF). A: You can use a message formatter to change the serializer used to deal with JSON. The post at https://docs.microsoft.com/en-us/archive/blogs/carlosfigueira/wcf-extensibility-message-formatters shows an example on how to change the default serializer (DataContractJsonSerializer) to another one (JSON.NET).
[ "stackoverflow", "0034859870.txt" ]
Q: Check if input control has certain type of vallidator in angular2 I have component that wraps input field. In the component i receive the Control object from @Input() inputControl: Control;. In the template i have span that shows message if input field in the component is not required. <span class="input-label-caption"> (optional) </span> and the input <input *ngIf="inputMode=='text' || inputMode=='email'" type="{{inputMode}}" [ngFormControl]="inputControl" placeholder="{{placeholder}}" class="input-text" [disabled]="inputDisabled" [ngClass]="{ 'inverted': inverted }"> How can i read form inputControl object if it contains Validators.required? I want to know if i can used it like this for example <span class="input-label-caption" *ngIf="!inputControl.validators.required" > (optional) </span> A: You can try to use this expression: <span class="input-label-caption" *ngIf="!inputControl.errors?.required" > (optional) </span> The errors attribute contains one entry per name of validator that failed. I use the Elvis operators for the errors attribute since it can be undefined if there is no validation error. Edit Following your comment, I think that you can check a "required" validator using the === operator with the Validators.required function directly. In fact a validator is simply a function and the Validators.required function is used for "required" validation. Here is the corresponding code: this.hasRequiredValidator = (this.inputControl.validator === Validators.required); In the case where the validator attribute is an array, you need to extend a bit the test to check if the Validators.required function is present in the array. Now the code in the template would be: (optional) Hope it helps you, Thierry A: I couldn't get the above to work which isn't surprising given the changes to Angular since Jan. With the latest version of Angular (2.2.0)you will need something like this in your class. get required(): boolean { var _validator: any = this.inputControl.validator && this.inputControl.validator(this.inputControl); return _validator && _validator.required; } This will also handle the case where you have multiple validators in a reactive form e.g. name: ['', [Validators.required, Validators.minLength(2)]]
[ "academia.stackexchange", "0000060787.txt" ]
Q: Concerted efforts to digitalize MS and PhD theses? Some universities digitize their masters and doctoral theses already and some of them even share them for free online. However, there are enough that are not digitized that inter-library loan remains often necessary for literature searches. Obviously this is just a matter of time until the librarians catch up with the modern era. However, government funding is often involved and could be leveraged towards progress in those instances. Has this been proposed already? Have similar mechanisms been proposed? A: Has this been proposed already? Have similar mechanisms been proposed? Yes, it was proposed, this was even implemented, partially or at a whole country level. In Russia, for example, all PhD theses' copies are centrally stored, scanned and recognized (if there wasn't already a digital copy) as a part of the degree awarding process. From 2005 the process needed a digital copy submitting, also, most of the old theses(~1.5M total) from 1951 were scanned.
[ "superuser", "0000290412.txt" ]
Q: Windows Vista, Fails to boot in Safe Mode, or load past initial Login under standard conditions. HP Pavillion DV6000 I have an HP Pavilion DV6000 laptop, with Windows Vista loaded onto it. Here is my problem (Besides still owning Vista): When I try to boot the computer in "Standard" (no debug/Safe modes), the computer will load completely to the desktop, at which point it will simply "stall", the task bar is loaded, as are the icons, the clock, the start menu (which does not open), and the background picture. However, that is as far as it will go. After that, the "loading" cursor (the spinning circle merry-go-round of 'thinking') is a constant feature. When I try to boot up into safe mode, the computer will load all drivers completely, however, after loading crcdisk.sys (The final driver my computer has), it will not activate logonui.exe/Winlogon.exe/whatever Vista calls the Welcome Screen loader. I simply receive a black screen. Here was what was happening previously: The computer would BSOD past loading netio.sys, because one program must have botched and corrupted it. After manually extracting netio.sys, tcpip.sys, etc, from a Windows Vista hotfix, I put them in place of the old files that were corrupted. However, I forgot to add the .mui files. Could this be my issue? Also, while the machine was down, I deleted a lot of programs/services I had loading at startup, to see if I could get in to Windows (Previously, under safe mode, it would load to the login screen, but stall exactly 5 seconds after first displaying the login screen.) I also deleted a few Bluetooth drivers the hard way, as they were also botching up the login. A: Some root kits and other spyware will actually prevent the computer from being started in Safe Mode. The following tools should be able to remove it for you, but you'll probably have to install the hard disk in a clean machine as a secondary drive (so the spyware can't interfere) to run a full scan on it: MalwareBytes SpyBot - Search & Destroy
[ "stackoverflow", "0005488808.txt" ]
Q: Are there any security issues with enabling CLR on SQL SERVER 2005? I am toying with the idea of enabling CLR on my SQL server, using EXEC sp_configure 'clr enabled', 1 However, I am sharing my database server with several other developers and their projects. I've heard vaguely that their might be security issues with enabling this. Does anyone know what these issues might be? Is CLR safe to use on SQL Server? A: No, SQLCLR code can’t do anything more in a database than an equivalent T-SQL code module running under the same security context. This was and currently is the most misunderstood security claim in all of SQL Server (especially 2012 onwards), which can break UI connectivity to SCCM databases, the flagship ETL deployment model SSISDB (requires CLR), because a 3rd party security tool inheriting CIS benchmarks (DBProtect primarily) which also incorrectly flags SQL Server collation coefficients via 2000 even if the server is not running 2000, falsely directing DBAs to rebuild master and forever crippling their environment and applications as case sensitive if nobody speaks up on the finding. CLR is not a security risk, it allows for flagship enhancements (post SQL Server 2012) to security in multiple regards via RDP and file system right mitigation and SSIS code management e.g. SSISDB, which is likely to impact every 90% of SQL Server shops, including HA solutions built to not rely on a single SAN. A side note regarding DBAs who are simply averse to CLR it because it can be "difficult to troubleshoot if made badly" - it is not primarily inside DBA purview to troubleshoot senior .NET developer code, if you hire bad DBAs they too can be difficult to troubleshoot (see above via collation). Further, the majority of people leveraging CLR are doing so for the flagship functions and have little or nothing to do with writing CLR code (although script tasks in SSIS leverage this to a degree), and have much more to do with SSISDB and using availability groups across SANs. DBAs who dislike this functionality should jump into a time warp and hit stasis mode for the year 2008. This is written from a full-stack BI/DBA perspective, not from a somewhat myopic sys internals vantage point. Further, Availability Groups utilize CLR, causing an error if CLR is not enabled. More information also vetted on Technet Both both Availability Groups and SSISDB are flagship features of modern SQL Server environments. Currently, by enabling CLR and deploying SSIS packages via the SSISDB, you can mitigate file system organization mismanagement and clutter, gain inherited backup maintenance plans and even TDE, and actually drastically lower the need for RDP to troubleshoot an SSIS package. Ask your DBA if he cares so much about security why Mixed Mode Authentication is set on, no SSL certs for SSMS or SSRS or Excel clients, TDE is not enabled, and lack of auditing or even logging successful and failed logins. http://www.codemag.com/article/0603031 To enable CLR simply run sp_configure 'show advanced options', 1; GO RECONFIGURE; GO sp_configure 'clr enabled', 1; GO RECONFIGURE; GO
[ "math.stackexchange", "0000758499.txt" ]
Q: How to calculated the integral of the area $C$ of $\mathbf{F}\cdot d\textbf{r}$? I'm doing a lon capa problem. It has two parts and I'm stuck on the second part. I first had to calculate the potential of the field. I did this and got it correct. Now I have to find $\textbf{F} \cdot d\textbf{r}$ but I don't know how to do this. Can someone give me a few hints? Problem: Now calculate $\textbf{F} \cdot d\textbf{r}$ where $C$ is the path of the parabola $y=x^2−6x+8$ from the point $(0,8)$ to the point $(3,−1)$. You also have $f(x,y)$ which I calculated in part one of them problem. A: The integral can often be computed by in parametric form: \begin{align} \int_{C}\vec F\cdot d\vec r = \int_{t_i}^{t_f}\vec F(x(t),y(t))\cdot\frac{d\vec r(t)}{dt}dt \end{align} Choose a parameterization for the curve $C$. A possible choice for this problem could be $\vec r(t)=(t,t^2-6t+8)\rightarrow \vec r'(t)=(1,2t-6)$. The point (0,8) corresponds to $t_i=0$ and the point (3,-1) corresponds to $t_f=3$. So writing everything in terms of $t$ we can compute the line integral. However, from the way you stated the problem, I assume you are interested in computing the line integral of a "conservative" vector field over $C$. ie. the gradient field of the scalar function you posted. In this special case the integral is independent of the path taken between the end points. Observe: \begin{align} \int_C \vec F\cdot d\vec r =\int_C \nabla f\cdot d\vec r =\int_C(f_x,f_y)\cdot(dx,dy)=\int_C f_xdx+f_ydy=\int df=f|_a^b \end{align} Where $a$ and $b$ are the endpoints you have listed and my $f$ is your $F$.
[ "stackoverflow", "0024486836.txt" ]
Q: Routing does not work in angularjs I am very new to angular js. I have implemented routing in angular js but it does not redirect me to the pages I have stated in the route.js here is the code: Route.js var sampleApp = angular.module('sampleApp', []); sampleApp.config(['$routeProvider', function($routeProvider) { $routeProvider. when('/getplaces', { templateUrl: 'getplaces.html', controller: 'ListCtrl', }). when('/getuncategorisedplaces', { templateUrl: 'list.html', controller: 'uncatCtrl' }) .otherwise ({ redirectTo: '/getplaces' }); }]); Controller.js function uncatCtrl($scope, $http) { $http.get('http://94.125.132.253:8000/getuncategorisedplaces').success(function (data) { $scope.places = data; console.log(data); } )} // get places function ListCtrl($scope, $http) { $http.get('http://94.125.132.253:8000/getplaces').success(function (data) { $scope.places = data; console.log("Successful") console.log(data); } )} HTML code includes ng view and href such as href="#getplaces" <body ng-app="sampleApp" > <div class="container"> <div class="row"> <div class="col-md-3"> <ul class="nav"> <li> <a class= "linha" href="#getplaces"> Get places </a></li> <li><a class= "linha" href="post.html"> Post a movie </a></li> <li><a class= "linha" href="#getuncategorisedplaces">List of uncategorised places </a></li> </ul> </div> <div class="col-md-9"> <div ng-view></div> </div> </div> A: Check that you have both scripts included (angular and ngroute) <script src='angular.js'> <script src='angular-route.js'> Then check that you are including that module in your app: var sampleApp = angular.module('sampleApp', ['ngRoute']); As of Angular 1.2.0, angular-route is a separate module refer to the angular documentation: https://docs.angularjs.org/api/ngRoute
[ "stackoverflow", "0051151707.txt" ]
Q: Stripe-Elixir How to get "payment source" I am using this package to incorporate Stripe into a phoenix app: https://github.com/sikanhe/stripe-elixir I am trying to create a customer that subscribes to a plan. defmodule StripeTestWeb.PaymentController do use StripeTestWeb, :controller use Stripe.API def index(conn, %{"stripeEmail" => email} = _params) do {:ok, customer_data} = Stripe.Customer.create(%{email: email}) Stripe.Subscription.create(%{ customer: customer_data["id"], items: [%{plan: "plan_D9JehUOiyPGtgp"}] }) render(conn, "index.html") end end The customer is created but the request returns an error when trying to create the subscription. The error is: { "error": { "code": "resource_missing", "doc_url": "https://stripe.com/docs/error-codes/resource-missing", "message": "This customer has no attached payment source", "type": "invalid_request_error" } } I don't know what the API expects me to send as "payment source" nor am I clear if this is supposed to be sent when creating the customer or when creating the subscription. I am using the JavaScript embedded code to create the payment pop up: <form action="payment" method="POST"> <input type="hidden" name="_csrf_token" value="<%= Plug.CSRFProtection.get_csrf_token()%>"> <script src="https://checkout.stripe.com/checkout.js" class="stripe-button" data-key="pk_test_2vzqy4IW9zHAYyKSjDNZkd2l" data-amount="14900" data-name="Demo Site" data-description="Subscription $149" data-locale="auto"> </script> </form> A: I am not familiar with Stripe Elixir but you can pass the source when creating a customer on Stripe, so try passing that with your create call. defmodule StripeTestWeb.PaymentController do use StripeTestWeb, :controller use Stripe.API def index(conn, %{"stripeEmail" => email, "stripeToken" => stripe_token} = _params) do {:ok, customer_data} = Stripe.Customer.create(%{email: email, source: stripe_token}) Stripe.Subscription.create(%{ customer: customer_data["id"], items: [%{plan: "plan_D9JehUOiyPGtgp"}] }) render(conn, "index.html") end end
[ "stackoverflow", "0005531870.txt" ]
Q: HTML + IE6 + IE7 + IE8 + IE9, unclickable div element I have <div>Some text</div>, and i want to make it unclickable (i want elements that under that div to be selected instead this div), unselectable (so user couldn't select text inside this div), but visible... is it possible for IE6 + IE7 + IE8 + IE9? Update I just want to render some text on top of picture, but i want picture to be the only one who can catch mouse events.. so i want text to be rendered, but not involved in mouse events at all.. A: Try overlaying the image and text with another div (named capturebox in my example) and capture mouse events on that. In order for capturebox to really capture events in IE, it must have a background color set. To make it transparent, I give it an opacity of 0: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script> function captureclick(event) { alert('capurebox'); } </script> <style> .imgbox { position: absolute; top: 0px; left: 0px; } .imgbox img { width: 200px; height: 200px; } .imgbox p { cursor: default; position: absolute; top: 50px; left: 50px; } .capturebox { filter: alpha(opacity=0); background-color: white; height: 200px; width: 200px; position: absolute; left: 0px; right: 0px; } </style> </head> <body> <div class="imgbox"> <img src="yourimage.jpg"/> <p>Some text</p> <div class="capturebox" onclick="captureclick(event)"></div> </div> </body> </html> A: You can disable your text by setting the unselectable attribute <p unselectable="on"> and setting the CSS property -moz-user-select: none; Assuming your text is inside a <p> you can trigger a click to the image when p is clicked on. $("p").click(function() { $(this).parent().find('img').trigger('click') }); $('img').click(function() { alert('image clicked'); }) Check working example at http://jsfiddle.net/pavgY/1/
[ "stackoverflow", "0023580247.txt" ]
Q: RangeValidator doesn't validate on AutoPostBack My problem is that the range validator doesn't validate when Text_changed event occur on AutoPostBack. my code is the following : public string s; protected void Page_Load(object sender, EventArgs e) {... TextBox textbox = new TextBox(); textbox.TextChanged += textbox_TextChanged; textbox.ID = p.IDProduct.ToString(); textbox.AutoPostBack = true; RangeValidator rangev = new RangeValidator(); rangev.ControlToValidate = p.IDProduct.ToString(); rangev.Type = ValidationDataType.Integer; rangev.MinimumValue = "0"; rangev.MaximumValue = "100"; rangev.ErrorMessage = "*"; ...} void textbox_TextChanged(object sender, EventArgs e) { s=((TextBox)sender).Text } The variable "s" gets some values that are not allowed, like text("asdf") or numbers that are not in range 1-100 ("207" for example). The question is , how to make the range validator work on autopostback ? if i remove autopostback , the rangevalidator works. But i don't need to remove it. I want it to work with autopostback because i don't want to refresh the page everytime i make a textchange. A: i discovered the answer myself. This is the answer : void textbox_TextChanged(object sender, EventArgs e) { Page.Validate() if(Page.IsValid) { s=((TextBox)sender).Text } }
[ "stackoverflow", "0043885496.txt" ]
Q: Separate component for Loader :Error: Uncaught (in promise): false I have create a loading component to show and hide loader. it work fine on the login page and home page,bus as soon as i call it again from another page it gives the error I want to create a separate component for loading and not repeat the code in every page ERROR Error: Uncaught (in promise): false Below is the code of the loading.modal.ts import { Component } from '@angular/core'; import { LoadingController } from 'ionic-angular'; /** * Generated class for the LoadingModal component. * * See https://angular.io/docs/ts/latest/api/core/index/ComponentMetadata-class.html * for more info on Angular Components. */ @Component({ selector: 'loading-modal', templateUrl: 'loading-modal.html', providers:[] }) export class LoadingModal { text: string; loader: any; constructor( public loadingCtrl: LoadingController ) { this.text = 'Hello World'; this.loader=this.loadingCtrl.create({ content: 'Please wait...' }); } showModal() { this.loader.present(); } hideModal() { //alert("hide modal"); this.loader.dismiss().catch(() => {}); } } From the home page when the next page is pushed then in the constructor of the new page i try to show the loader again /** * Generated class for the ProductCatalog page. * * See http://ionicframework.com/docs/components/#navigation for more info * on Ionic pages and navigation. */ @IonicPage() @Component({ selector: 'page-product-catalog', templateUrl: 'product-catalog.html', }) export class ProductCatalog { public currentCatId:any; public productArray=[]; public imageBaseUrl:string; constructor(public navCtrl: NavController, public navParams: NavParams, public prdServ: ProductService,public appService:AppService, public loaderService: LoadingModal) { this.imageBaseUrl=appService.ThumbNailUrl this.currentCatId=navParams.get("catId"); loaderService.showModal(); prdServ.getProductsforCategory(this.currentCatId).subscribe(data => { this.productArray=data.items; loaderService.hideModal(); }); } loadDescription(product){ var p=product; this.navCtrl.push(ProductDescription,{product:p}); } ionViewDidLoad() { } } Below is the ionic Info: Cordova CLI: 7.0.0 Ionic Framework Version: 3.0.1 Ionic CLI Version: 2.2.3 Ionic App Lib Version: 2.2.1 Ionic App Scripts Version: 1.3.0 ios-deploy version: Not installed ios-sim version: Not installed OS: Linux 4.4 Node Version: v7.4.0 Xcode version: Not installed I have read a lot of threads where people have the same issue but not able to figure out how to solve this. Thanks! A: So taking clue from the comment as per the Doc Note that after the component is dismissed, it will not be usable anymore and another one must be created. This can be avoided by wrapping the creation and presentation of the component in a reusable function as shown in the usage section below. Loading component once dismissed cannot be used again. i.e we have to create a new loader everytime we wish to use it. So in my loading.modal.ts i moved the create method to the showModal method. So now everytime showModal is called a new loader is created and is available for use. export class LoadingModal { text: string; loader: any; constructor( public loadingCtrl: LoadingController ) { this.text = 'Hello World'; } showModal() { this.loader=this.loadingCtrl.create({ content: 'Please wait...' }); this.loader.present(); } hideModal() { //alert("hide modal"); this.loader.dismiss().catch(() => {}); } }
[ "aviation.stackexchange", "0000077563.txt" ]
Q: Shall We Consider Reversers in performance Calculations? Thrust reversers are featured to help slow down the plane after touchdown. Moving the thrust levers aft activates the translating cowl to open, closing the blocker doors. This action stops the fan airflow from going aft and redirects it through the cascade vanes, which direct the airflow forward to slow the aircraft. My question is Shall We Consider Reversers in performance Calculations ? A: For airplanes certified under Part 23, both takeoff (AMC 23.55b) and landing (AMC 23.75f) performance can take credit for thrust reverser (T/R) if it's shown to be reliable and safe. As detailed in AC 23-8C, much extra work would be required to take credit for T/R for multi-engine airplanes: For accelerate-stop distance: demonstration of full T/R with one-engine-inoperative and in a 10kt crosswind and on wet runway for adequate lateral controllability is required. For landing distance: the landing distance used must be that with one-engine-inoperative; differential braking needed to maintain lateral control for this situation may negate most, if not all, of the advantage of a single T/R. For airplanes certified under Part 25, only takeoff on wet runway may take credit for thrust reverser (25.109f). Similar situation for landing distance as with Part 23, 25.125c)3) allows credit for T/R, but only for that with one-engine-inoperative; therefore, the same problem as discussed before applies.
[ "stackoverflow", "0017161646.txt" ]
Q: Own jQuery plugin only working on first selector I've had a go at writing my first plugin. It is a simple jQuery plugin that reorders the DOM based on screen width. If the plugin is used on a single selector, like $("#box3").domorder(); it works as expected. However, if multiple selectors are used to call the function, or the function is called multiple times, the function only works once, on the first selector it comes to. I have the each(function(){}) iterating over each selector, but I'm obviously missing something. jsFiddle (function($) { "use strict"; $.fn.domorder = function(options) { var settings = { breakpoint : 960, targetContainer : $(this).parent(), targetPosition : "start" }; if (options) { $.extend(settings, options); } return this.each(function(i, el) { /* remember selector's original order position */ var originalLocation = {}; if ($(el).prev().length) { /* not originally first child */ originalLocation.prev = $(el).prev()[0]; } else { /* originally a first child */ originalLocation.parent = $(el).parent()[0]; } var initiatedomorder = function() { var winW = $(window).width(); if (winW < settings.breakpoint && !$("body").hasClass("domorder-reordered")) { /* dom the order of the item */ if (settings.targetPosition === "start") { $(el).prependTo(settings.targetContainer[0]); } else { $(el).appendTo(settings.targetContainer[0]); } $("body").addClass("domorder-reordered"); } else if (winW >= settings.breakpoint && $("body").hasClass("domorder-reordered")) { /* return the reordered item back into the orignal flow */ if (originalLocation.parent) { /* element was a first child */ $(originalLocation.parent).prepend(el); } else { /* element was not a first child */ /* add a line break to preserve inline-block spacing */ $(originalLocation.prev).after(el).after("\n"); } $("body").removeClass("domorder-reordered"); } }; initiatedomorder(); $(window).resize(function() { initiatedomorder(); }); }); }; }(jQuery)); A: $("body").addClass("domorder-reordered"); cause the problem since only the first iteration will do the ordering. maybe you should change the $("body") to something like $(el.parentNode). check this jsfiddle
[ "tex.stackexchange", "0000223081.txt" ]
Q: arabxetex and footnote I've had some problems with ^s when using arabxetex in footnotes. Transliteration and conversion to Arabic script work fine in the main text, but in footnotes they do not. All other letters seem to work fine. \documentclass{article} \usepackage{fontspec} \defaultfontfeatures{Ligatures=TeX} \setmainfont[Numbers=OldStyle]{Brill} \newfontfamily\arabicfont[Script=Arabic,Scale=1.3]{Scheherazade} \usepackage{arabxetex} \begin{document} Here it works: \textarab[trans]{^s} Here it doesn't: \footnote{\textarab[trans]{^s}} \end{document} A: The \textarab command changes category codes so it can't be used in the argument to another command. There's a way out by using \scantokens. A quick redefinition can be obtained with the regexpatch command. \documentclass{article} \usepackage{fontspec} \usepackage{arabxetex} \usepackage{regexpatch} \defaultfontfeatures{Ligatures=TeX} \setmainfont{Brill} \newfontfamily\arabicfont[Script=Arabic,Scale=1.3]{Scheherazade} \makeatletter \xpatchcmd*{\text@arab}{#2}{\scantokens{#2\noexpand}}{}{} \makeatother \setlength{\textheight}{2cm} % just to have a smaller picture \begin{document} Here it works: \textarab[trans]{^s}X\textarab{^s}X Here too\footnote{\textarab[trans]{^s}X\textarab{^s}X} \end{document} The X's I added are just to ensure that no spurious space creeps in. Here's the full redefinition in case you can't use regexpatch. \documentclass{article} \usepackage{fontspec} \usepackage{arabxetex} \defaultfontfeatures{Ligatures=TeX} \setmainfont{Brill} \newfontfamily\arabicfont[Script=Arabic,Scale=1.3]{Scheherazade} \makeatletter \renewcommand\text@arab[2][\ax@mode]{% \edef\@tempa{#1}% \def\ax@lang{arab}% \ax@ismode@defined{\@tempa}% \ifax@mode@defined \ifx\@tempa\ax@mode@trans {\ax@trans@style\addfontfeature{Mapping=arabtex-trans-\ax@trans@convention}\scantokens{#2\noexpand}}% \else \ifx\@tempa\ax@mode@utf \RL{\arabicfont\utf@fontfeature\scantokens{#2\noexpand}}% \else \RL{\arabicfont\addfontfeature{Mapping=arabtex-\ax@font@allah-\@tempa}\scantokens{#2\noexpand}}% \fi \fi \else \PackageWarning{arabxetex}{Mode \@tempa\ not defined, defaulting to \@ax@mode}% \RL{\arabicfont\addfontfeature{Mapping=arabtex-\ax@font@allah-\ax@mode}\scantokens{#2\noexpand}}% \fi \egroup} \makeatother \setlength{\textheight}{2cm} % just to have a smaller picture \begin{document} Here it works: \textarab[trans]{^s}X\textarab{^s}X Here too\footnote{\textarab[trans]{^s}X\textarab{^s}X} \end{document}
[ "stackoverflow", "0005533122.txt" ]
Q: Ruby extension link error I keep getting this fairly obscure link error whenever I try to link my Ruby extension: /usr/bin/ld: Mg.o: relocation R_X86_64_PC32 against undefined symbol `init_window_class_under' can not be used when making a shared object; recompile with -fPIC /usr/bin/ld: final link failed: Bad value I couldn't find anything on this. I experimented for a while and it linked fine when I removed the header files, so I moved on without them (Yes, very bad idea). Turns out I need them, now. So, what is this error exactly, and how do I eliminate it? Update: After clearing everything, I started getting these warnings: warning: ‘init_window_class_under’ used but never defined warning: ‘init_display_mode_class_under’ used but never defined These also appeared when I first encountered the problem. I'm not exactly sure about what they mean. A: Your updated error is telling you that you're referencing init_window_class_under and init_display_mode_class_under somewhere but they are not defined. Those functions are actually defined in Window.c but they're declared static in both the source file and header file. Remove the static linkage modifiers from the functions in Window.c and declare them as extern in Window.h. Looks like you're making the same mistake in Display.c and everything in the x11 subdirectory. Anything declared as static has file scope and is not visible outside the file itself. Your original error: undefined symbol `init_window_class_under' occurs because all the functions in Window.c (and init_window_class_under in particular) are static and static functions do not result in any symbols for the linker to find. Only entities with external linkage result in symbols in the object files.
[ "stackoverflow", "0056423773.txt" ]
Q: NiFi: is there a way to execute line by line python code before we put in executescript? i am planning to write python code in executescript processor. As this is my first time, i am finding difficult to start. basically, i want to read flowfile (csv) and do some manipulation and write it to flowfile. is there a way where we can write the code beforehand, say suppose jupyter and then replicate the same in the processor? also, is there any syntax documentation for writing the code? EXECUTESTREAMCOMMAND: import org.apache.commons.io.IOUtils import java.io import csv # Get flowFile Session flowFile = session.get() # Open data.json file and parse json values readFile = csv.reader(sys.stdin) for row in readFile: new_value = row[0] if (flowFile != None): flowFile = session.putAttribute(flowFile, "from_python_string", "python string example") flowFile = session.putAttribute(flowFile, "from_python_number", str(new_value)) session.transfer(flowFile, REL_SUCCESS) session.commit() Command Arguments: C:\Users\Desktop\samp1.py Command Path: C:\Users\AppData\Local\Programs\Python\Python37-32\python when i execute it, it throws error on the import statement saying no module found. tia A: Matt Burgess wrote a script tester tool which can accept a Jython script and test it. Not quite the interactive environment you're looking for, but probably as close as exists out of the box. The code you write when using ExecuteScript and ExecuteStreamCommand will be very different; the core logic may be the same, but the way your code accesses and generates flowfile attributes and content will differ because when run outside of the NiFi runtime, Python has no awareness of the NiFi-specific features. See this answer for more details on how to write for ExecuteStreamCommand and this answer for ExecuteScript.
[ "stackoverflow", "0039332064.txt" ]
Q: Managing Jira issues at Jenkins I am using Jenkins JIRA plugin. When the job is done, I am creating new Jira version and then moving Resolved, Closed, Done jiras to this new version. But the problem is only Resolved and Done jiras are moved. The Closed one stays at old version. Anyone knows why? A: I think this because of closed jira tickets cannot be updated/moved.you can make them editable through the workflow. for more information you can follow this link
[ "stackoverflow", "0047725513.txt" ]
Q: How can I write logical Column expression with AND and OR in SparkR? I need to add column to SparkR (spark version 2.1.1) dataset based on some logical criteria on several other columns. But obvious solution (using && or ||) do not work, I get "invalid 'x' type in 'x && y'" error. For example, using built-in mtcars dataset: > dcars = as.DataFrame(mtcars) > dcars$cool_enough <- dcars$cyl >= 6 && dcars$hp >= 180 Error in dcars$cyl >= 6 && dcars$hp >= 180 : invalid 'x' type in 'x && y' How can I do that? A: Why &&? Simple & works OK: sparkR.version() # "2.1.1" dcars$cool_enough <- dcars$cyl >= 6 & dcars$hp >= 170 # changed 180 to 170 for demonstration purposes head(dcars) Result: mpg cyl disp hp drat wt qsec vs am gear carb cool_enough 1 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 FALSE 2 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 FALSE 3 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 FALSE 4 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1 FALSE 5 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2 TRUE 6 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1 FALSE Alternatively, this gives the same result: dcars <- withColumn(dcars,"cool_enough", dcars$cyl >= 6 & dcars$hp >= 170)
[ "matheducators.stackexchange", "0000018552.txt" ]
Q: What is a good place for teachers to share self-created content? I am a high school mathematics teacher and I regularly create problems and their solutions for my students. It has always lingered in my mind that this content can also benefit others. What would be a good place for me to share it? Hosting own website would just be an island with no visitors. I believe that I ideally need a place with a regular stream of problem solving visitors, some of whom could then benefit from my content as well. A: What is the medium of the content? If they are videos, then YouTube would probably be first option but if they are, say, pdfs, then you might have to make a blog and then upload to that there. It still might feel like an island at first but it will gain traffic from your students and then other people who find it in search results. There are also problem-solving forums which one could join, but the rules of posting content would need to be read beforehand.
[ "math.stackexchange", "0000354751.txt" ]
Q: Convexity of product of elements from two convex set Given two convex set $X\subseteq \mathbb{R}^N$,$Y\subseteq \mathbb{R}^{N\times N}$ Given a $x\in X$, is the set $\{z|z=yx,\forall y \in Y\}$ convex? If no, by adding what can force it to be convex? A: The current and original edition of your question seems to asking for completely different thing. Do you want to ask whether the set $YX = \{ yx : y \in Y, x \in X \}$ is convex or not? In any event, for fixed $x$, the set $Yx = \{ yx : y \in Y\}$ is convex. For any $z_1, z_2 \in Yx, \lambda \in [0,1]$, pick $y_1, y_2 \in Y$ s.t. $z_1 = y_1 x, z_2 = y_2 x$. $$\begin{align}Y \text{ convex } &\implies y = \lambda y_1 + (1-\lambda) y_2 \in Y\\ &\implies \lambda z_1 + (1-\lambda) z_2 = (\lambda y_1 + (1-\lambda) y_2) x = y x \in Yx\end{align}$$ In contrast, the set $YX$ need not be convex. For a counter example, conside the case $$Y = \left\{ \begin{pmatrix}1&p\\0&1\end{pmatrix} : p \in \mathbb{R} \right\} \quad\text{ and }\quad X = \left\{ \begin{pmatrix}1\\q\end{pmatrix} : q \in \mathbb{R} \right\} $$ It is then clear $$YX = \left\{ \begin{pmatrix}1 + pq\\q\end{pmatrix} : p, q \in \mathbb{R} \right \} = \mathbb{R}^{2} \setminus \left\{ \begin{pmatrix}r\\0\end{pmatrix} : r \in \mathbb{R}, r \ne 1 \right \} $$ is not convex.
[ "stackoverflow", "0008758412.txt" ]
Q: Android Process Lifecycle Details The main activity in my app sometimes calls startActivityForResult, expecting a result that will tell it (the main activity) what information to display next. Looking at the documentation for the process lifecycle, it appears that while the selection activity is active, the main activity is considered a "background" activity and could possibly be killed. So what happens when the selection activity completes? I see that my activity will be re-created and onCreate is called with the SaveInstance Bundle, but then what? Is onActivityResult then called just as if my main activity had never exited and been re-created? Also, is there any way to force this behavior in a testing environment, since it should otherwise be a very rare occurrence? A: Hint: log statements The paused state as described in docs is: If an activity has lost focus but is still visible (that is, a new non-full-sized or transparent activity has focus on top of your activity), it is paused. A paused activity is completely alive (it maintains all state and member information and remains attached to the window manager), but can be killed by the system in extreme low memory situations. That means, under normal circumstances , your main activity should just transfer the control to onActivityResult() when the selection activity completes. However, docs also state that: A background activity (an activity that is not visible to the user and has been paused) is no longer critical, so the system may safely kill its process to reclaim memory for other foreground or visible processes. If its process needs to be killed, when the user navigates back to the activity (making it visible on the screen again), its onCreate(Bundle) method will be called with the savedInstanceState it had previously supplied in onSaveInstanceState(Bundle) so that it can restart itself in the same state as the user last left it. In such cases, the main activity can be redrawn. One important point to note is that the docs have never mentioned onActivityResult() as one of their lifecycle methods here So, it might also be the case where android system treats a sub activity and parent activity (read startActivityforResult() and onActivityResult()) in the same manner as it treats an activity - dialog as stated here: A visible activity (an activity that is visible to the user but not in the foreground, such as one sitting behind a foreground dialog) is considered extremely important and will not be killed unless that is required to keep the foreground activity running.
[ "stackoverflow", "0047402461.txt" ]
Q: Template for setting branch policies for repos We are in the process of migrating all our repositories from Github to VSTS finally and getting our automated build and deployment process setup as well as a new working flow. While setting up our repositories we had to go through each one individually and configure the branch policies. It got me thinking is there not a way to create some sort of branch policy template that can be reused for your other repos or new repos? I couldn't find anything in the settings that indicated otherwise but I've been having a hard time sifting through all the ways you can customize VSTS that I'm sure I could have missed it. A: For now, there is no way bulk set branch policies for branches and repositories. I posted an user voice Have branch police template to store the branch policies usually set for most branches, you can vote and follow up. And there is also another user voice Share single branch policy by multiple branches which suggest the similar functions to set branch policies for multiple branches, you can also vote and follow up.
[ "stackoverflow", "0043035417.txt" ]
Q: parsing and display xml data in asp.net core Im still working on my first asp.net core project and now I want to display "a qoute of the day". I have the qoutes in a xml file stored in a folder called File under wwwroot. Im planning on my making this a View Component. Im used to working with web forms so it seems like Im spending alot of time on small issues, but I guess its the only way to learn. I've created a folder named Custom where I plan to hold all my custom classes. the QuoteController.cs is located in the Controllers folder. So yeah, I think I know how to crate the View Component. "I think" is an important factor here. Im also used to using XmlDocument, so Im trying my best to get XmlReader to work. But any hint or tips would be highly appreciated. This is what I got so far. QuoteController.cs public class QuoteController : Controller { public Custom.Quote Index() { Custom.Quote result = new Custom.Quote(); XmlReader rdr = XmlReader.Create(@"\File\qoutes.xml"); Random rnd = new Random(DateTime.Now.Millisecond); int tmp = rdr.AttributeCount; int count = rnd.Next(0, tmp); int i = 0; while (rdr.Read()) { if (count.Equals(i)) { result = new Custom.Quote(rdr.GetAttribute("q"), rdr.GetAttribute("author")); break; } i++; } rdr.Dispose(); rdr = null; rnd = null; return result; } } I guess the next step will be to add some visuals, but I cant imagine that my code actully works. Does anybody know how to easily parse through and xml file i CORE? Should I go for async? I guess it doesnt matter, but the xml file is formated like: <quotes> <q>Be Strong</b> <author>Stein The Ruler</author> </quotes> Again, I will be very happy if you take the time to look at this :) Thank you! A: My way to implement this: 1)convert the xmldocument to look like this <quotes> <quote Content="Be Strong" Author="Stein..."/> </quotes> 2) Fix the Custom.Quote object to contain these 2 (public getters, setters string) fields: Content and Author, and then,3) use this code to turn the xml to a list: XDocument quotesDoc = XDocument.Parse('your path'); List<Custom.Quote> quotes = quotesDoc.Root .Elements("quote") .Select(x => new Speaker { Content= (string)x.Attribute("Content"), Author = (string)x.Attribute("Author") }) .ToList<Custom.Quote>(); Hope this helps!
[ "stackoverflow", "0042064809.txt" ]
Q: Implement Jsignature within vuejs component I'm new to Vue and trying to implement Jsignature within a 'custom' Vuejs component. My solution is based on: https://vuejs.org/v2/examples/select2.html It should be straight forward however I don't get it working, the solution I got so far results in the following error: 'Jsignature' is defined but never used import Jsignature from '../../lib/jsignature The component containing the signature. <template> <div> <app-signature></app-signature> </div> </template> <script> import Signature from './signature/Signature.vue' export default { components: { appSignature: Signature } } </script> The signature component. <template> <div id="signaturecanvas"></div> </template> <script> import Jsignature from '../../lib/jsignature' export default { data () { return { signature: '' } }, methods: { initial () { var element = ('#signaturecanvas') element.Jsignature.jSignature() } }, created () { this.initial() } } </script> <style></style> A: Instead of importing JQuery and JSignature, I made the choice to use signature pad. https://github.com/szimek/signature_pad This 'plug-in' is in native javascript/html5 which makes my application less constraint to external libraries like JQuery.
[ "stackoverflow", "0008895917.txt" ]
Q: server for testing I'm given some nasty task in concurrent programming. I need to continuously read data from source address then upload the data via HTTP protocol to the target address and I do that multi-threaded. How can i test it? Is there some site i can freely connect to and read to them? Or how can i do it (preferred easily) with my own computer? I heard the words(Apache server something..) Thank u (in advance for your kind help). Oh and I'm doing it as a Java console application. I will be happy for a direction where to read about that too. A: What you heard about is Apache Tomcat, an open source Java web server; it's very easy to set up, just follow the instructions on the site; a similar alternative is Jetty. Of course what you actually do with them once they are running it's all up to you.
[ "stackoverflow", "0021439586.txt" ]
Q: Cannot test RSpec due to namespace clash? I have a User model in my Rails application and I have a UserQueue model as well. User has_many UserQueues and UserQueue belongs_to User. Here is the problem. When I try to test UserQueue and try to create one with let(:user) { FactoryGirl.create(:user) } before { @queue = user.user_queues.create(queue_privacy_id: 1) } I get the following error. NameError: uninitialized constant User::user_queue What I understand from this is RSpec expects the UserQueue to be in the namespace of User(ie User::UserQueue). However that is not the case in my app. And I can't name the model Queue since it is reserved. Is there a way to tell RSpec that the model has no namespace? Here are my models. class User < ActiveRecord::Base attr_protected has_many :user_queues, :class_name => "user_queue", :foreign_key => "user_id" def name "#{self.first_name} #{self.last_name}" end end class UserQueue < ActiveRecord::Base attr_accessible :queue_privacy_id, :user_id belongs_to :user, :class_name => "User", :foreign_key => "user_id" end A: I do not have the rep to comment, but was going to ask you to post your factories as well. Some other ideas: Take a look at how you can handle assocations with FactoryGirl. I'm assuming you are not on Rails 4 because of: attr_accessible :queue_privacy_id, :user_id
[ "stackoverflow", "0001219338.txt" ]
Q: how to query restful rails app with curl? here's my problem.. resource: user method: create I call curl like this: curl -X POST -H 'Content-type: text/xml' -d '<xml><login>john</login><password>123456</password></xml>' http://0.0.0.0:3000/users but the params hash in rails look like this: {"xml"=> {"login"=>"luca", "password"=>"123456"}} I want it to look like this: {"login"=>"luca", "password"=>"123456"} I can get it to be like that if I pass the parameters on the url (...?login=luca&pas....), but that's not good... any idea? A: curl -X POST -d 'login=john&password=123456' http://0.0.0.0:3000/users See also: Stack Overflow: How do I make a POST request with curl
[ "stackoverflow", "0035282617.txt" ]
Q: AutoIt Firefox _FFClick doesn't work on button? (FF.au3) Using the firefox plugin ("ff-au3") for AutoIt, how do I click a button? Here is the HTML of the item I'd like to click: <input accesskey="s" class="aui-button" id="login-form-submit" name="login" title="Press Alt+s to submit this form" type="submit" value="Log In"> And here is the code snippet to click the button: ;Click the "Log In" button, id is "login-form-submit" _FFClick("login-form-submit", "id") At this point, my script is already connected to firefox, already on the page I need, and everything else works (except for this click part!) Here is the error I get back: _FFClick ==> No match: $sElement: FFau3.WCD.getElementById('login-form-submit') Also, this works when I manually run it on the page using a javascript console: document.getElementById("login-form-submit") And here is the API for the plugin: http://english.documentation.ff-au3.thorsten-willert.de/ff_functions/_FFClick.php Anyone see anything I'm doing wrong? Versions: Firefox 44.0.1 AutoIt v3.3.14.2 FF V0.6.0.1b-15.au3 (Firefox plugin) MozRepl v.1.1.2 SciTE-Lite v. 3.5.4 A: Well this didn't get much traffic but I found the solution! Pretty simple... I disconnected from firefox before executing the click! When using firefox, you first need to open the firefox exe with the "Run" command, then you need to connect to firefox using the "_FFConnect" command. Next you can start clicking elements. Once you're done, disconnect from firefox using the "ProcessClose" command. The problem I was running into was I connected to firefox, then disconnected immediately, then I tried clicking. So, I made sure I disconnected after I did the clicking... Working solution: myScript.au3 (See the "LogIn" function at the bottom) #include <Constants.au3> #include <MsgBoxConstants.au3> #include <File.au3> #include <EventLog.au3> #include <FF V0.6.0.1b-15.au3> ;FireFox OpenLog() OpenFirefox() ConnectToFirefox() LogIn() ; //////////////////////////////////////////////////// ; Configure the Log ; //////////////////////////////////////////////////// Func OpenLog() Global $log = FileOpen("K:\Log.txt", 2) ; Check if file opened for reading OK If $log == -1 Then FileWrite($log,"[ERROR] Could not open log file." & @CRLF) MsgBox(0, "Error", "Unable to open log file.", [ timeout = 0]) Exit Else FileWrite($log,"[INFO] Opened log file successfully." & @CRLF) EndIf EndFunc ; //////////////////////////////////////////////////// ; Open Firefox ; //////////////////////////////////////////////////// Func OpenFirefox() ;Run Firefox in Maximized Global $ffPid = Run("C:\Program Files (x86)\Mozilla Firefox\firefox.exe","",@SW_MAXIMIZE) ; Check if firefox was opened OK If @error <> 0 Then FileWrite($log,"[ERROR] Could not open firefox." & @CRLF) MsgBox(0, "Error", "Could not open firefox.", [ timeout = 0]) Exit Else FileWrite($log,"[INFO] Firefox opened successfully." & @CRLF) EndIf ;Wait 10 seconds for Firefox to open $result = WinWait("[CLASS:MozillaWindowClass]","",10) ; Check if file opened for reading OK If $result == 0 Then FileWrite($log,"[ERROR] Unable to open firefox class." & @CRLF) MsgBox(0, "Error", "Unable to open firefox class.", [ timeout = 0]) Exit Else FileWrite($log,"[INFO] Opened firefox class successfully." & @CRLF) EndIf ;Wait for 2 seconds after opening Sleep(2000) EndFunc ; //////////////////////////////////////////////////// ; Connect To Firefox ; //////////////////////////////////////////////////// Func ConnectToFirefox() ; trying to connect to a running FireFox with MozRepl on If _FFConnect(Default, Default, 3000) Then FileWrite($log,"[INFO] Connected to Firefox." & @CRLF) Else FileWrite($log,"[ERROR] Can't connect to FireFox!" & @CRLF) MsgBox(64, "", "Can't connect to FireFox!") EndIf ;Wait for 2 seconds after opening Sleep(2000) EndFunc ; //////////////////////////////////////////////////// ; Log into page ; //////////////////////////////////////////////////// Func LogIn() ;Load Login Page _FFOpenURL("http://localhost/login.jsp") Sleep(2000) If @error <> 0 Then FileWrite($log,"[ERROR] Could not open URL." & @CRLF) MsgBox(0, "Error", "Could not open URL.", [ timeout = 0]) Exit Else FileWrite($log,"[INFO] Opened URL successfully." & @CRLF) EndIf Sleep(2000) ;Click the "Log In" button, id is "login-form-submit" ;<input accesskey="s" class="aui-button" id="login-form-submit" name="login" title="Press Alt+s to submit this form" type="submit" value="Log In"> _FFClick("login-form-submit", "id") If @error <> 0 Then FileWrite($log,"[ERROR] Could not click login button." & @CRLF) MsgBox(0, "Error", "Could not click login button:", [ timeout = 0]) Exit Else FileWrite($log,"[INFO] Found and clicked login button successfully." & @CRLF) EndIf EndFunc
[ "ethereum.stackexchange", "0000029607.txt" ]
Q: Send Custom ERC20 Tokens from one Address to another How to send custom ERC20 tokens from one wallet to another, if i want to send EBTC/ECASH custom ERC20 tokens. I wrote a method that can send the ether from one account to another, how could i do the same for non ether transactions? public static void sendCustomToken(String privateKey,String toAccount, double amount) throws Exception{ Web3j web3 = Web3j.build(new HttpService("http://localhost:8180/")); BigInteger key = new BigInteger(privateKey,16); ECKeyPair ecKeyPair = ECKeyPair.create(key.toByteArray()); Credentials credentials = Credentials.create(ecKeyPair); TransactionReceipt transactionReceipt = Transfer.sendFundsAsync( web3, credentials, toAccount, BigDecimal.valueOf(amount), Convert.Unit.ETHER).get(); System.out.println("Transaction Hash:"+transactionReceipt.getTransactionHash()); } Custom Token: eBTC Contract Address: 0x2fd41f516fac94ed08e156f489f56ca3a80b04d0 Token Decimals: 8 Any help or pointers? A: I assume you are using Web3j and a deployed smart contract implementing ERC20 interface, where transfer method looks like this: function transfer(address _to, uint256 _value) public returns (bool success) { require(balances[msg.sender] >= _value && _value > 0); balances[msg.sender] -= _value; balances[_to] += _value; return true; } You can use web3j wrapper for your contract to call contract methods on a blockahain. Suppose your Contract filname is MyContract.sol, then you'll need solc compiler and web3j tool and do the following in your console: $ solc {contract}.sol --bin --abi --optimize -o {output-dir}/ this will generate .abi and .bin files from which you generate a java wrapper class: $ web3j solidity generate /path/to/<smart-contract>.bin /path/to/<smart-contract>.abi -o /path/to/src/main/java -p com.your.organisation.name This will produce a java wrapper class for your contract like MyContract.java on which you can call all the methods available on the smart contract: import static org.web3j.tx.Contract.GAS_LIMIT; import static org.web3j.tx.ManagedTransaction.GAS_PRICE; //web3j initialization code goes here //Load the deployed contract: MyContract contract = MyContract.load(contractAddress, web3j, credentials, GAS_PRICE, GAS_LIMIT); //Call methods on the contract: Future<> result = contract.transfer(_to, _value); You can find more info on how to work with smart contracts wrappers here. Hope that helps. edit. abi and bin for this particular contract can be obtained from etherscan.io You can transfer tokens even if you are not the owner of the contract. But you are only abe to transfer tokens available to your own account as seen in the contract: function transfer(address _to, uint256 _amount) returns (bool success) { if (balances[msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { return false; } }
[ "superuser", "0001368538.txt" ]
Q: Batch file: Run command and loop at same time I want to run a simple batch script that basically includes only two Wireshark commands: @echo off dumpcap -i 1 -f "tcp port 8800" -a "filesize:100" -n -w "data.pcap" && :loop start tshark -r data.pcap -T fields -Y "frame contains ERROR" -e data.data > data.txt timeout /t 5 echo hi goto :loop However, only the first command dumpcap.... will run. I can't get the loop to work. It works when I put the loop in a separate batch file, but that's not what I want. A: You need to remove the line that contains &&. If you run your script from the Command Prompt (instead of double-clicking it in Windows) you should be getting this error: && was unexpected at this time. The && is a conditional command separator that means "run the following command only if the proceeding command was successful." However it has no meaning on a line of its own. The working script should look like this: @echo off dumpcap -i 1 -f "tcp port 8800" -a "filesize:100" -n -w "data.pcap" :loop start tshark -r data.pcap -T fields -Y "frame contains ERROR" -e data.data > data.txt timeout /t 5 echo hi goto :loop You can learn more about this command at this StackOverflow question.
[ "stackoverflow", "0026664317.txt" ]
Q: Feature doesn't show up on the map I've been trying the new version (3) of Open Layers. I've modified the icon feature example slightly, so it would show a polygon. I've been searching, reading and trying for a couple of hours, but can't figure out what I'm doing wrong. I don't want to use geoJSON, because I want to dynamically add and remove features. This is the code I have so far: <script type="text/javascript"> var point1 = ol.proj.transform([37.41, 8.82], 'EPSG:4326', 'EPSG:3857'); var point2 = ol.proj.transform([35.41, 9.82], 'EPSG:4326', 'EPSG:3857'); var point3 = ol.proj.transform([33.41, 11.82], 'EPSG:4326', 'EPSG:3857'); var polyFeat = new ol.Feature({ geometry: new ol.geom.Polygon([point1, point2, point3]) }); var polyStyle = new ol.style.Style({ fill: new ol.style.Fill({ color: 'blue' }), stroke: new ol.style.Stroke({ color: 'red', width: 2 }) }); polyFeat.setStyle(polyStyle); var vectorSource = new ol.source.Vector({ features: [polyFeat] }); var vectorLayer = new ol.layer.Vector({ source: vectorSource }); var rasterLayer = new ol.layer.Tile({ source: new ol.source.TileJSON({ url: 'http://api.tiles.mapbox.com/v3/mapbox.geography-class.jsonp' }) }); var map = new ol.Map({ layers: [rasterLayer, vectorLayer], target: document.getElementById('map'), view: new ol.View({ center: ol.proj.transform([37.41, 8.82], 'EPSG:4326', 'EPSG:3857'), zoom: 3 }) }); </script> Why is the polygon not showing? A: Two small things to solve your issue: First, it's recommended to close a polygon, so declare a fourth point with same coordinates as the first. var point4 = ol.proj.transform([37.41, 8.82], 'EPSG:4326', 'EPSG:3857'); Then, your geometry new ol.geom.Polygon([point1, point2, point3]) should be new ol.geom.Polygon([[point1, point2, point3, point4]]) The important fact here is not the point4 addition but to transform your array point to an array of array of points. See the API that says OpenLayers 3 ol.geom.Polygon constructor expects an Array.<Array.<ol.Coordinate>> expected.
[ "stackoverflow", "0049905026.txt" ]
Q: how to set new date() in a @requestParam? I would like to know if is possible to set a new date() in a @requestParam? @RequestMapping("/resa") public String reservation(Model model,@RequestParam(name = "page", defaultValue = ?????? )int p ) throws ParseException Thank you in advance A: Annotations in Java are limited to compile-time constants, so you can't instantiate any new Objects there. There may be a way by using Spring's Expression Language, but I find that hacky. I guess after Java 8, the correct way to do this would be to have a parameter of type Optional<LocalDateTime>> (Date is a bad old API, don't use it): @RequestMapping("/resa") public String reservation(Model model, @RequestParam("date") Optional<LocalDateTime>> optionalDate){ LocalDateTime date = optionalDate.orElseGet(()-> LocalDateTime.now()); } The Spring docs explicitly mention that Optionals are supported as arguments.
[ "stackoverflow", "0061337633.txt" ]
Q: Caliburn.Micro TreeView add a static element I have a working TreeView <TreeView x:Name="TVAccess" ItemsSource="{Binding AccessLevel}" Grid.Row="1" Grid.Column="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.ColumnSpan="3"> <TreeView.ItemTemplate> <HierarchicalDataTemplate > <StackPanel Orientation="Horizontal"> <!--<CheckBox Checked="{Binding Checked}"/>--> <TextBlock Text="{Binding Text}" /> </StackPanel> </HierarchicalDataTemplate> </TreeView.ItemTemplate> </TreeView> It is bind to AccessLevel object defined like this public BindableCollection<UserLibrary.DataAccess.TextHelper.TreeViewItem> AccessLevel { get; set; } This works well The result is this I would like to add a fixed first level named "Access Right", how can I do that? EDIT 1 The structure I would like is this: Thank you for your help. Edit 2 - The TreeViewItem class public class TreeViewItem { public string Text { get; set; } public bool Checked { get; set; } } Edit 3 - Modify the TreeViewItem Class So if I mofify my call like this, now the problem is to bind it to the TreeView public class TreeViewItem { public string Text { get; set; } public bool Checked { get; set; } public IEnumerable<TreeViewItem> SubTreeViewItem { get; set; } } A: Insert a TreeViewItem to the source collection at index 0. AccessLevel.Insert(0, new UserLibrary.DataAccess.TextHelper.TreeViewItem() { Text = "Access Right" } ); Or set the ItemsSource property to a CompositeCollection and define the fixed item in the XAML markup: <TreeView x:Name="TVAccess" Grid.Row="1" Grid.Column="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.ColumnSpan="3"> <TreeView.Resources> <CollectionViewSource x:Key="source" Source="{Binding AccessLevel}" /> </TreeView.Resources> <TreeView.ItemsSource> <CompositeCollection> <local:TreeViewItem Text="Access Right" /> <CollectionContainer Collection="{Binding Source={StaticResource source}}" /> </CompositeCollection> </TreeView.ItemsSource> <TreeView.ItemTemplate> <HierarchicalDataTemplate > <StackPanel Orientation="Horizontal"> <!--<CheckBox Checked="{Binding Checked}"/>--> <TextBlock Text="{Binding Text}" /> </StackPanel> </HierarchicalDataTemplate> </TreeView.ItemTemplate> </TreeView>
[ "stackoverflow", "0052469050.txt" ]
Q: send_push_message() missing 4 required positional arguments: 'token', 'title', 'message', and 'extra' I keep getting this error: send_push_message() missing 4 required positional arguments: 'token', 'title', 'message', and 'extra', what can i do? def receive_request(request, self): self.token = request.data['token'] self.title = request.data['title'] self.message = request.data['message'] self.extra = request.data['extra'] @api_view(["POST"]) @permission_classes((AllowAny, )) def send_push_message(self, token, title, message, extra): token = self.token title = self.title message = self.message extra = self.extra #it continues from here A: In Django Rest Framework, function based views should accept a request as the first argument and then any other arguments need to be defined by regular expression capture in the url definition for the view. See this doc for more: http://www.django-rest-framework.org/api-guide/views/#function-based-views It looks like the data you're getting comes from the request body. Note that to pass arguments to a view function, they need to be defined in the url, not the request payload. With that in mind, here's how you can refactor your code: import json @api_view(["POST"]) @permission_classes((AllowAny, )) def send_push_message(request): data = json.loads(request.body) token = data.get('token') title = data.get('title') message = data.get('message') extra = data.get('extra')
[ "stackoverflow", "0052625951.txt" ]
Q: Python logic if and or opposite Level = 4 Name = "Mike" Form = None if Level == 5 or Name in ['James','Chris','Alex'] or (Name in ['John','Mike'] and Form): The above code does exactly what I want it to do, but I can't figure out how to do the opposite: e.g. if Level != 5 and Name not in ['James','Chris','Alex'] and (Name not in ['John','Mike'] and Form): As close as I got but does not work the same. A: How about clubbing everything in parenthesis and just use not in the beginning. That way, you don't need to reverse any operator. if not (Level == 5 or Name in ['James','Chris','Alex'] or (Name in ['John','Mike'] and Form)):
[ "stackoverflow", "0042942294.txt" ]
Q: Method to bind Model to ViewModel In ReactiveUI, if I have a model (INotifyPropertyChanged) behind a ViewModel (ReactiveObject) what's the best practice? Do I use the model in the getter and setter of a property: private Model model; public string Minky { get { return model.Minky; } set { model.Minky = value; this.PropertyChanged(); } } Or should I bind individual properties: private string minky; public string Minky { get { return minky; } set { this.RaiseAndSetIfChanged(ref minky, value); } } public ViewModel( Model model ) { if ( model != null ) { model.WhenAnyValue( x => x.Minky ).BindTo( this, x => x.Minky ); } } The second version seems like a good idea (I can still set properties when there is no model). Is there any reason why this is a bad idea? A: In any MVVM binding pattern best practice is to bind the "View" to the "ViewModel" and no model is used here. Of course models are then used in data access and business layers to do stuff like record in db or pass to web services but not in binding. By any chance if you want to use your encapsulated models for binding reasons you should make your models as bindable objects with their own PropertyChanged notifiers and then bind to them. Like this: You have a Model in your ViewModel private Model model; public Model Model { get { return model; } set { model = value; this.PropertyChanged(); } } And then bind to properties this.Bind(ViewModel, x => x.Name, x => x.Model.Minky); So to summarize: It's a bad idea. But if you want to do it bind directly to a model instance inside your ViewMdel.
[ "stackoverflow", "0022081251.txt" ]
Q: Inserting a record in Oracle using biztalk 2010 issue I am trying to follow this blog to insert a record into an oracle table using BizTalk 2010 http://biztalk2010changes.blogspot.co.nz/2011/04/insert-update-delete-select-operation.html No orchestration was created I only created a WCF-custom generated item using OracleDBBinding contract type client/(outbound operation). I selected the table and picked Insert category. An xsd was generated with the following entries xxRECORDINSERT, arrayOfxxxRECORDINSERT, Insert, InsertResponse. I generated an instance of the above schema, my goal is using that instance as a file with content to be inserted into my oracle table. I deployed the application successfully, set up FilePort when BizTalk will pick up the file and the oracle port based on the bindings created by BizTalk (the steps I followed as similar to the link I provided above. I have also set up the filter for the application to pickup the file and the message However, when the file was drop into the directory, it was indeed picked up but I got this routing error: and the I got this error msg log: WcfSendPort_OracleDBBinding_ORASCHEMA_Table_ROTATION_REQ_Custom oracledb://oracleServer/?PollingId=TEST_00042 Microsoft.ServiceModel.Channels.Common.XmlReaderParsingException: Unexpected start node "ROTATION_REQRECORDINSERT" with namespace "http://Microsoft.LobServices.OracleDB/2007/03/ORASCHEMA/Table/ROTATION_REQ" found. This is an extract of my schema: <?xml version="1.0" encoding="utf-16" ?> - <xs:schema xmlns:b="http://schemas.microsoft.com/BizTalk/2003" xmlns:tns="http://Microsoft.LobServices.OracleDB/2007/03/ORASCHEMA/Table/ROTATION_REQ" elementFormDefault="qualified" targetNamespace="http://Microsoft.LobServices.OracleDB/2007/03/ORASCHEMA/Table/ROTATION_REQ" version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema"> and this is an instance of my sample I tried to insert into my table: <ns0:ROTATION_REQRECORDINSERT xmlns:ns0="http://Microsoft.LobServices.OracleDB/2007/03/ORASCHEMA/Table/ROTATION_REQ"> <ns0:RotationID InlineValue="InlineValue_0">RotationID_0</ns0:RotationID> <ns0:Year InlineValue="InlineValue_0">2015</ns0:Year> <ns0:Class InlineValue="2015">T4</ns0:Class> <ns0:Rotation InlineValue="InlineValue_0">Rotation_0</ns0:Rotation> <ns0:From InlineValue="InlineValue_0">1999-05-31T13:20:00.000-05:00</ns0:From> <ns0:To InlineValue="InlineValue_0">1999-05-31T13:20:00.000-05:00</ns0:To> <ns0:NumberOfConsecutiveSession InlineValue="InlineValue_0">500</ns0:NumberOfConsecutiveSession> <ns0:AmOrPM InlineValue="InlineValue_0">3</ns0:AmOrPM> <ns0:DayOfWeek InlineValue="InlineValue_0">6</ns0:DayOfWeek> </ns0:ROTATION_REQRECORDINSERT> Anything I did was incorrect? Update: The context of the message: A: After a while banging my head against the wall, I finally managed to figure out what I need to do to make it works. The post was accurate at what it described but it was what not there that confused me and caused issue for me. I updated this for myself or anyone else that might run into my same scenario in the future. These are the things I did incorrectly for lack of instructions: 1) I used xxRECORDINSERT to create my message which is not correct. I should have used Insert instead. It was actually there in the sample but I have overlooked it and have let BizTalk auto generate it. The insert should have been moved to the beginning of the file so that BizTalk could generate the message correctly. That was probably the reason why BizTalk was complaining about the "unexpected start node". 2) I need to create another port to catch the response from BizTalk after the record was inserted otherwise it will cause the routing error I had experienced earlier. These are very fundamental errors that I have overlooked. Hope it will save someone else time should they come across the same issue in the future.
[ "stackoverflow", "0021247203.txt" ]
Q: How to make a pandas crosstab with percentages? Given a dataframe with different categorical variables, how do I return a cross-tabulation with percentages instead of frequencies? df = pd.DataFrame({'A' : ['one', 'one', 'two', 'three'] * 6, 'B' : ['A', 'B', 'C'] * 8, 'C' : ['foo', 'foo', 'foo', 'bar', 'bar', 'bar'] * 4, 'D' : np.random.randn(24), 'E' : np.random.randn(24)}) pd.crosstab(df.A,df.B) B A B C A one 4 4 4 three 2 2 2 two 2 2 2 Using the margins option in crosstab to compute row and column totals gets us close enough to think that it should be possible using an aggfunc or groupby, but my meager brain can't think it through. B A B C A one .33 .33 .33 three .33 .33 .33 two .33 .33 .33 A: From Pandas 0.18.1 onwards, there's a normalize option: In [1]: pd.crosstab(df.A,df.B, normalize='index') Out[1]: B A B C A one 0.333333 0.333333 0.333333 three 0.333333 0.333333 0.333333 two 0.333333 0.333333 0.333333 Where you can normalise across either all, index (rows), or columns. More details are available in the documentation. A: pd.crosstab(df.A, df.B).apply(lambda r: r/r.sum(), axis=1) Basically you just have the function that does row/row.sum(), and you use apply with axis=1 to apply it by row. (If doing this in Python 2, you should use from __future__ import division to make sure division always returns a float.) A: We can show it as percentages by multiplying by 100: pd.crosstab(df.A,df.B, normalize='index')\ .round(4)*100 B A B C A one 33.33 33.33 33.33 three 33.33 33.33 33.33 two 33.33 33.33 33.33 Where I've rounded for convenience.
[ "magento.stackexchange", "0000000971.txt" ]
Q: Limiting javascript includes by store within a module I have a payment module that requires a bit of javascript on the checkout page for stores where it is enabled. The good news is that it is correctly including the link on the checkout page. Unfortunately, its also including the link on every other page and in every store. How do you setup a javascript include to only appear in a certain section and only in stores where it is enabled? A: If your module has a simple enable/disabled configuration setting for each store scope (which it seems to), you can use ifconfig, which is evaluated by Mage::getStoreConfigFlag(): <?xml version="1.0" encoding="UTF-8"?> <layout> <checkout_onepage_index><!-- the onepage checkout "page" --> <reference name="head"><!-- The HTML head block --> <action method="addJs" ifconfig="your/checkout_module/enabled"> <js>your/file.js</js><!-- i.e. js/your/file.js --> </action> </reference> </checkout_onepage_index> </layout>
[ "stackoverflow", "0017427325.txt" ]
Q: how to display product image in order history in prestashop I need to display product image in order details page when user click order details link. I have edited below code in order-detail.tpl but it not shows product image it shows only some dummy image <td> <a href="{$link->getProductLink($product.product_id, $product.link_rewrite, $product.category, null, null, $product.id_shop, $product.id_product_attribute)|escape:'htmlall':'UTF-8'}"> <img src="{$link->getImageLink($product.link_rewrite, $product.id_image, 'small_default')}" alt="{$product.name|escape:'htmlall':'UTF-8'}" {if isset($smallSize)}width="{$smallSize.width}" height="{$smallSize.height}" {/if} /></a> </td> A: If that page you can view the variable what comes with $product. Like this. {$product|var_dump} and you will notice that $product have a array value image which is a object so now go with this. {$product.image|var_dump} and you will view all this value. object(Image)#490 (26) { ["id"]=&gt; int(1) ["id_image"]=&gt; string(1) "1" ["id_product"]=&gt; string(1) "3" ["position"]=&gt; string(1) "1" ["cover"]=&gt; string(1) "1" ["image_format"]=&gt; string(3) "jpg" ["source_index"]=&gt; string(52) "/Applications/MAMP/htdocs/prestashop/img/p/index.php" ["folder":protected]=&gt; NULL ["existing_path":protected]=&gt; NULL ["id_lang":protected]=&gt; NULL ["id_shop":protected]=&gt; int(1) ["id_shop_list"]=&gt; NULL ["get_shop_from_context":protected]=&gt; bool(true) ["table":protected]=&gt; string(5) "image" ["identifier":protected]=&gt; string(8) "id_image" ["fieldsRequired":protected]=&gt; array(1) { [0]=&gt; string(10) "id_product" } ["fieldsSize":protected]=&gt; array(0) { } ["fieldsValidate":protected]=&gt; array(3) { ["id_product"]=&gt; string(12) "isUnsignedId" ["position"]=&gt; string(13) "isUnsignedInt" ["cover"]=&gt; string(6) "isBool" } ["fieldsRequiredLang":protected]=&gt; array(0) { } ["fieldsSizeLang":protected]=&gt; array(0) { } ["fieldsValidateLang":protected]=&gt; array(0) { } ["tables":protected]=&gt; array(0) { } ["webserviceParameters":protected]=&gt; array(0) { } ["image_dir":protected]=&gt; string(43) "/Applications/MAMP/htdocs/prestashop/img/p/" ["def":protected]=&gt; array(6) { ["table"]=&gt; string(5) "image" ["primary"]=&gt; string(8) "id_image" ["multilang"]=&gt; bool(true) ["fields"]=&gt; array(3) { ["id_product"]=&gt; array(3) { ["type"]=&gt; int(1) ["validate"]=&gt; string(12) "isUnsignedId" ["required"]=&gt; bool(true) } ["position"]=&gt; array(2) { ["type"]=&gt; int(1) ["validate"]=&gt; string(13) "isUnsignedInt" } ["cover"]=&gt; array(3) { ["type"]=&gt; int(2) ["validate"]=&gt; string(6) "isBool" ["shop"]=&gt; bool(true) } } ["classname"]=&gt; string(5) "Image" ["associations"]=&gt; array(1) { ["l"]=&gt; array(3) { ["type"]=&gt; int(2) ["field"]=&gt; string(8) "id_image" ["foreign_field"]=&gt; string(8) "id_image" } } } ["update_fields":protected]=&gt; NULL } You will notice that there is not value of link_rewrite. So you need to pass that from the controller.
[ "stackoverflow", "0004423560.txt" ]
Q: Problem with a regular expression in PHP I need to get this working: PHP First match should look for the following: $pattern1 = "/<div rawurl\=\"(.*)\" class/"; // Add wildcard here as there will be 10 matches, we are only looking for one. preg_match($pattern1, $file, $out1); Then run a second check to see if our defined variable exists in the result from the first preg_match $out1, $pattern2 = preg_quote("http://domain.com/extras/?possiblequery" ."/"); $pattern2 = "/".$pattern2."/"; if (preg_match($pattern2, $file, $out)); { return result I have trouble coding up the regular expression for these two preg_match lines... I am pretty sure it's the first one with the wildcard.. Any help is welcome! A: You need to specify the delimiters with the second parameter of preg_quote: preg_quote("http://example.com/extras/?possiblequery", "/")
[ "stackoverflow", "0050358903.txt" ]
Q: reducing the number of email notifications sent by Gerrit I'm currently using Gerrit to manage a project, I've received complaints about how chatty gerrit is. Is there anyway to filter who gets which emails (i.e. code review owner gets all emails, while reviewers only get notified when added to a new code review or a new patchset is added) I've looked into the project level notification settings but I'm not 100% sure how they work? (do they only apply to the project watchers? or to everyone involved in a code review in that project) I understand that when using the REST API calls I can choose who to notify but not when making changes using the web interface. A: You can configure e-mail notifications in two different levels: 1) User level Go to Settings > Watched Projects and add the project(s) which you want to receive notifications. You can also add a search expression to receive notifications "only if" a situation is satisfacted (e.g. branch:release). You can receive notifications for one (or more) of the following: New Changes New Patch Sets All Comments Submitted Changes Abandoned Changes 2) Project level Independent if users configured or not the first notification level, you can set projects to send notifications to users or groups if some pre defined situations (like the ones showed in the user level above) happens. See here more details about the e-mail notifications and how to configure the project level one. Notes: Although you can add more notifications using these methods, you can not remove the default existing notifications. With Gerrit 2.15 you can ignore and mute changes. I think these new features can be very usefull to you.
[ "stackoverflow", "0018598507.txt" ]
Q: Disjunction of filters in ajax, request to flask-restless I have a backend application with flask-restless which replies some json data. It is properly set. I request these data from javascript by $.ajax function. It works perfect with one filter, I need more filters, but I don't know how them set. Example with one filter (it works): var page = 1; var filters = [{"name": "device", "op": "eq", "val": 1}]; var url = 'http://..../results?page=' + page; $.ajax({ url: url, data: {"q": JSON.stringify({"filters": filters})}, dataType: "jsonp", type: "GET", contentType: "application/jsonp", success: function(responseData, textStatus, XMLHttpRequest) {...} }); For 2 filters I tried (it doesn't work): var page = 1; var filters = [{"name": "device", "op": "eq", "val": 1},{"name": "device", "op": "eq", "val": 2}]; var url = 'http://..../results?page=' + page; $.ajax({ url: url, data: {"q": JSON.stringify({"filters": filters},{"disjunction":true})}, dataType: "jsonp", type: "GET", contentType: "application/jsonp", success: function(responseData, textStatus, XMLHttpRequest) {...} }); Has anyone of you ever had similar problem? A: You need to give JSON.stringify an array to convert to string. data: {"q": JSON.stringify([{"filters": filters},{"disjunction":true}])},
[ "stackoverflow", "0009804484.txt" ]
Q: How do I use a back reference in the cmd executed by :g? When answering Remove EOL spaces of selection only if there are, I noticed that my answer is not really satisfying: the pattern \ \+$ has to be typed twice: once for searching with :g once for replacing with :s First thought was to simply use g/\(\ \+$\)/s/\1//g but this gives me an error about an invalid back reference (E65). Is there a way to re-use the pattern used in :g for the [cmd] being executed? A: You don't need \1: :g/ \+$/s///g :g/pat/s//PAT/g is same as: :%s/pat/PAT/g
[ "stackoverflow", "0057295382.txt" ]
Q: create a plot from two dataframe with two y -axes I want a plot with two y-axes from two different data frame in one plot. So far I tried to change the one data frame two y-axes version but I failed. import pandas as pd import matplotlib.pyplot as plt plt.close("all") df1 = pd.DataFrame({"x1": [1,2 ,3 ,4 ], "y1_1": [555,525,532,585], "y1_2": [50,48,49,51]}) df2 = pd.DataFrame({"x2": [1, 2, 3,4], "y2_1": [557,522,575,590], "y2_2": [47,49,50,53]}) ax1 = df1.plot(x="x1", y="y1_1", legend=False) ax2 = ax1.twinx() df1.plot(x="x1", y="y1_2", ax=ax2, legend=False, color="r") ax3 = df2.plot(x="x2", y="y2_1", legend=False) ax4 = ax1.twinx() df2.plot(x="x2", y="y2_2", ax=ax4, legend=False, color="r") plt.grid(True) ax1.figure.legend() plt.show() below this is what I want. So far I have two plots but I want just everything in one plot. A: Is this what you want: ax1 = df1.plot(x="x1", y="y1_1", legend=False) ax2=ax1.twinx() df1.plot(x="x1", y="y1_2", ax=ax2, legend=False, color="r") df2.plot(x="x2", y="y2_1", ax=ax1, legend=False) df2.plot(x="x2", y="y2_2", ax=ax2, legend=False, color="r") which gives: Or, you can predefine ax1 and ax2, then pass them to plot functions: fig, ax1 = plt.subplots() ax2=ax1.twinx() df1.plot(x="x1", y= ["y1_1"], ax=ax1, legend=False) df1.plot(x="x1", y="y1_2", ax=ax2, legend=False, color="r") df2.plot(x="x2", y="y2_1", ax=ax1, legend=False) df2.plot(x="x2", y="y2_2", ax=ax2, legend=False, color="r")
[ "stackoverflow", "0013552928.txt" ]
Q: Combine text fields as shown in Windows 7 Calculator How can I make a 'combined' Text Field (outlined in red, below) as shown in Windows Calculator? A: Neither of those fields is focusable. Two labels stacked on top of each other should do it.
[ "money.stackexchange", "0000046013.txt" ]
Q: As a J-1 visa holder, am I allowed to make additional income in the US? I am living in the US under a J-1 visa. I am thinking of building and launching an iOS application that might bring in some additional income from the App Store (potentially hundreds to thousands of dollars per month). As a "non-resident" under a J-1 visa in the US, am I allowed to receive additional income besides the salary at my regular job (the one I was brought here under my J-1 visa)? A: The prohibition is on working for someone else, not on making money. You would not be an employee or contractor of the app stores, you will also be able to release the app worldwide, and you will sign up to those services based on your current citizenship and banking relationships in your country. As such, I'm going to go with "Yes", to your original question.
[ "stackoverflow", "0005089982.txt" ]
Q: Android: Service start Activity The problem is: Service send me a data every 1 hour and i need to start Activity1. If i do nothing, its all the time will create the same Activity1 and in a 5 hours in stack i will have 5 the same Activities...So, how to kill activity before new one will start ? Thanks ! Intent dialogIntent = new Intent(getBaseContext(), someClass.class); getApplication().startActivity(dialogIntent); A: So, how to kill activity before new one will start ? You don't. First, your users will attack you with hunting knives for popping up an activity in the middle of nowhere. You do not know what they may be in the middle of doing (playing a game, typing a text message, etc.). Only a very few apps, such as VOIP clients and alarm clocks, should be displaying activities except based upon direct user input. Second, you don't "kill activity" from a service. Rather you put appropriate flags on your Intent to bring the existing activity to the front if it exists (e.g., FLAG_REORDER_TO_FRONT), rather than create a new one.
[ "stackoverflow", "0039907323.txt" ]
Q: I need to remote desktop into 100s of VMs created in Azure I will be creating 100s of Virtual Machines in the Azure, which I will use them for execution of my UI test case. Challenge here is I Need to have a active desktop for running the Tests. Currently at on promise I download Microsoft Remote desktop manager and make connections to 20-30 machines from each RDP session and hence able to keep desktop active for 100s of VMs. In Azure I have observed that it downloads 1 rdp file for each VM. So my question now is what is the best way to remote desktop into 100s of VMs running in azure ?. Are there any other ways to keep desktop active and logged in without using the RDP manager ? A: If you are simply trying to have the VMs log in as a user when it boots, you can achieve that by setting registry keys through the custom script extension. Write a powershell script that sets the auto-logon registry keys and run it via the custom script extension. The powershell script may need to reboot the VM at the end to get it to log in the first time. Here is a custom script extension example: https://github.com/Azure/azure-quickstart-templates/tree/master/201-vm-custom-script-windows Here is info on the registry keys for automatically logging in on startup: https://support.microsoft.com/en-us/kb/324737 You also probably want to set the screen resolution to something reasonable: https://technet.microsoft.com/en-us/library/jj603036(v=wps.630).aspx
[ "stackoverflow", "0017113196.txt" ]
Q: How/should I replace nested foreach with one linq query? Trying to set a property on certain labels contained in a Windows Forms GroupBox, I wrote the loops below. This works fine, but I don't like it due to its (I think unnecessary) double foreach nesting. I have tried to rewrite this to be more clear, use only one foreach, and a combined Linq expression, but all my attempts fail at runtime with a CastException, either from GroupBox to Label or vice versa. Is there a more clear, more efficient, or more readable way to write this loop construct? foreach (var gb in (from Control c in this.Controls where c is GroupBox select c)) foreach (Label tlbl in (from Control a in gb.Controls where a is Label && a.Tag != null && a.Tag.ToString() == "answer" select a)) tlbl.ForeColor = (tlbl.Name.Replace("lbl", "") == rb.Name) ? afterSelectColor : beforeSelectColor; Readability is my highest goal. With that in mind, is it worth trying to rewrite it? A: I'd recommend you do the editing in a foreach, as LINQ is not meant to cause side effects. Like this: foreach (Label tlbl in (this.Controls.OfType<GroupBox>() .SelectMany(g => g.Controls.Cast<Control>()).OfType<Label>() .Where(a => a.Tag != null && a.Tag.ToString() == "answer"))) { tblb.ForeColour = tlbl.Name.Replace("lbl", "") == rb.Name ? afterSelectColor : beforeSelectColor; } Note SelectMany in here. That's how you translate nested foreach loops to LINQ, as it is pretty much just a nested foreach loop.
[ "stackoverflow", "0062182269.txt" ]
Q: NodeJS MVC asynchronous request I'm getting undefined data from controller to model request in NodeJS. My Model: const db = require('../util/database'); module.exports = class Property { constructor(pID) { } getPropertyByID(pID) { let property = {}; db.execute('SELECT * From Properties Where PropertyID = ' + pID) .then(res => { const data = res[0][0]; if(data){ //console.log(data); This shows DATA if I remove the comment property = data; } return property; }) .catch(err => { console.log(err); }); } } Then, in my controller I tried to use the Model method. exports.sendDataID = (req, res, next) => { const propID = req.params.propID; if(propID) { const property = new Property(); const data = property.getPropertyByID(propID); console.log(data); } }; The console.log(data) is returning undefined. Why is it happening? Thanks A: You may use async and await function to return a promise result. async getPropertyByID(pID) { let property = {}; try{ var res = await db.execute('SELECT * From Properties Where PropertyID = ' + pID) property = res[0][0]; //not sure what res variable is return data }catch(error){ return error } } and for use this function you only need to do this: const propID = req.params.propID; if(propID) { const property = new Property(); const data = await property.getPropertyByID(propID); console.log(data); } I recomend you to read about promises functions: https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Promise
[ "stackoverflow", "0014123672.txt" ]
Q: Cannot create new git branch in Heroku project I pulled a project from Heroku and now when I am trying to create in this project on my localhost a new branch, I always get this error message: git checkout new_branch error: pathspec 'new_branch' did not match any file(s) known to git. When I run git branch -a, I get * master remotes/heroku/HEAD -> heroku/master remotes/heroku/master What causing this error? And, how can I fix it? Thank you A: You need to say git checkout -b new_branch to create the branch. See the documentation for checkout here: http://www.kernel.org/pub/software/scm/git/docs/git-checkout.html
[ "unix.stackexchange", "0000406961.txt" ]
Q: How to use linebreak in read -p command while using variables in prompt string I want to have a line break after prompt while using the cowsay function in the prompt : read -p "$(cowsay "do you know this word?") \n" answer there are multiple answers to this problem : 1)https://stackoverflow.com/questions/4296108/how-do-i-add-a-line-break-for-read-command/4296147 2)https://stackoverflow.com/questions/12741529/how-to-break-a-line-add-a-newline-in-read-p-in-bash However the answers use the '' notation, which doesn't resolve the cowsay command A: Why would you use the -p option for which you'd need the bash shell? Just do: cowsay "do you know this word?" read answer In bash, the -p option is only useful in conjunction with -e (another bash extension which makes bash's read behave like zsh's vared) where bash may need to redraw the prompt on some occasions (like upon Ctrl+L). But then, you would probably not need nor want it to redraw that prompt when it's several lines. If you wanted to, you could always do: read -ep "$(cowsay "do you know this word?")"$'\n' answer (here using ksh93's $'...' form of quoting that understands C-like escape sequences) or read -ep "$(cowsay "do you know this word?") " answer More generally, the problem is that command substitution strips newline characters (not just one, all of them which could be considered a bug/misfeature¹) from the end of the command's output. To work around that, the usual trick is to do: output=$(cowsay "do you know this word?"; echo .) output=${output%.} read -p "$output" answer That is, add .\n to the output. Command substitution strips the \n and we strip the . with ${output%.} leaving the whole command's output (provided it doesn't contain NUL characters in shells other than zsh, and that it's valid text in the current locale in yash). For the record, in other Korn-like shells, the syntax for read to issue a prompt by itself is with: read 'answer?prompt: ' The Korn shell would also redraw that prompt when reading from the terminal and an editor option has been enabled (like with set -o emacs or set -o vi). zsh also supports that syntax for compatibility, but the line editor is only used for vared, not for read there. ¹ for instance, it makes things like basename=$(basename -- "$file") wrong, as it could strip newline characters from the end of the file name, not just the one added by basename
[ "stackoverflow", "0032892081.txt" ]
Q: javascript fire method before or after another method is called I would like to know what are the common approach to make this concept works: function Abc () { var beforeMethod = function (e) { console.log(e); }; this.before('bob ana', beforeMethod); } Abc.prototype.ana = function () { console.log('ana'); } Abc.prototype.bob = function () { console.log('bob'); } Abc.prototype.maria = function () { console.log('maria'); } // var abc = new Abc(); abc.ana(); It's supposed to call beforeMethod before bob or ana is called. A: Quickly : need to be tested and securised, but i think it do the trick ! I haven't understood what your e mean so i put the called method name in it ! var el = document.getElementById('debug'); var $l = function(val) { console.log(val); el.innerHTML = el.innerHTML + '<div>' + val + '</div>'; }; //___________________________________________________________________ var Before = function( methods , func , context){ methods.split(' ').map(function(m){ var ori = context[m]; if(ori){ context[m] = function(){ func.call(context , m); return ori.apply(context , arguments); }; } }); }; var Abc = function () { var beforeMethod = function (e) { $l('from beforeMethod : ' + e); }; Before('bob ana ', beforeMethod , this); }; Abc.prototype.ana = function () { $l('from ana '); }; Abc.prototype.bob = function () { $l('from bob '); }; Abc.prototype.maria = function () { $l('from maria '); }; var abc = new Abc(); abc.ana(); abc.maria(); abc.bob(); <div id='debug'>Debug <div>
[ "stackoverflow", "0013093559.txt" ]
Q: Quote issue in HTML, Javascript, .innerHTML, switch and case I'm modifying a websense block page to include a few functions based on a variable: $*WS_BLOCKREASON*$. I know the potential output of this variable, and I want to have a specific function for. The issue is that the page is not passing even the default case to the '<'div'>' contents. Essentially I need the contents of the <div id="helpDiv"> to be a whole set of text including the button. Script below: <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Access to this site is blocked</title> <link rel="stylesheet" href="/en/Custom/master.css" type="text/css"> <script type="text/javascript" language="javascript" src="/en/Default/master.js"></script> <script type="text/javascript" language="javascript" src="/en/Default/base64.js"></script> <script type="text/javascript" language="javascript" src="/en/Custom/security.js"></script> <style type="text/css"> .style1 { width: 130px; height: 70px; } </style> </head> <body> <!--[if lt IE 7]> <div style="width: 725px; height: 381px;"> <![endif] --> <img alt="BHI" class="style1" src="/en/Custom/other.gif" /><br /> <br /> <br /> <div style="border: 1px solid #285EA6;width: 99.5%; max-width: 915px; overflow: hidden; margin-left: 1px; background-color: #EEF2F7;"> <iframe src="$*WS_BLOCKMESSAGE_PAGE*$*WS_SESSIONID*$" title="BHI_BLOCK" name="ws_block" frameborder="0" scrolling="no" style="width:100%; height: 200px; margin-bottom: 0px;"> </iframe> <hr /> <!-- onload=function() possible fix --> <script type="text/javascript"> var blockReason=$*WS_BLOCKREASON*$; switch (blockReason) { case 'This Websense category is filtered: <b>Uncategorized</b>.': document.getElementById('helpDiv').innerHTML='<p style="margin-left: 10px">Help:&nbsp;&nbsp;&nbsp;&nbsp;<INPUT TYPE="button" VALUE="Submit UNCATEGORIZED website to Websense" onClick="parent.location=\'mailto:[email protected]?subject=Uncategorized Website&body=Please review and correctly categorize the website that is listed below:%0A%0A' + $*WS_URL*$ + '%0A%0AThank you.\'"></p>\ <hr />\ <p style="margin-left: 64px">Clicking on the above button will open your mail client to send an e-mail to Websense for recategorization of the above site.</p>\ <p style="margin-left: 64px">You will receive a confirmation e-mail and a case number from Websense indicating your request is proccessing.</p>\ <p style="margin-left: 64px">Please note the response time for your request will vary. Allow to three to four (3-4) hours for updates to take effect once approved.</p>\ <p style="margin-left: 64px">If you have any questions, please contact SOLV at <a href=tel:+18772222222>+1 877 2222222<a/> or <a href=http://solv:8093/CAisd/pdmweb.exe?OP=JUST_GRONK_IT+HTMPL=about.htmpl target="_blank">this link.</a></p>'; break; case 'This Websense category is filtered: <b>Parked Domain</b>.': document.getElementById('helpDiv').innerHTML='<p>Parked domain</p>'; break; default: document.getElementById('helpDiv').innerHTML='<p>No Block message help.</p>'; } </script> <div frameborder="0" scrolling="no" style="width:100%; height: auto; margin-bottom: 0px;" id="helpDiv"> </div> <iframe src="$*WS_BLOCKOPTION_PAGE*$*WS_SESSIONID*$" name="ws_blockoption" frameborder="0" scrolling="no" style="width:100%; height: auto;"> <p>To enable further options, view this page with a browser that supports iframes</p> padding: 2px 0px;"> <div style="clear: both; overflow: hidden; height:1px;"></div> </div> </div> <!--[if lt IE 7]> </div> <![endif]--> <div id="light" class="white_content"></div> <div id="fade" class="black_overlay"></div> </body> </html> A: Try this instead. You have some incorrect escaping going on... The part in particular is around your onClick in the first line of the case case 'This Websense category is filtered: <b>Uncategorized</b>.': document.getElementById('helpDiv').innerHTML='<p style="margin-left: 10px">Help:&nbsp;&nbsp;&nbsp;&nbsp;<INPUT TYPE="button" VALUE="Submit UNCATEGORIZED website to Websense" onClick="parent.location=\'mailto:[email protected]?subject=Uncategorized Website&body=Please review and correctly categorize the website that is listed below:%0A%0A' + $*WS_URL*$ + '%0A%0AThank you.\'"></p>\ <hr />\ <p style="margin-left: 64px">Clicking on the above button will open your mail client to send an e-mail to Websense for recategorization of the above site.</p>\ <p style="margin-left: 64px">You will receive a confirmation e-mail and a case number from Websense indicating your request is proccessing.</p>\ <p style="margin-left: 64px">Please note the response time for your request will vary. Allow to three to four (3-4) hours for updates to take effect once approved.</p>\ <p style="margin-left: 64px">If you have any questions, please contact SOLV at <a href=tel:+18772097658>+1 877 209 7658<a/> or <a href=http://solv:8093/CAisd/pdmweb.exe?OP=JUST_GRONK_IT+HTMPL=about.htmpl target="_blank">this link.</a></p>'; break; UPDATE: Having just had a play in jsFiddle I have come to the conclusion that your reference to helpDiv is invalid.. If you replace all of these with some alerts your switch will reach the default. It's dying because there is something wrong with your getElementById. Maybe the element doesn't have the ID helpDiv? Here is a well and truly stripped down version http://jsfiddle.net/5wvC3/ Here is another fiddle - and update on the last one, showing that the code mostly works. You deff have an issue with your HTML http://jsfiddle.net/5wvC3/1/
[ "stackoverflow", "0059853684.txt" ]
Q: How can I check if if Google Map co-ordinates lie in London Congestion Zone? I am trying to check if google map co-ordinates lie in London Congestion Zone. How can I detect if the co-ordinates lie inside the boundary of London Congestion Zone or Is there any other way around. A: The congestion charge area is available in GeoJSON format from this site. https://data.cdrc.ac.uk/dataset/ccz You can import this data into Google Maps using map.data.loadGeoJson. Some example code can be found at: https://developers-dot-devsite-v2-prod.appspot.com/maps/documentation/javascript/examples/layer-data-simple You can then use map.geometry.poly.containsLocation from the map API to answer your question
[ "stackoverflow", "0012846784.txt" ]
Q: How do I set up my hosts and httpd.conf files using a static IP address I set Centos 6.3 up on a Rackspace box, using a static IP address (not a FQDN). I will be setting up virtual hosts on this box, and it seems to be working fine, but when I restart the HTTPD server, I get an error message "could not reliably determine the server's fully qualified domain name, using xx.xxx.xx.xx for ServerName" (xx.xxx.xx.xx is the static IP address for the server). My /etc/hosts has the following in it: 27.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6 xx.xxx.xx.xx name-used-for-rackspace name-used-for-racspace is a name (not a FQDN) I used when I created the server (you have to enter a name). I assume that I may not have to change anything in /etc/hosts, but what do I put in httpd.conf? right now, I have the following in that file: NameVirtualHost *:80 <VirtualHost *:80> DocumentRoot /var/www/html ServerName localhost <Directory /var/www/html> allow from all Options +Indexes </Directory> </VirtualHost> I also tried setting ServerName to xx.xxx.xx.xx, but I got the same error message. A: This error is because you are not using a FQDN. It should not affect the operation of the webserver. To get rid of the message on startup you'd need to configure your hosts file with the correct domain and IP address. Your httpd.conf should also use the same name (where you have localhost specified). As long as your server is starting and you don't plan on assigning a domain to your webserver, this error can be ignored. Example virtual host with FQDN: <VirtualHost *:80> ServerName www.domain.net ServerAlias domain.net *.domain.net ServerAdmin [email protected] DocumentRoot "/home/domain/htdocs" <Directory "/home/domain/htdocs"> Options Indexes FollowSymLinks AllowOverride All Order allow,deny Allow from all </Directory> CustomLog "/home/domain/logs/access-www.log" common ErrorLog "/home/domain/logs/error-www.log" <IfModule mpm_peruser_module> ServerEnvironment apache apache </IfModule> </VirtualHost> Example hosts file: 127.0.0.1 localhost localhost.localdomain gentoo1 x.x.x.x gentoo1.domain.net
[ "stackoverflow", "0043738717.txt" ]
Q: Trying to remove parent container of slide made by Slick Slider Plugin I have made a filter that hides a certain class in a slick slider based on the objects data-tag and the checkbox's value. When the class is hidden, it still leaves a blank space open because it should actually hide the parent container made by the slick slider. EXAMPLE - If you are on the first slide page and you select "Truck", the trucks will not show up. But if you go to the next page and select truck, you will see all the trucks. If I can just hide the parent container which is made by the plugin(See image below), the rest of the slides will fall into place and make the correct amount of slides and slide pages. I have added a image of the outputted slider structure with the class that has to be hidden - Screenshot I have inserted the plugin along with the filter. I have also made comments highlighting the objects that need to be dealt with. See snippet below - //MODEL FILTER FUNCTION $(document).ready(function(){ $('.mo-type-check').on('change', function(){ var category_list = []; $('#filters :input:checked').each(function(){ var category = $(this).val(); category_list.push(category); }); if(category_list.length == 0){ $('.resultblock').fadeIn(); } else { $('.resultblock').each(function(){ var item = $(this).attr('data-tag'); if(jQuery.inArray(item,category_list) > - 1) //Check if data-tag's value is in array $(this).fadeIn('slow'); else $(this).hide(); }); } }); }); $('.mo-slide').slick({ dots: true, infinite: false, rows: 2, speed: 300, slidesToShow: 4, slidesToScroll: 4, prevArrow: '<button type="button" data-role="none" class="slick-prev" aria-label="Previous" tabindex="0" role="button">▸</button>', nextArrow: '<button type="button" data-role="none" class="slick-next" aria-label="Next" tabindex="0" role="button">▸</button>', responsive: [ { breakpoint: 912, settings: { slidesToShow: 3, slidesToScroll: 3, infinite: false, dots: true } } ] }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.6.0/slick.js"></script> <link href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.6.0/slick.css" rel="stylesheet"/> <ul id="filters"> <li> <input id="check1" type="checkbox" name="check" value="convert" class="mo-type-check"> <label for="check1">Convertable</label> <label for="check1" class="selection"></label> </li> <li> <input id="check2" type="checkbox" name="check" value="hatch" class="mo-type-check"> <label for="check2">Hatchback</label> <label for="check2" class="selection"></label> </li> <li> <input id="check3" type="checkbox" name="check" value="sedan" class="mo-type-check"> <label for="check3">Sedan</label> <label for="check3" class="selection"></label> </li> <li> <input id="check4" type="checkbox" name="check" value="coupe" class="mo-type-check"> <label for="check4">Coupe</label> <label for="check4" class="selection"></label> </li> <li> <input id="check5" type="checkbox" name="check" value="suv" class="mo-type-check"> <label for="check5">SUV</label> <label for="check5" class="selection"></label> </li> <li> <input id="check6" type="checkbox" name="check" value="wag" class="mo-type-check"> <label for="check6">Wagon</label> <label for="check6" class="selection"></label> </li> <li> <input id="check7" type="checkbox" name="check" value="truck" class="mo-type-check"> <label for="check7">Truck</label> <label for="check7" class="selection"></label> </li> <li> <input id="check8" type="checkbox" name="check" value="van" class="mo-type-check"> <label for="check8">Van</label> <label for="check8" class="selection"></label> </li> </ul> <div class="mo-slide" id="mo-slide"> <div class="resultblock" data-tag="convert"> <img src="img/convert.png" class="mo-img"> <p class="mo-desc">Convertable</p> </div> <div class="resultblock" data-tag="hatch"> <img src="img/hatchback.png" class="mo-img"> <p class="mo-desc">Hacthback</p> </div> <div class="resultblock" data-tag="sedan"> <img src="img/sedan.png" class="mo-img"> <p class="mo-desc">Sedan</p> </div> <div class="resultblock" data-tag="coupe"> <img src="img/coupe.png" class="mo-img"> <p class="mo-desc">Coupe</p> </div> <div class="resultblock" data-tag="suv"> <img src="img/suv.png" class="mo-img"> <p class="mo-desc">SUV</p> </div> <div class="resultblock" data-tag="wag"> <img src="img/wagon.png" class="mo-img"> <p class="mo-desc">Wagon</p> </div> <div class="resultblock" data-tag="truck"> <img src="img/truck.png" class="mo-img"> <p class="mo-desc">Truck</p> </div> <div class="resultblock" data-tag="van"> <img src="img/van.png" class="mo-img"> <p class="mo-desc">Van</p> </div> <div class="resultblock" data-tag="truck"> <img src="img/truck.png" class="mo-img"> <p class="mo-desc">Truck</p> </div> <div class="resultblock" data-tag="van"> <img src="img/van.png" class="mo-img"> <p class="mo-desc">Van</p> </div> </div> A: Your containers have a min-height of 1px. Add the following CSS to reset it to 0. .slick-initialized .slick-slide { min-height: 0; } //MODEL FILTER FUNCTION $(document).ready(function(){ $('.mo-type-check').on('change', function(){ var category_list = []; $('#filters :input:checked').each(function(){ var category = $(this).val(); category_list.push(category); }); if(category_list.length == 0){ $('.resultblock').fadeIn(); } else { $('.resultblock').each(function(){ var item = $(this).attr('data-tag'); if(jQuery.inArray(item,category_list) > - 1) //Check if data-tag's value is in array $(this).fadeIn('slow'); else $(this).hide(); }); } }); }); $('.mo-slide').slick({ dots: true, infinite: false, rows: 2, speed: 300, slidesToShow: 4, slidesToScroll: 4, prevArrow: '<button type="button" data-role="none" class="slick-prev" aria-label="Previous" tabindex="0" role="button">▸</button>', nextArrow: '<button type="button" data-role="none" class="slick-next" aria-label="Next" tabindex="0" role="button">▸</button>', responsive: [ { breakpoint: 912, settings: { slidesToShow: 3, slidesToScroll: 3, infinite: false, dots: true } } ] }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.6.0/slick.js"></script> <link href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.6.0/slick.css" rel="stylesheet"/> <style> .slick-initialized .slick-slide { min-height: 0; } </style> <ul id="filters"> <li> <input id="check1" type="checkbox" name="check" value="convert" class="mo-type-check"> <label for="check1">Convertable</label> <label for="check1" class="selection"></label> </li> <li> <input id="check2" type="checkbox" name="check" value="hatch" class="mo-type-check"> <label for="check2">Hatchback</label> <label for="check2" class="selection"></label> </li> <li> <input id="check3" type="checkbox" name="check" value="sedan" class="mo-type-check"> <label for="check3">Sedan</label> <label for="check3" class="selection"></label> </li> <li> <input id="check4" type="checkbox" name="check" value="coupe" class="mo-type-check"> <label for="check4">Coupe</label> <label for="check4" class="selection"></label> </li> <li> <input id="check5" type="checkbox" name="check" value="suv" class="mo-type-check"> <label for="check5">SUV</label> <label for="check5" class="selection"></label> </li> <li> <input id="check6" type="checkbox" name="check" value="wag" class="mo-type-check"> <label for="check6">Wagon</label> <label for="check6" class="selection"></label> </li> <li> <input id="check7" type="checkbox" name="check" value="truck" class="mo-type-check"> <label for="check7">Truck</label> <label for="check7" class="selection"></label> </li> <li> <input id="check8" type="checkbox" name="check" value="van" class="mo-type-check"> <label for="check8">Van</label> <label for="check8" class="selection"></label> </li> </ul> <div class="mo-slide" id="mo-slide"> <div class="resultblock" data-tag="convert"> <img src="img/convert.png" class="mo-img"> <p class="mo-desc">Convertable</p> </div> <div class="resultblock" data-tag="hatch"> <img src="img/hatchback.png" class="mo-img"> <p class="mo-desc">Hacthback</p> </div> <div class="resultblock" data-tag="sedan"> <img src="img/sedan.png" class="mo-img"> <p class="mo-desc">Sedan</p> </div> <div class="resultblock" data-tag="coupe"> <img src="img/coupe.png" class="mo-img"> <p class="mo-desc">Coupe</p> </div> <div class="resultblock" data-tag="suv"> <img src="img/suv.png" class="mo-img"> <p class="mo-desc">SUV</p> </div> <div class="resultblock" data-tag="wag"> <img src="img/wagon.png" class="mo-img"> <p class="mo-desc">Wagon</p> </div> <div class="resultblock" data-tag="truck"> <img src="img/truck.png" class="mo-img"> <p class="mo-desc">Truck</p> </div> <div class="resultblock" data-tag="van"> <img src="img/van.png" class="mo-img"> <p class="mo-desc">Van</p> </div> <div class="resultblock" data-tag="truck"> <img src="img/truck.png" class="mo-img"> <p class="mo-desc">Truck</p> </div> <div class="resultblock" data-tag="van"> <img src="img/van.png" class="mo-img"> <p class="mo-desc">Van</p> </div> </div>
[ "stackoverflow", "0031910947.txt" ]
Q: How to reuse the submodule in Gradle? I have two following Android Studio project, structure like this: projectA/ ├----build.gradle ├----settings.gradle ├----bluewhale/ ├----krill/ projectA settings.gradle file:include 'bluewhale', 'krill' projectB/ ├----build.gradle ├----settings.gradle ├----hello/ ├----krill/ projectB settings.gradle file:include 'hello', 'krill' You can see "projectA" and "projectB" contain the same module "krill". Actually, it's a library project. My question is: how to reuse the submodule "krill" in Gradle? I don't want to include the same copy of "krill" in every project Looking forward to your reply! Thanks! A: If you have a sub-module that is used in multiple projects, you should think about extracting it to a separate project. Then you can create a dependency out of it and include it in both projects in dependencies section. If you only use your local machine for development, without any custom repository, the best way would probably be to use the mavenLocal() repository. You can use the maven publish plugin to publish your jar into the local maven repository. It should be as simple as adding this to the new krill: apply plugin: 'maven' apply plugin: 'maven-publish' publishing { publications { maven(MavenPublication) { from components.java artifact sourceJar { classifier "sources" } } } } repositories { mavenLocal() } You might want to set the group and artifact ID. See the documentation for more info. You can also keep krill in one of the projects, let's say ProjectA, if it has some relation to it. Then you set up the maven publishing in the krill sub-module. You can also publish to maven local by running gradle :krill:publishToMavenLocal and then use it as dependency in ProjectB. Another option is to save the submodule outside the projectA and projectB trees and add it using something like this: include("krill") project(":krill") { projectDir = new File("$settingsDir/../krill") } But I can't recommend this because it's hacky and your IDE might have a problem with it too. Last thing that might be possible is to create symlinks from a directory where your krill project is located to both ProjectA and ProjectB. But that is a really bad idea e.g. when you are using a version control.
[ "stackoverflow", "0016194362.txt" ]
Q: Shared Preferences issue, not freeing the value after calling clear In my application I want to clear SharedPreferences on button click. This is what I'm using for storing values in it: SharedPreferences clearNotificationSP = getSharedPreferences("notification_prefs", 0); SharedPreferences.Editor Notificationeditor = clearNotificationSP.edit(); Notificationeditor.putString("notificationCount", notificationCountValue); Notificationeditor.commit(); And the following code on onClick(): SharedPreferences clearedNotificationSP = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); SharedPreferences.Editor editorSP = clearedNotificationSP.edit(); editorSP.remove("notificationCount"); editorSP.commit(); System.out.println("Saved in SP clearedNotification: "+ clearNotification); I was printing the value after clearing it but still I was getting the same value. What am I missing? Any kind of help will be appreciated. A: getDefaultSharedPreferences and getSharedPreferences("notification_prefs", ); returns two different SharedPreferences. Since you are adding notificationCount inside notification_prefs, you should retrieve SharedPreference with getSharedPreferences("notification_prefs", ); getDefaultSharedPreferences uses a default preference-file name, while getSharedPreferences use the filename you provided as paramter
[ "stackoverflow", "0041673499.txt" ]
Q: How to upload multiple files to Firebase? Is there a way to upload multiple files to Firebase storage. It can upload single file within single attempt as follows. fileButton.addEventListener('change', function(e){ //Get file var file = e.target.files[0]; //Create storage reference var storageRef = firebase.storage().ref(DirectryPath+"/"+file.name); //Upload file var task = storageRef.put(file); //Update progress bar task.on('state_changed', function progress(snapshot){ var percentage = snapshot.bytesTransferred / snapshot.totalBytes * 100; uploader.value = percentage; }, function error(err){ }, function complete(){ var downloadURL = task.snapshot.downloadURL; } ); }); How to upload multiple files to the Firebase storage. A: I found the solution for my above question and I like to put it here because it can be useful for anyone. //Listen for file selection fileButton.addEventListener('change', function(e){ //Get files for (var i = 0; i < e.target.files.length; i++) { var imageFile = e.target.files[i]; uploadImageAsPromise(imageFile); } }); //Handle waiting to upload each file using promise function uploadImageAsPromise (imageFile) { return new Promise(function (resolve, reject) { var storageRef = firebase.storage().ref(fullDirectory+"/"+imageFile.name); //Upload file var task = storageRef.put(imageFile); //Update progress bar task.on('state_changed', function progress(snapshot){ var percentage = snapshot.bytesTransferred / snapshot.totalBytes * 100; uploader.value = percentage; }, function error(err){ }, function complete(){ var downloadURL = task.snapshot.downloadURL; } ); }); } A: Firebase Storage uses Promise, so you can use Promises to achieve it. Here's the firebase blog article that covers this subject: Keeping our Promises (and Callbacks) Give Promise.all() an "Array of Promises" Promise.all( // Array of "Promises" myItems.map(item => putStorageItem(item)) ) .then((url) => { console.log(`All success`) }) .catch((error) => { console.log(`Some failed: `, error.message) }); Upload each file and return a Promise putStorageItem(item) { // the return value will be a Promise return firebase.storage().ref("YourPath").put("YourFile") .then((snapshot) => { console.log('One success:', item) }).catch((error) => { console.log('One failed:', item, error.message) }); } YourPath and YourFile can be carried with myItems array (thus the item object). I omitted them here just for readability, but you get the concept. A: I believe there's a simpler solution: // set it up firebase.storage().ref().constructor.prototype.putFiles = function(files) { var ref = this; return Promise.all(files.map(function(file) { return ref.child(file.name).put(file); })); } // use it! firebase.storage().ref().putFiles(files).then(function(metadatas) { // Get an array of file metadata }).catch(function(error) { // If any task fails, handle this });
[ "stackoverflow", "0010586832.txt" ]
Q: Cloning C++ class with pure virtual methods I have the following relation of classes. I want to clone the class Derived, but I get the error "cannot instantiate abstract class". How I can clone the derived class? Thanks. class Base { public: virtual ~Base() {} virtual Base* clone() const = 0; }; class Derived: public Base { public: virtual void func() = 0; virtual Derived* clone() const { return new Derived(*this); } }; A: Only concrete classes can be instantiated. You have to redesign the interface of Derived in order to do cloning. At first, remove virtual void func() = 0; Then you will be able to write this code: class Base { public: virtual ~Base() {} virtual Base* clone() const = 0; }; class Derived: public Base { public: virtual Derived* clone() const { return new Derived(*this); } }; Another solution is keeping pure virtual function in-place and adding a concrete class: class Base { public: virtual ~Base() {} virtual Base* clone() const = 0; }; class Derived: public Base { public: virtual void func() = 0; }; class Derived2: public Derived { public: virtual void func() {}; virtual Derived2* clone() const { return new Derived2(*this); } }; A: You can not instantiate a class which has a pure virtual function like this: virtual void yourFunction() = 0 Make a subclass or remove it.
[ "stackoverflow", "0034130903.txt" ]
Q: Why does Angular repeat filter only have access to its element in the return function I have some Angular code which I have gotten to work but I don't understand why - being from a C Sharp background and new to JS and Typescript. <tr ng-repeat="colleague in Model.FilteredColleagueListModel | filter:Model.searchText(Model.SearchCriteria)" > public searchText(searchCriteria) { return function (item) { if (item.DisplayName.indexOf(searchCriteria) > -1 { return true; } return false; } }; And I have a filter but what I don't understand is the nested function. Why is item only available in the return function. Also is the returning function the right way to do it in TypeScript? Is it OK to ask slightly open ended questions like this? A: This works very similar to JavaScript 'array.filter()`, in fact i wouldn't be surprised if its using it under the hood. what's happening is your searchText method is accepting your search criteria and is called. The method it returns is called by angulars filter on every element in your collection, passing it that element. If you console.log(item); you will see it is not the whole array but each individual item. If your returned method returns true angular will keep that specific item, if it returns false angular will discard it. Exactly like the native filter. So your returned anonymous function is called not once, but for every item in your array. I can't comment on the syntax and mechanism with regards to TypeScript but returning a method is indeed to correct way to use this functionality, exactly like a native array.filter(). EDIT: Here's the Fiddle i used to make double sure of my comments if interested: http://jsfiddle.net/wf5shz70/ EDIT: @jonas made a very good and important point about statefull filters, i missed that.
[ "biology.stackexchange", "0000077533.txt" ]
Q: What kind of snake is this Found this outside on patio in northern Virginia, Ashburn area, September 2018. It's about 12 inches. Is it a water snake or rattlesnake? A: It looks like an Eastern Hognose Snake, which is characterized by an upturned nose and high likelihood of playing dead. These are described as variable in coloration: "Two color phases are common in Virginia: (1) a patterned phase (79.6%, n = 98), characterized by a series of 19-27 (average = 23.2 ± 2.4, n = 12) black or dark-brown blotches along middorsal line, with alternating black spots on sides; body color consists of varying combinations of gray, tan, pink, yellow, orange, and red; venter of body and tail immaculate cream to dark gray;" If you replace the tan in this image (www.virginiaherpetologicalsociety.com) with gray in yours, I think the pattern match and overall body form are very similar:
[ "movies.stackexchange", "0000072885.txt" ]
Q: Why didn't Lundy tell Debra he was close to retiring? In season 2 of Dexter, Debra meets and starts a relationship with Frank Lundy. This ends when Lundy goes to work his next case in Oregon. In season 4, Lundy is back in Miami having retired and is pursuing a case in his own time. My question is, why didn't Lundy tell Debra about his upcoming retirement plans to keep their relationship going? N.B. I am up to S4E1 Living the Dream, so please use spoiler tags where appropriate. A: At the point when Lundy moves to Oregon, he doesn't realize that a couple of years later he might find a case that brings him back to Miami (post retirement). He's just does the right thing to not drag on something which doesn't have a future. At that moment he needs to leave and they might have the option to work it long distance or simply call it off. A: I don't believe we were ever told when Lundy decided to retire. He may not have made the decision until after leaving for Oregon. It's certainly possible that his feelings after leaving could have lead to the decision to retire. However, that's supposition, not something I can back up with anything in-universe. A: why didn't Lundy tell Debra about his upcoming retirement plans to keep their relationship going? There's no indication that Lundy had already planned to retire! In season 2, Lundy seems to be in the heat of his career, tracking serial killers across the country and being assigned to one of the biggest serial killer cases in FBI history. He seemed to really enjoy what he was doing, and, IIRC, he rarely [if ever] complained about the job. That being said, IMO, Frank had no reservations of retiring during the events of season 2. In season 4 though, as the OP mentioned, Lundy has retired, and is now tracking his own case (and is back in Miami). Per this timeline of events, there's about a four year difference between season 2 and 4, and a lot can happen in four years. But, all in all, I don't think Frank ever had intentions of continuing things with Debra on a long term basis (I mean, his job heavily involves traveling, and this is a concern that Frank himself expressed). So, even if Frank was planning on retiring down the road, with him leaving Miami right after the BHB case, why would he tell Debra? In all probability, Frank didn't plan on seeing Debra again after the BHB case. In fact, when he returned to Miami in season 4, he had already been there some time before coincidentally running into her.
[ "stackoverflow", "0028983875.txt" ]
Q: how to make computed re-evaluate when dynamic I created a model that encapsulates filtering logic that I use on a lot of models but I'm having an issue were the isFiltering and clearFilterImg computed's only fire once because I'm dynamically evaluating each observable on the model in the isFiltering computed. Is there a way to get these computed's to re-evaluate even though I'm doing dynamic checking? Super secret internal Knockout API call or rewriting the computed in a different way perhaps..? var filterModel = (function () { function filterModel(parent) { var self = this; // needed for the "this" argument when calling the callback self.parent = parent; // this allows us to clear the filters and only kick off one ajax call regardless of how many filters are cleared at one time self.filterThrottle = ko.observable().extend({ throttle: 50 }); // not firing more than once because the observable properties are checked dynamically self.isFiltering = ko.computed(function () { console.log("isFiltering called"); var isFiltering = false; for (var property in self) { if (self.hasOwnProperty(property) && ko.isObservable(self[property]) && !ko.isComputed(self[property])) { if (self[property]()) { // dynamic property check isFiltering = true; break; } } } return isFiltering; }); // not firing more than once self.clearFilterImg = ko.computed(function () { console.log("clearFilterImg called"); if (self.isFiltering()) return "/content/images/clear-filter.png"; else return "/content/images/clear-filter-disabled.png"; }); } filterModel.prototype.clearFilters = function () { var self = this; for (var property in self) { if (self.hasOwnProperty(property) && ko.isObservable(self[property]) && !ko.isComputed(self[property])) { // only reset a property if it has a value if (self[property]()) { self.filterThrottle(externalbyte.createUUID()); self[property](null); } } } }; filterModel.prototype.subscribeToFilters = function (callback) { var self = this; // fires the callback that makes the ajax call self.filterThrottle.subscribe(function (newValue) { callback.call(self.parent, true); }); // subscribe to all observables for (var property in self) { if (self.hasOwnProperty(property) && ko.isObservable(self[property]) && !ko.isComputed(self[property])) { self[property].subscribe(function (newValue) { // update the throttling observable to a new random UUID when a filter changes self.filterThrottle(createUUID()); }); } } }; filterModel.prototype.createFilterObject = function (filter) { var self = this; for (var property in self) { if (self.hasOwnProperty(property) && ko.isObservable(self[property]) && !ko.isComputed(self[property])) { filter[property] = self[property](); } } return filter; }; return filterModel; })(); usage: function errorLogListModel() { var self = this; // create a new filter model self.filters = new filterModel(self); // add whatever filters I want self.filters.errorLogId = ko.observable(); self.filters.userId = ko.observable(); self.filters.userName = ko.observable(); self.getErrors = function(resetPage) { // make an ajax call to filter records }; // subscribe to any filter changes and call getErrors method self.filters.subscribeToFilters(self.getErrors); } A: After creating an isolated sample in jsfiddle I found the fix which is to set deferEvaluation to true for the computed's in question. self.isFiltering = ko.computed(function () { var isFiltering = false; for (var property in self) { if (self.hasOwnProperty(property) && ko.isObservable(self[property]) && !ko.isComputed(self[property])) { if (self[property]()) { isFiltering = true; break; } } } return isFiltering; }, self, { deferEvaluation: true }); // defer evaluation until the model is fully realized http://jsfiddle.net/StrandedPirate/rrkh66ha/27/
[ "math.stackexchange", "0002762531.txt" ]
Q: Finding an $\alpha$-Hölder continuous function $f_{\alpha}$ at $0$, but not $\beta$-Hölder. Assuming $\alpha\in(0,1]$, which function $f_\alpha:\mathbb{R}\rightarrow\mathbb{R}$ is $\alpha$-Hölder continuous at $0$, but not $\beta$-Hölder continuous for $\beta>\alpha$? I've been thinking about a function that somehow relates to $f_\alpha(t)\sim |t|^\alpha$, though I haven't been able to confirm that. Anyone that could come up with one? A: For the ease we can just search for $f_\alpha$ with $f_\alpha(0)=0$ so $|f_\alpha(t)-f_\alpha(0)|\leq M|t|^\alpha$ becomes $|f_\alpha(t)|\leq M|t|^\alpha$ (for some $M,\delta>0$ with $|t|<\delta$). Now $|t|^\alpha$ is indeed a correct candidate for $\alpha$-Hölder continuity by choosing $M,\delta=1$. Now we need to show that $f_\alpha$ is not $\beta$-Hölder continuous, that is, we have $|f_\alpha(t)|> M|t|^\beta$ for any $M,\delta>0$ and some $|t|<\delta$. So we find $$|t|^\alpha> M|t|^\beta\iff |t|^{\beta-\alpha}< \frac{1}{M}\iff |t|< \left(\frac{1}{M}\right)^\frac{1}{\beta-\alpha}$$ Therefore $t=\frac{1}{2}\min\{\delta,\left(\frac{1}{M}\right)^\frac{1}{\beta-\alpha}\}$ will do.
[ "math.stackexchange", "0002209265.txt" ]
Q: Why is the integral of a parabola between its two roots always equals to twice the integral between a root and half the root separation? I came across an interesting relationship today, which I assume to be related to symmetry and the fact that all parabolas are a transformation of $y=x^2$. However, I am unable to prove it for the general case and would be interested to know more information or where I can find it. Here is the maths (excuse my notation, I'm still new to this!): Assume a parabola with roots $a$ and $b$. $\int_a^b \!f(x)$ = $\int_b^y \! f(x)$ where $y=b+\frac{b - a}{2}$ (assuming absolute value, the geometric area, and therefore ignoring any positive/negative signs). Any ideas? I'm interested to know how this can be proven to be the case and what it shows geometrically. A: Note that your integrals will generally have opposite sign. I will show that their absolute values are equal. Suppose first that $f(x)=x^2-b^2$ with $b>0$. Then $$ \int_{-b}^b f(x) \, dx = \left[\frac{x^3}{3}-b^2x\right]_{-b}^b=\frac{2b^3}{3}-2b^3=-\frac{4b^3}{3} $$ and $$ \int_b^{2b} f(x) \, dx = \left[\frac{x^3}{3}-b^2x\right]_b^{2b}=\frac{7b^3}{3}-b^3=\frac{4b^3}{3} $$ and so the claim is true for this special case. In general, if $f$ has roots $a$ and $b$, then $$f(x)=k(x-a)(x-b)=k\left[\left(x-\frac{b+a}{2}\right)^2-\left(\frac{b-a}{2}\right)^2\right]$$ We know by the argument above that the two areas are equal for the polynomial $$ g_1(x)=x^2-\left(\frac{b-a}{2}\right)^2 $$ Since shifting horizontally preserves area, they are also equal for the polynomial $$ g_2(x)=g_1\!\left(x-\frac{b+a}{2}\right)=\left(x-\frac{b+a}{2}\right)^2-\left(\frac{b-a}{2}\right)^2 $$ Since scaling vertically preserves the ratios of areas, this finally means that they are equal for the polynomial $$ f(x)=kg_2(x)=k\left[\left(x-\frac{b+a}{2}\right)^2-\left(\frac{b-a}{2}\right)^2\right] $$ which establishes the claim for general quadratic functions with real roots. (Of course, you could also compute this integral for general $f$, but it'd be messier...)
[ "stackoverflow", "0040010461.txt" ]
Q: Vim: Delay after hitting gg There is about a half second delay after I gg, which is extremely annoying. Other commands such as Shift-G work instantaneously, but with gg, I think there may be something in my .vimrc where vim is expecting another input. My .vimrc is below if that helps. Thanks. call plug#begin('~/.vim/plugged') "Plug 'valloric/youcompleteme' Plug 'scrooloose/syntastic' Plug 'tpope/vim-rails' Plug 'vim-ruby/vim-ruby' "autocomplete Plug 'honza/vim-snippets' Plug 'garbas/vim-snipmate' Plug 'ervandew/supertab' Plug 'MarcWeber/vim-addon-mw-utils' Plug 'tomtom/tlib_vim' Plug 'tpope/vim-surround' Plug 'tpope/vim-endwise' Plug 'tpope/vim-repeat' "comments Plug 'scrooloose/nerdcommenter' Plug 'tpope/vim-commentary' Plug 'kien/ctrlp.vim' Plug 'wakatime/vim-wakatime' Plug 'Yggdroot/indentLine' Plug 'terryma/vim-multiple-cursors' Plug 'itchyny/lightline.vim' Plug 'matze/vim-move' Plug 'jacoborus/tender' Plug 'craigemery/vim-autotag' Plug 'flazz/vim-colorschemes' Plug 'jiangmiao/auto-pairs' Plug 'justinmk/vim-syntax-extra' Plug 'svermeulen/vim-easyclip' call plug#end() " toby vim set expandtab set tabstop=4 set softtabstop=4 set shiftwidth=4 set backspace=indent,eol,start set mouse=a set statusline+=%f set number set linebreak set ruler set showcmd set smartcase set laststatus=2 set incsearch " search as characters are entered set foldenable " enable folding nnoremap E ^ " Line Numbers set number set relativenumber augroup lineNums autocmd! autocmd InsertEnter * set norelativenumber autocmd InsertLeave * set relativenumber augroup END " Copy Paste to System Clipboard set clipboard=unnamed let mapleader="g" "for nerdcommenter nnoremap gcc :call NERDComment(0,"toggle")<CR> filetype plugin on " If you have vim >=8.0 or Neovim >= 0.1.5 if (has("termguicolors")) set termguicolors endif " Theme syntax enable set background=dark colorscheme molokai let t_Co=256 " set lighline theme inside lightline config " let g:lightline = { 'colorscheme': 'wombat' } "vim-move let g:move_key_modifier = 'C' " syntastic settings set statusline+=%#warningmsg# set statusline+=%{SyntasticStatuslineFlag()} set statusline+=%* let g:syntastic_always_populate_loc_list = 1 let g:syntastic_auto_loc_list = 1 let g:syntastic_check_on_open = 1 let g:syntastic_check_on_wq = 0 " :ca off SyntasticToggleMode :ca WQ wq :ca Wq wq :ca wQ wq A: I don't think you need to look further than: let mapleader="g" "for nerdcommenter Since nerdcommenter defines a whole bunch of <leader> mappings, every time you press g Vim is going to wait a bit in order to decide if you wanted g or one of your many mappings starting with g. g is a very bad <leader>, you should find an alternative.
[ "stackoverflow", "0020934591.txt" ]
Q: How to write an asynchronous for-each loop in Express.js and mongoose? I have a function that returns an array of items from MongoDB: var getBooks = function(callback){ Comment.distinct("doc", function(err, docs){ callback(docs); } }); }; Now, for each of the items returned in docs, I'd like to execute another mongoose query, gather the count for specific fields, gather them all in a counts object, and finally pass that on to res.render: getBooks(function(docs){ var counts = {}; docs.forEach(function(entry){ getAllCount(entry, ...){}; }); }); If I put res.render after the forEach loop, it will execute before the count queries have finished. However, if I include it in the loop, it will execute for each entry. What is the proper way of doing this? A: I'd recommend using the popular NodeJS package, async. It's far easier than doing the work/counting, and eventual error handling would be needed by another answer. In particular, I'd suggest considering each (reference): getBooks(function(docs){ var counts = {}; async.each(docs, function(doc, callback){ getAllCount(entry, ...); // call the `callback` with a error if one occured, or // empty params if everything was OK. // store the value for each doc in counts }, function(err) { // all are complete (or an error occurred) // you can access counts here res.render(...); }); }); or you could use map (reference): getBooks(function(docs){ async.map(docs, function(doc, transformed){ getAllCount(entry, ...); // call transformed(null, theCount); // for each document (or transformed(err); if there was an error); }, function(err, results) { // all are complete (or an error occurred) // you can access results here, which contains the count value // returned by calling: transformed(null, ###) in the map function res.render(...); }); }); If there are too many simultaneous requests, you could use the mapLimit or eachLimit function to limit the amount of simultaneous asynchronous mongoose requests. A: forEach probably isn't your best bet here, unless you want all of your calls to getAllCount happening in parallel (maybe you do, I don't know — or for that matter, Node is still single-threaded by default, isn't it?). Instead, just keeping an index and repeating the call for each entry in docs until you're done seems better. E.g.: getBooks(function(docs){ var counts = {}, index = 0, entry; loop(); function loop() { if (index < docs.length) { entry = docs[index++]; getAllCount(entry, gotCount); } else { // Done, call `res.render` with the result } } function gotCount(count) { // ...store the count, it relates to `entry`... // And loop loop(); } }); If you want the calls to happen in parallel (or if you can rely on this working in the single thread), just remember how many are outstanding so you know when you're done: // Assumes `docs` is not sparse getBooks(function(docs){ var counts = {}, received = 0, outstanding; outstanding = docs.length; docs.forEach(function(entry){ getAllCount(entry, function(count) { // ...store the count, note that it *doesn't* relate to `entry` as we // have overlapping calls... // Done? --outstanding; if (outstanding === 0) { // Yup, call `res.render` with the result } }); }); });