id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_4800
how can I do this? And I don't want to use any editor. A: Not possible, textarea is a plain text input control. You need to allow rich-text/mark-up interpreted correctly using WYSIWYG editor textarea The TEXTAREA element creates a multi-line text input control. User agents should use the contents of this element as the initial value of the control and should render this text initially. A: Use html_entities of php $textarea_code = htmlentities($_REQUEST['text_area_name']); $b = html_entity_decode($textarea_code); $textarea = mysql_real_escape_string($b); echo $textarea;
doc_4801
I have a collection with a list of documents, and those documents further have many fields each. I have an API for accessing the documents, which returns a list of the details in each document. But, I want to access the document id of each document. How to do that? A: If you write such a query you can have every documentId of your documents. _getDocuments() async { await _firestore.collection("yourCollection").getDocuments(). then((myDocuments) { for (DocumentSnapshot eachDocument in myDocuments.documents) { print(eachDocument.documentID); } } }); }
doc_4802
I have tried to install python-igraph for older versions from anaconda cloud but a version problem occurs. !conda install -c vtraag python-igraph Fetching package metadata ............. Solving package specifications: . UnsatisfiableError: The following specifications were found to be in conflict: - python 3.6* - python-igraph -> python 3.5* Use "conda info <package>" to see the dependencies for each package.` I know that python-igraph exists for older python versions, but I don't want to overwrite the current python 3.6 version, so I think I need a new environment to install the older version and be able to use both. I have already tried to create a new environment for python 3.5: !conda create -n py35 python=3.5 ipykernel But after 30min I didn't obtain any response... I have also followed the same procedure to install a package for python 2.7 (from marufr contributor), but I get the same problem creating an environment for python 2.7. Note: I am working from Jupyter notebook on Windows (win-64) and using Anaconda. Update: Solution found here: https://medium.com/towards-data-science/environment-management-with-conda-python-2-3-b9961a8a5097 Since there is no python-igraph for python 3.6 yet, I have to use an older version. First, from Anaconda Prompt, install the nb_conda_kernels package before creating the new environment: conda install nb_conda_kernels Then, create the environment where I will work with the older python version: conda create -n py35 python=3.5 ipykernel Finally, install the package through the wheel (found here: http://www.lfd.uci.edu/~gohlke/pythonlibs/#python-igraph) pip install python_igraph‑0.7.1.post6‑cp35‑none‑win_amd64.whl (You have to this command in the same folder that you donwloaded the wheel!) A: There is a Windows installer for igraph‘s Python interface on the Python Package Index. Download the one that is suitable for your Python version (currently there are binary packages for Python 2.6, Python 2.7 and Python 3.2, though it might change in the future). To test the installed package, launch your favourite Python IDE and type the following: import igraph.test igraph.test.run_tests() The above commands run the bundled test cases to ensure that everything is fine with your igraph installation. A: Now, you can download 'python_geohash‑0.8.5‑cp36‑cp36m‑win_amd64.whl'. Use the following command to install: pip install python_geohash‑0.8.5‑cp36‑cp36m‑win_amd64.whl Then you can use python-igraph in your Python3.6
doc_4803
$subscriptionName = "***" $clusterName = "***" $queryString = "SELECT city FROM logs WHERE city =""New York"";" Use-AzureHDInsightCluster $clusterName Invoke-Hive -Query $queryString But I am not able to use Quotes in following PowerShell Comamnds - $subscriptionName = "***" $storageAccountName = "***" $containerName = "***" $clusterName = "***" $queryString = "SELECT city FROM logs WHERE city =""New York"";" $hiveJobDefinition = New-AzureHDInsightHiveJobDefinition -Query $queryString Select-AzureSubscription $subscriptionName $hiveJob = Start-AzureHDInsightJob -Cluster $clusterName -JobDefinition $hiveJobDefinition Wait-AzureHDInsightJob -Job $hiveJob -WaitTimeoutInSeconds 36000 Get-AzureHDInsightJobOutput -Cluster $clusterName -JobId $hiveJob.JobId -StandardOutput It is giving me following error - Please give me some information why is this sporadic behavior. Both implementations creates jobs, then why one implementation accepting double quotes and other not. A: Try a couple of alternate ways of quoting your query to see if you get any further: Single Quotes $queryString = 'SELECT city FROM logs WHERE city ="New York";' Backtick Escape $queryString = "SELECT city FROM logs WHERE city =`"New York`";" My guess is that it is the way that Start-AzureHDInsightJob is interpreting the string differently. Update 1 Sorry to hear the above didn't work, maybe try (single quote string): $queryString = "SELECT city FROM logs WHERE city ='New York';" Update 2 Looking at New-AzureHDInsightHiveJobDefinition you haven't specified a job name, if you don't specify a job name then the following applies: The name of the Hive job being defined. If the name is not specified, it is "Hive: <first 100 characters of Query>" by default. So your job name will contain your query, try specifying a job name to see if that helps.
doc_4804
I just installed Apache, php and MySQL on a VPS. Then I had to install PostgreSQL and set up a database and a new user. After running the psql command, I got the following output: psql: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? So, my question is how do I fix this. I'd be grateful if I receive some feedback.
doc_4805
I have one template and navigation like (Read, Dont Read). Problem is that I see all posts (when I must see posts with flagged false or flagged true), and I dont understand why, I think problem in publish/subscribe Router.configure({ layoutTemplate: 'layout', loadingTemplate: 'loading', }); AllPostsController = RouteController.extend({ template: 'timeTable', waitOn: function() { return Meteor.subscribe('allPosts'); } }); readPostController = AllPostsController.extend({ waitOn: function() { return Meteor.subscribe('readPosts'); } }); dontreaderPostController = AllPostsController.extend({ waitOn: function() { return Meteor.subscribe('dontreadPosts'); } }); Router.map(function() { this.route('timeTable', {path: '/', controller: AllPostsController }); this.route('readPosts', {path: '/read', controller: readPostsController }); this.route('dontreaderPosts', { path: '/dontreader', controller: dontreaderPostController }); }); Meteor.publish('allPosts', function(){ return Posts.find({},{ sort: { createdAt: -1 }}); }); Meteor.publish('readPosts', function(){ return Posts.find({read:true},{ sort: { createdAt: -1 }}); }); Meteor.publish('dontreadPosts', function(){ return Posts.find({read:false},{ sort: { createdAt: -1 }}); }); If someone need more code, Just ask me Anybody help EDIT : David solved problem for regular tasks. Main problem that I have specific return Posts.find(...) in my tamplate helper. <template name="timeTable"> {{#if posts_exist_week}} {{> table posts=week}} {{/if}} {{#if posts_exist_month}} {{> table posts=month}} {{/if}} </template> <template name="table"> <table class="main-table table"> {{#each posts}} {{> post}} {{/each}} </table> </template> You solved my problem if I did not have template timeTable (that show posts for last week and month) Because here it Template helper Template.timeTable.helpers({ week: function() { //... return Posts.find({createdAt: {$gte: weekstart, $lt: yesterday}},{ sort: { createdAt: -1 }}); //return posts that was created in this week }, month: function() { //... return Posts.find({createdAt: {$gte: monthstart, $lte: weekstart}},{ sort: { createdAt: -1 }}); } }); And now you see that if I choose your decision (David) I will have 2 !! return first - in router second - in template helper A: I recreated this locally and found that extend causes the parent controller's waitOn to run. So whenever you go to the /read route it will actually activate both subscriptions and you'll end up with all of the documents on your client. A simple fix is to refactor your controllers like so: PostController = RouteController.extend({ template: 'timeTable' }); AllPostsController = PostController.extend({ waitOn: function() { return Meteor.subscribe('allPosts'); } }); readPostController = PostController.extend({ waitOn: function() { return Meteor.subscribe('readPosts'); } }); dontreaderPostController = PostController.extend({ waitOn: function() { return Meteor.subscribe('dontreadPosts'); } }); That being said, you don't want to build your app in a way that it breaks when extra subscriptions happen to be running. I would rewrite the controllers to select only the documents that pertain to them. For example: dontreaderPostController = PostController.extend({ waitOn: function() { return Meteor.subscribe('dontreadPosts'); }, data: {selector: {read: false}} }); And now your helpers can use the selector like this: Template.timeTable.helpers({ week: function() { var selector = _.clone(this.selector || {}); selector.createdAt = {$gte: weekstart, $lt: yesterday}; return Posts.find(selector, {sort: {createdAt: -1}}); } }); Also note that sorting in the publish functions may not be useful - see common mistakes.
doc_4806
uty4014 access module error 35 received during 'comm_pmreadddparse' operation:'Unable to determine EOR for the datafile !ERROR! Could not find a valid EOR'. Also providing the mload script: .logtable ALL_wkSCRATCHPAD_DB.Coverage_log; .logmech ldap; .logdata authcid= password=; .LOGON tdip/; DROP Table ALL_WKSCRATCHPAD_DB.Coverage; DROP Table ALL_WKSCRATCHPAD_DB.error_1; DROP Table ALL_WKSCRATCHPAD_DB.error_2; DROP Table ALL_WKSCRATCHPAD_DB.Coverage_WK; CREATE SET TABLE ABCD_DB.Coverage ( COVG_KEY VARCHAR(50), TRANSACTION_TYPE VARCHAR(20), POLICY_NUMBER VARCHAR(18), PRODUCER VARCHAR(17), AGENT_NAME VARCHAR(64), TRANSACTION_PROCESS_DATE VARCHAR(20), ENDORSEMENT_EFFECTIVE_DATE VARCHAR(10), ENDORSEMENT_EXPIRATION_DATE VARCHAR(10), POLICY_EFFECTIVE_DATE VARCHAR(10), POLICY_EXPIRATION_DATE VARCHAR(10), LINE_OF_BUSINESS VARCHAR(10), STATE VARCHAR(2), PREMIUM_AMOUNT VARCHAR(20), COMPANY VARCHAR(32), NAICS_CODE VARCHAR(6), GL_CLASS_CODE VARCHAR(5), BUSINESS_CLASS_DESCRIPTION VARCHAR(64), PARTY_NAME VARCHAR(64), PARTY_TYPE_CD VARCHAR(16), BUSINESS_PHONE VARCHAR(10), BL_STREET_ADDRESS_LINE_1 VARCHAR(64), BL_STREET_ADDRESS_LINE_2 VARCHAR(64), BL_STREET_ADDRESS_LINE_3 VARCHAR(32), BL_COUNTRY VARCHAR(32), BL_STATE VARCHAR(2), BL_CITY VARCHAR(64), BL_ZIP VARCHAR(10), BL_COUNTY VARCHAR(32), STATUS_CD VARCHAR(3), QUOTE_CREATED_DATE VARCHAR(20) ); .BEGIN IMPORT MLOAD TABLES ALL_WKSCRATCHPAD_DB.Coverage WORKTABLES ALL_WKSCRATCHPAD_DB.Coverage_WK ERRORTABLES ALL_wkSCRATCHPAD_DB.error_1 ALL_wkSCRATCHPAD_DB.error_2 SESSIONS 5; .LAYOUT INPUT_RECORD; .FIELD COVG_KEY * VARCHAR(50); .FIELD TRANSACTION_TYPE * VARCHAR(20); .FIELD POLICY_NUMBER * VARCHAR(18); .FIELD PRODUCER * VARCHAR(17); .FIELD AGENT_NAME * VARCHAR(64); .FIELD TRANSACTION_PROCESS_DATE * VARCHAR(6); .FIELD ENDORSEMENT_EFFECTIVE_DATE * VARCHAR(10); .FIELD ENDORSEMENT_EXPIRATION_DATE * VARCHAR(10); .FIELD POLICY_EFFECTIVE_DATE * VARCHAR(10); .FIELD POLICY_EXPIRATION_DATE * VARCHAR(10); .FIELD LINE_OF_BUSINESS * VARCHAR(10); .FIELD STATE * VARCHAR(2); .FIELD PREMIUM_AMOUNT * VARCHAR(20); .FIELD COMPANY * VARCHAR(32); .FIELD NAICS_CODE * VARCHAR(6); .FIELD GL_CLASS_CODE * VARCHAR(5); .FIELD BUSINESS_CLASS_DESCRIPTION * VARCHAR(64); .FIELD PARTY_NAME * VARCHAR(64); .FIELD PARTY_TYPE_CD * VARCHAR(16); .FIELD BUSINESS_PHONE * VARCHAR(10); .FIELD BL_STREET_ADDRESS_LINE_1 * VARCHAR(64); .FIELD BL_STREET_ADDRESS_LINE_2 * VARCHAR(64); .FIELD BL_STREET_ADDRESS_LINE_3 * VARCHAR(32); .FIELD BL_COUNTRY * VARCHAR(32); .FIELD BL_STATE * VARCHAR(2); .FIELD BL_CITY * VARCHAR(64); .FIELD BL_ZIP * VARCHAR(10); .FIELD BL_COUNTY * VARCHAR(32); .FIELD STATUS_CD * VARCHAR(3); .FIELD QUOTE_CREATED_DATE * VARCHAR(10); .DML LABEL insdml; insert into ALL_WKSCRATCHPAD_DB.Coverage ( COVG_KEY ,TRANSACTION_TYPE ,POLICY_NUMBER ,PRODUCER ,AGENT_NAME ,TRANSACTION_PROCESS_DATE ,ENDORSEMENT_EFFECTIVE_DATE ,ENDORSEMENT_EXPIRATION_DATE ,POLICY_EFFECTIVE_DATE ,POLICY_EXPIRATION_DATE ,LINE_OF_BUSINESS ,STATE ,PREMIUM_AMOUNT ,COMPANY ,NAICS_CODE ,GL_CLASS_CODE ,BUSINESS_CLASS_DESCRIPTION ,PARTY_NAME ,PARTY_TYPE_CD ,BUSINESS_PHONE ,BL_STREET_ADDRESS_LINE_1 ,BL_STREET_ADDRESS_LINE_2 ,BL_STREET_ADDRESS_LINE_3 ,BL_COUNTRY ,BL_STATE ,BL_CITY ,BL_ZIP ,BL_COUNTY ,STATUS_CD ,QUOTE_CREATED_DATE ) values ( :COVG_KEY ,:TRANSACTION_TYPE ,:POLICY_NUMBER ,:PRODUCER ,:AGENT_NAME ,:TRANSACTION_PROCESS_DATE ,:ENDORSEMENT_EFFECTIVE_DATE ,:ENDORSEMENT_EXPIRATION_DATE ,:POLICY_EFFECTIVE_DATE ,:POLICY_EXPIRATION_DATE ,:LINE_OF_BUSINESS ,:STATE ,:PREMIUM_AMOUNT ,:COMPANY ,:NAICS_CODE ,:GL_CLASS_CODE ,:BUSINESS_CLASS_DESCRIPTION ,:PARTY_NAME ,:PARTY_TYPE_CD ,:BUSINESS_PHONE ,:BL_STREET_ADDRESS_LINE_1 ,:BL_STREET_ADDRESS_LINE_2 ,:BL_STREET_ADDRESS_LINE_3 ,:BL_COUNTRY ,:BL_STATE ,:BL_CITY ,:BL_ZIP ,:BL_COUNTY ,:STATUS_CD ,:QUOTE_CREATED_DATE ); .IMPORT INFILE '/home/adepum2/ABDC.txt' FORMAT VARTEXT '|' display errors NOSTOP LAYOUT INPUT_RECORD APPLY insdml; .END MLOAD; .LOGOFF; My txt file looks like: ||ACP 3008641853|00055050-140|JOHN RUSSELL MORAN|02/06/2018 08:52:00|||||GL||13538.00||||||||265 Buckingham Ct|||||ILSchaumburg|601932084||||02/06/2018 08:33:00 I have tried to look for any Regex in my text file but not able to find it. Your help would be really appreciated. Thanks, phantom A: I finally solved the issue. The issue was about the file type and also with the EOR it was LF not CRLF. I made changes to it and the only file type it was accepting was .DAT. I m not sure why the .DAT file type is being accepted only not the other types. Thanks guys for your suggestions and spending your valuable time.
doc_4807
Definitions: * *Forum: a collection of discussion threads (e.g. "Questions and Answers") *Thread: a collection of posts on a particular topic (e.g. "What is the meaning of life, the universe, and everything?") *Post: contains the body of a message. (e.g. "Duh... it's 42") Model Design: Here's my initial draft for modeling my entities. In this model, forums are the root. Forums can contain zero or more threads, and threads can contain 1 or more posts. For sake of this question, I have kept things as simple as possible. Here are my service classes: Here's what the database schema looks like: To create my objects, I am using my interpretation of the Data Mapper Pattern to translate data from the database into entity objects. The layered architecture looks like this: Here's where things get a little complex: My understanding of good OOP design is that entities shouldn't really have to deal with things like "foreign keys", because those are data persistence concerns. Instead, entities should reference the actual object that the "foreign key" represents. Therefore I want to make sure my child entities (Thread and Post) have references to their parents. This way, when it comes time to persisting them, the data mapper layer can infer the foreign keys by calling a method like this in a Post object. : // get the primary key from the parent object and return it function getThreadId() { return thread.getThreadId(); } One of the problems I've run into is determining when I should inject references to parent objects into the entities. Approach 1: My instincts tell me that the Data Mapper layer should be responsible for this behavior. Here's a simplified version of what the build() method might look like in the Post data mapper: // build a post entity function build( required postId ) { // go out to the database and get our dto var dto = dao.getById( postId ); // initialize the entity var post = new post( dto.postId, dto.body ); // inject a reference to the parent object (thread) post.setThread( threadDataMapper.getById( dto.threadId ) ); return post; } I see a few problems with this approach: * *I've read that in OOP child objects shouldn't really know about their parents and that parents should be responsible for injecting soft references to their children, not the other way around. *The approach above feels inefficient because each entity has to go out and get a copy of its parent on every new() instance. If I have a controller that gets a Thread entity, the data mapper has to instance both a new Thread and a Forum (2 trips to the database). If I then need to get a Post from that Thread via getPostById(), I have to instance the Post, and then re-instance the Thread and Forum again (3 trips to the database). That just smells terrible to me. Approach 2: Another idea I had was to have my parent entities inject themselves into their respective children. So for example, a Thread might do this when getting a Post: // Get a post by id function getPostById( id ) { // get the post entity from the service layer var post = postService.getById( arguments.id ); // inject a reference of this thread into the post post.setThread( this ); return post; } This feels a little better! However, the main caveat I've run into is if you want to directly access a Post in the application. Let's say for example you want to have a page for editing a Post. Since the only way to properly construct a post is to go through its Thread (and the only way to construct a Thread is through its Forum) I have to make my controller do a lot more work just to get an instance of a particular Post. This seems like adding a lot of complexity just so I can access a single entity so I can edit it. Approach 3: Finally, perhaps the simplest approach would be to keep Forum entities, Thread entities, and Post entities completely separate and include their foreign keys as object properties. However, this approach seems like I'm just using the entities as fancy DTOs as they just hold data and don't contain any business logic: Approach 4: ??? So that's where I am at as of today. Perhaps I'm going about solving this problem all wrong, or maybe there's a pattern that exists already for this type of model that I'm not aware of. Any help or insight you could offer would be most appreciated! A: I'm not the guru of OOP design but I guess the answer heavily depends on your app logic. I think first of all you have to consider your objects as an entity that keeps own internal data in consistency. E.g., if the Post does not need to know to which thread it belongs in order to update own 'title' and 'body' properties than it should not keep the thread reference at all. Thread as a posts container should have some sort of reference to the posts. As the next step let's say we want to improve thread search performance (for the given post find it's parent thread). Or Post internal consistency starts depends on thread (e.g. when thread is blocked Post body could not be updated). Post in such case may contain reference to the parent thread (by id or by the instance). There are supporters and opponents of how to store the reference. Related to creation I guess all entities should have own factories. What instances would be instantiated during creation depends on how you choose to store reference. Whatever variant you choose it may work for some time until Post starts to depend on too many classes (Thread, Author, List of Best Posts). To keep own consistency post should have the reference to all those classes which expose a lot of external information. That is the time when we have to close Post for modification. All post rules that depends on external objects post should take as a dependency during initialization.
doc_4808
https://wrapbootstrap.com/ A: Almost every theme is different on how to integrate within your project/site but every theme I have purchased has come with a good amount of documentation. The best way to get information on how to use your purchased theme is by reading the documentation that came with it.
doc_4809
1) divId_1 2) divId_2 4) divId_3 5) divId_4 6) divId_5 than how I can apply onclick event for div's which would work for all the div's using javascript in jquery I am sure how to achieve this but not sure how to do this javascript . like in jquery we can do as below $('[id^="divId_"]').click(function(){ }) same how we can achieve in javascript . A: This should work: for(var i = 0; i < document.querySelectorAll('[id^="divId_"]').length; i++){ document.querySelectorAll('[id^="divId_"]')[i].addEventListener("click", function(){ alert("Hello World!"); }); } A: You can use .querySelectorAll() and .forEach() document.querySelectorAll("[id^='divId_']") .forEach(function(el) { el.onclick = function() { console.log(this.id) } }) <div id="divId_1">click</div> <div id="divId_2">click</div> <div id="divId_3">click</div>
doc_4810
When I execute my code in AS3 I get this: &levelUser=5&livesUser=5 And its good, it's all the data I want to transfer But when I try to get only one variable I get this error: ReferenceError: Error #1069: Property livesUser not found on String and there is no default value. at petRush_fla::MainTimeline/serverResponse() at flash.events::EventDispatcher/dispatchEventFunction() at flash.events::EventDispatcher/dispatchEvent() at flash.net::URLLoader/onComplete() And I don't know who this is happening, I left my code here: function conectToServer() { //Conectamos al servidor loadingNum.text = "Connection to server..."; var zahtjev:URLRequest=new URLRequest("getUserInfo.php"); var loader:URLLoader = new URLLoader(); loader.addEventListener(Event.COMPLETE, serverResponse); loader.load(zahtjev); } var livesVar:String; function serverResponse(e:Event):void { trace(e.target.data.livesUser); gotoAndStop(2); } A: The data returned is a string, and you need to create a URLVariables instance like this : function serverResponse(e:Event):void { var myVariables:URLVariables = new URLVariables(e.target.data); trace(myVariables.livesUser); gotoAndStop(2); } Also I should note that your string shouldn't begin with a &, it should be : levelUser=5&livesUser=5
doc_4811
User.findOne(userId, function foundUsr(err, user) { // ..handle error stuff.. User.update(userId, {viewsNo: user.viewsNo + 1}, function (err, usr) { // ..rest of the code.. }) }); Is it possible to handle those two database operations with a single call? Besides the database load it will also increase code clarity, but I was unable to find a solution. A: Yes @Vee6 as you stated, using User.native() will work, another option is to do: User.findOne(userId, function foundUsr(err, user) { user.viewsNo++; user.save(function(err) { /* updated user */ }); }); A: If I catch your problem right the first query is needed just to check if record with given userId exist in database. In such situation you should probably add beforeUpdate() method to your model. Something like: // api/models/user.js module.exports = { attributes: {/* ... */}, beforeUpdate: function(values, next) { User.findOne(values.userId).exec(function(err, user) { // ..handle error stuff.. if (err) return next(err); if (typeof user === 'undefined') return next(new Error('bad userId')); next(); }); } }; Now you can just update your values in controller and if error happens sails will stop updating. UPD: About incrementing viewsNo in single query: no it is not possible at the moment. Here is feature request about it.
doc_4812
My MainWindow has an video file feed with VLC plugin, and my Window2 has a transparent background and overlaying Toggle button and an Exit button. Any suggestions / definitive examples would be helpful if any one can help. MainWindow: namespace VLC_Test { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { AxAXVLC.AxVLCPlugin vlcPlayer = new AxAXVLC.AxVLCPlugin(); public MainWindow() { InitializeComponent(); WFH1.Child = vlcPlayer; } private void Window_Loaded(object sender, RoutedEventArgs e) { Window2 win2 = new Window2(); win2.Show(); string file1 = @"C:\Users\Username\Desktop\drop.avi"; vlcPlayer.addTarget("file:///" + file1, null, AXVLC.VLCPlaylistMode.VLCPlayListReplaceAndGo, 0); vlcPlayer.play(); } } } XAML: <Window x:Class="VLC_Test.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" SizeToContent="WidthAndHeight" WindowStartupLocation="Manual" Top="0" Left="7" AllowsTransparency="False" WindowStyle="None" Loaded="Window_Loaded" Topmost="True" ShowInTaskbar="False" BorderThickness="0" ResizeMode="CanResizeWithGrip"> <Window.Background> <SolidColorBrush Opacity="0" Color="White"/> </Window.Background> <Grid Width="Auto" Height="Auto"> <WindowsFormsHost Height="495" Width="550" HorizontalAlignment="Left" Name="WFH1" VerticalAlignment="Top" Margin="-11,-24,0,0" ChildChanged="WFH1_ChildChanged" /> </Grid> </Window> Window2: namespace VLC_Test { /// <summary> /// Interaction logic for Window2.xaml /// </summary> public partial class Window2 : Window { public Window2() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { } private void button2_Click(object sender, RoutedEventArgs e) { this.Close(); App.Current.Shutdown(); } } } XAML: <Window x:Class="VLC_Test.Window2" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window2" Height="495" Width="550" WindowStartupLocation="Manual" Top="0" Left="7" AllowsTransparency="True" WindowStyle="None" Topmost="True" > <Window.Background> <SolidColorBrush Opacity="0" /> </Window.Background> <Window.Resources> <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/> </Window.Resources> <Grid Width="Auto" Height="Auto"> <ToggleButton Content="Crosshair" Height="39" HorizontalAlignment="Right" Margin="0,0,125,12" Name="Button1" VerticalAlignment="Bottom" Width="58" Click="button1_Click" IsChecked="False" DataContext="{Binding}"/> <Button Content="Exit" Height="39" HorizontalAlignment="Right" Margin="0,0,49,12" Name="button2" VerticalAlignment="Bottom" Width="58" Click="button2_Click" /> <Canvas Background="Transparent" Height="200" Width="200" HorizontalAlignment="Center" Margin="0,0,0,0" Name="Canvas1" VerticalAlignment="Center" Visibility="{Binding IsChecked, ElementName=Button1, Converter={StaticResource BooleanToVisibilityConverter}}"> <Line X1="100" Y1="0" X2="100" Y2="75" Stroke="Red" StrokeThickness="0.95" /> <!--Top long vertical line> /--> <Line X1="100" Y1="95" X2="100" Y2="105" Stroke="Red" StrokeThickness="0.95" /> <!--Crosshair vertical line> /--> <Line X1="100" Y1="125" X2="100" Y2="200" Stroke="Red" StrokeThickness="0.95" /> <!--Bottom long vertical line> /--> <Line X1="0" Y1="100" X2="75" Y2="100" Stroke="Red" StrokeThickness="0.75" /> <!--Left long horizontal line> /--> <Line X1="95" Y1="100" X2="105" Y2="100" Stroke="Red" StrokeThickness="0.75" /> <!--Crosshair horizontal line> /--> <Line X1="125" Y1="100" X2="200" Y2="100" Stroke="Red" StrokeThickness="0.75" /> </Canvas> </Grid> </Window> A: I would simply use the SizeChanged event. Change your MainWindow XAML to include a call to the event handler. (Similarly, if you want to keep the two windows together when your MainWindow is moved, use the LocationChanged event, also shown.): <Window x:Class="VLC_Test.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" SizeToContent="WidthAndHeight" WindowStartupLocation="Manual" Top="0" Left="7" AllowsTransparency="False" WindowStyle="None" Loaded="Window_Loaded" Topmost="True" ShowInTaskbar="False" BorderThickness="0" ResizeMode="CanResizeWithGrip" SizeChanged="Window_Resize" LocationChanged="Window_Moved"> <Window.Background> <SolidColorBrush Opacity="0" Color="White"/> </Window.Background> <Grid Width="Auto" Height="Auto"> <WindowsFormsHost Height="495" Width="550" HorizontalAlignment="Left" Name="WFH1" VerticalAlignment="Top" Margin="-11,-24,0,0" ChildChanged="WFH1_ChildChanged" /> </Grid> </Window> Then in your cs file for MainWindow, implement the event. Notice that I kept a variable on the window to store your Window2 object so I could refer back to it after it had been loaded. namespace VLC_Test { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { AxAXVLC.AxVLCPlugin vlcPlayer = new AxAXVLC.AxVLCPlugin(); Window2 win2; public MainWindow() { InitializeComponent(); WFH1.Child = vlcPlayer; } private void Window_Loaded(object sender, RoutedEventArgs e) { CreateWindow2Overlay(); string file1 = @"C:\Users\Username\Desktop\drop.avi"; vlcPlayer.addTarget("file:///" + file1, null, AXVLC.VLCPlaylistMode.VLCPlayListReplaceAndGo, 0); vlcPlayer.play(); } private void CreateWindow2Overlay() { win2 = new Window2(); win2.Left = Left; win2.Top = Top; win2.Width = Width; win2.Height = Height; win2.Owner = this; win2.Show(); } private void Window_Resize(object sender, SizeChangedEventArgs e) { if (win2 != null) { win2.Height = e.NewSize.Height; win2.Left = Left; win2.Width = e.NewSize.Width; win2.Top = Top; } } private void Window_Moved(object sender, EventArgs e) { if (win2 != null) { win2.Left = Left; win2.Top = Top; } } } } All changes made to the code for MainWindow. I did not change the cs or xaml for Window2. This solution tested in Visual Studio 2010. Note that I added the CreateWindow2Overlay method which sets up the second window. It specifically sets the owner of Window2 to this (MainWindow) so as to put Window2 in front of MainWindow. To be clear, the problems this change solves are: 1. Put Window2 object on top of MainWindow 2. Change Window2 size when MainWindow resized If there is any part of your request which I am missing, please don't hesitate to point it out. I hope that helps you.
doc_4813
Case when COUNT_DISTINCT(Campaign = 1) then "1" When COUNT_DISTINCT(Campaign =2) then "2" When COUNT_DISTINCT(Campaign =3) then "3" else "more" End The end result I would like is a table that looks something like this: * *Received 1 campaign, X amount of users *Received 2 campaigns, Y amount of users *Received 3 campaigns, W amount of users *... (and so on) A: This is not possible since CASE aggregation only works over report dimensions but not over actual user records.
doc_4814
Is there a way I can achieve client credentials grant using Google Auth Server? Can I use Service Accounts to communicate between services outside Google Cloud?
doc_4815
string deliminator = ","; string tablename = "Converted"; //string filelink = FileName.Text; string fileintro = FileName.Text; DataSet DS = new DataSet(); StreamReader SR = new StreamReader(fileintro.Trim()); DS.Tables.Add(tablename); DS.Tables[tablename].Columns.Add("A"); DS.Tables[tablename].Columns.Add("B"); DS.Tables[tablename].Columns.Add("C"); DS.Tables[tablename].Columns.Add("D"); DS.Tables[tablename].Columns.Add("E"); DS.Tables[tablename].Columns.Add("F"); DS.Tables[tablename].Columns.Add("G"); DS.Tables[tablename].Columns.Add("H"); DS.Tables[tablename].Columns.Add("I"); ... SQLiteConnectionconn=newSQLiteConnection(ConfigurationManager.ConnectionStrings["dbcon"].ConnectionString); SQLiteCommand cmd = new SQLiteCommand ("INSERT INTO ConvertData (a,b,c,d,e,f) values ('"+a+"'...), con); cmd.ExecuteNonQuery(); co.Close(); FileName.Text = ""; } it saves data in database table like "1,2,3,4,5,6,7" so how can i save it normally like 1,2,3,4,5,6,into database columns.' A: The data from comma separate files are exported as string. So before inserting into the database tables convert them into required data types. For examples, if the data type in the table is int, use the Parse function and convert the string to integer before inserting, You need to repeat this for all columns int Id = Int32.Parse(ExcelCol1.Text); If you are looking for a detailed approach, the below link will help you Uploading an Excel sheet and importing the data into SQL Server database
doc_4816
structure(list(k = structure(c(17563, 17591, 17622, 17652, 17683 ), class = "Date"), startdt = structure(c(17532, 17561, 17589, 17620, 17650), class = "Date"), enddt = structure(c(17560, 17588, 17619, 17649, 17652), class = "Date")), row.names = c(NA, -5L ), class = c("grouped_df", "tbl_df", "tbl", "data.frame"), .Names = c("k", "startdt", "enddt"), vars = "k", drop = TRUE, indices = list( 0L, 1L, 2L, 3L, 4L), group_sizes = c(1L, 1L, 1L, 1L, 1L), biggest_group_size = 1L, labels = structure(list( k = structure(c(17563, 17591, 17622, 17652, 17683), class = "Date")), row.names = c(NA, -5L), class = "data.frame", vars = "k", drop = TRUE, .Names = "k")) and I want to pipe it into a function. here's how I would use map3, which does not exist (hooray) -- dates %>% map3_df(.x = $.k, .y = $.startdt, .z = $.enddt, .f = ~ fetchdata(startdate = .z, enddate = .z, k = .x) Pmap may be an option? i'm just not too familiar, and an issue seems to be that i can't assign variables explicitly (ie .x, .y, .z) and the function i want to map to takes a ton of optional variables (and i only want to specify startdate, enddt, and k). Any help appreciated, thanks in advance.
doc_4817
I Want to * *I click me Div then Second hiddendiv Div display. But I want to click a second time in click me Div, then hide a hiddendiv Div . Similar toggle event using pure css. *I click me Div then Second hiddendiv Div display. But I click other area click then hide ahiddendiv Div . So I want to not hide ahiddendiv Div in any other click using pure css. Note: Only pure CSS,CSS3 Use in Answer not use (javascript,jquery) & any other from control Code .clicker { width: 100px; height: 100px; background-color: blue; outline: none; cursor: pointer; color:#FFF; } .hiddendiv { display: none; height: 200px; background-color: green; } .clicker:focus+.hiddendiv { display: block; } <div> <div class="clicker" tabindex="1">Click me</div> <div class="hiddendiv"></div> </div> A: You can use a checkbox input and based on if this is checked or not you can show hide the div. below is a example using the same. .clicker { width: 100px; height: 100px; background-color: blue; outline: none; cursor: pointer; color:#FFF; display:block; } .hiddendiv { display: none; height: 200px; background-color: green; } .clicker:focus+.hiddendiv { display: block; } .hidden{ margin-left:-99999px; } input#cmn-toggle-7:checked + label + div{ display:block; } <div> <input id="cmn-toggle-7" class="hidden" type="checkbox" > <label for="cmn-toggle-7" class="clicker" tabindex="1">Click me</label> <div class="hiddendiv"></div> </div> A: you achieve that using checkbox with some css manipulation div input { margin-right: 100px; } .check-btn label { display: inline-block; } .check-btn input { display: none; } .clicker { background: green; padding: 5px 10px; } .hiddendiv { background: #000; width: 100px; height: 100px; display: none; } .check-btn input:checked ~ .hiddendiv { display: block; } <div class="check-btn"> <input id="myid" type="checkbox" > <label for="myid" class="clicker">Click me</label> <div class="hiddendiv"></div> </div> Here jsfiddle A: That is not possible with the given requirements, all elements being a div. It would be possible if you change div's acting as links to anchors a, and use :target pseudo By setting display: inline-block on the anchor a, you can size it as you can with a div .clicker { display: inline-block; width: 100px; height: 50px; background-color: blue; color:#FFF; } .clicker.hidden { display: none; } .hiddendiv { height: 0px; background-color: green; overflow: hidden; transition: height 0.5s; } .hiddendiv.nr2 { background-color: red; } #showdiv1:target ~ div a[href="#showdiv1"], #showdiv2:target ~ div a[href="#showdiv2"] { display: none; } #showdiv1:target ~ div a[href="#hidediv1"], #showdiv2:target ~ div a[href="#hidediv2"] { display: inline-block; } #showdiv1:target ~ div .hiddendiv.nr1, #showdiv2:target ~ div .hiddendiv.nr2 { height: 130px; } <div id="showdiv1"></div> <div id="showdiv2"></div> <div> <a href="#showdiv1" class="clicker" tabindex="1">Click me 1</a> <a href="#hidediv1" class="clicker hidden" tabindex="1">Click me 1</a> <a href="#showdiv2" class="clicker" tabindex="2">Click me 2</a> <a href="#hidediv2" class="clicker hidden" tabindex="2">Click me 2</a> <div class="hiddendiv nr1"></div> <div class="hiddendiv nr2"></div> </div>
doc_4818
Am I missing something? Fatal Exception: java.lang.RuntimeException: Parcelable encountered IOException writing serializable object (name = mypackage.a.a.a) at android.os.Parcel.writeSerializable(Parcel.java:1447) at android.os.Parcel.writeValue(Parcel.java:1395) at android.os.Parcel.writeArrayMapInternal(Parcel.java:665) at android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1337) at android.os.Bundle.writeToParcel(Bundle.java:1079) at android.os.Parcel.writeBundle(Parcel.java:690) at android.support.v4.app.FragmentState.writeToParcel(Fragment.java:148) at android.os.Parcel.writeTypedArray(Parcel.java:1233) at android.support.v4.app.FragmentManagerState.writeToParcel(FragmentManager.java:564) at android.os.Parcel.writeParcelable(Parcel.java:1416) at android.os.Parcel.writeValue(Parcel.java:1322) at android.os.Parcel.writeArrayMapInternal(Parcel.java:665) at android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1337) at android.os.Bundle.writeToParcel(Bundle.java:1079) at android.os.Parcel.writeBundle(Parcel.java:690) at android.support.v4.app.FragmentState.writeToParcel(Fragment.java:150) at android.os.Parcel.writeTypedArray(Parcel.java:1233) at android.support.v4.app.FragmentManagerState.writeToParcel(FragmentManager.java:564) at android.os.Parcel.writeParcelable(Parcel.java:1416) at android.os.Parcel.writeValue(Parcel.java:1322) at android.os.Parcel.writeArrayMapInternal(Parcel.java:665) at android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1337) at android.os.Bundle.writeToParcel(Bundle.java:1079) at android.os.Parcel.writeBundle(Parcel.java:690) at android.app.ActivityManagerProxy.activityStopped(ActivityManagerNative.java:3153) at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3455) at android.os.Handler.handleCallback(Handler.java:743) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:150) at android.app.ActivityThread.main(ActivityThread.java:5621) at java.lang.reflect.Method.invoke(Method.java) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:794) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:684) Caused by java.io.NotSerializableException mypackage.model.MyClass and here is MyClass code: public class MyClass implements Parcelable { private transient JSONObject json; public static final String KEY = "my_key"; public static final String VALUE = "my_value"; public MyClass(){ json = new JSONObject(); } public MyClass(String json){ try { if (!TextUtils.isEmpty(json)) { json = new JSONObject(json); }else { json = new JSONObject(); } } catch (JSONException e) { e.printStackTrace(); } } public MyClass myMethod1(String s1, String s2){ //Do something here } public String myMethod2(String s1){ //Do something here return null; } @Override public String toString() { return json.toString(); } public String jsonText() { return json.toString(); } protected MyClass(Parcel in) { try { json = in.readByte() == 0x00 ? null : new JSONObject(in.readString()); } catch (JSONException e) { e.printStackTrace(); } } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { if (json == null) { dest.writeByte((byte) (0x00)); } else { dest.writeByte((byte) (0x01)); dest.writeString(json.toString()); } } public static final Parcelable.Creator<MyClass> CREATOR = new Parcelable.Creator<MyClass>() { @Override public MyClass createFromParcel(Parcel in) { return new MyClass(in); } @Override public MyClass[] newArray(int size) { return new MyClass[size]; } }; public static MyClass myMethod3(){ //Do something here } } I have removed the body of methods for make it shorter to review. I'm passing this object with Intent between my activities and my code is working on many phones, but this exception only occurs in some phones, not all of them.
doc_4819
class MyType { string A; string B; int C; DateTime D;} I have a list of strings, let's say List<string> columns = new List<string>(){ "A", "C", "D"}; I want to create a new type at run time based on property matches to the strings in the columns. Like my new type will be MyType oldType = new MyType() { A = "Hello", B = "World", C = 2013, D = DateTime.Now() } // it contains ACD as in columns list and corresponding values from oldType var newtype = new { A = "Hello" , C = 2013, D = DateTime.Now() } I am not able to understand what approach I should take other than using emit to create new type. Suggest me something without using reflection or emit.
doc_4820
export function Uppercase(isEnabled: boolean) { return function ( target: any, propertyKey: string, descriptor: PropertyDescriptor, ) { console.log(isEnabled); if (isEnabled) { const originalMethod = descriptor.value; descriptor.value = function (...args: any[]) { const result = originalMethod.apply(this, args); return result.toUpperCase(); }; } else { const originalMethod = descriptor.value; descriptor.value = function (...args: any[]) { const result = originalMethod.apply(this, args); return result; }; } }; } I don't understand why this is working and why the inner function can access the variable isEnabled. In my understanding this should only work if the returned function was an anonymous function.
doc_4821
But the same is not working if we try to fetch information at a class level (https://sonar-service/api/resources?resource=com.demo.project:demo-project:src/main/java/com/demoClass.java&metrics=new_coverage&includetrends=true). It simply returns current value. Is there any way to fetch historical coverage data for a given class/method (either by using APIs or querying Database). If it is not possible in Sonarqube 5.x & below, do we have any simpler way in 6.x version of Sonarqube. A: Historical data is not retained at the file level. I don't believe it ever has been.
doc_4822
doc_4823
* *It's true when define Filter, it's required to define FilterDefs? There's scenario that i does't required any parameter, because the filter it's self is sufficient. eg: filterName="filter1" condition="ID in (select id from table1"), filterName="filter2" condition="ID in (select id from table2)" *It's true when define a Filter, filter name should not contain dot "." character? When I define a class name as filterName, hibernate can't find FilterDefs eg: filterName="org.my.company.Class1" condition="ID in (select id from table1") *Is the following condition is correct: filterName="filter3" condition="ID in (select id from table1 where column1 like '%:param1%')" question: What I'm tries to do? Answer: I'm using Spring ACL and I want to query all granted entity for given sid. I had create Spring ACL entity object. My domain and sid is my ACL session query parameter. Then I'm using my domain name as a filter name so that a would easily enable the required filter eg: session.enableFilter(myclass.getCanonicalName()); session.createQuery("select count(distinct aoi.id) from AclObjectIdentity aoi join aoi.entries e where ......" Thanks
doc_4824
Here's my main class import java.util.Arrays; import java.util.*; public class Main { public static void main(String[] args){ int choice; int g; Scanner input=new Scanner(System.in); System.out.println("Enter how many random no:"); g=input.nextInt(); RandomAlgo ran=new RandomAlgo(); g=ran.randomNum(g); RandomAlgo rand=new RandomAlgo(); int[] data=rand.randomNum(randomNumbers); //did i did this right here? System.out.println("Choose Sorting algorithm: \n (1)Selection Sort \n (2)Insertion Sort \n (3)Bubble Sort \n (4)Quick Sort" ); choice=input.nextInt(); switch(choice){ case 1:{ SortingAlgo algo=new SortingAlgo(); data=algo.selectionSort(data); break; } for my random numbers class here is my code. My problem is how do I pass the values of randomNumbers to my main class? public class RandomAlgo extends Main{ public int randomNum(int g){ Random rand = new Random(); int e; int i; HashSet<Integer> randomNumbers = new HashSet<Integer>(); for (i = 0; i < g; i++) { e = rand.nextInt(1000); randomNumbers.add(e); if (randomNumbers.size() <= 0) { if (randomNumbers.size() == 0) { g = g; } g++; randomNumbers.add(e); } } System.out.println("Random numbers Are : " +randomNumbers); return g; } } A: int[] data=rand.randomNum(randomNumbers); //did i did this right here? randomNumbers is a local variable of subclass RandomAlgo.randomNum(), Main don't know about it. You may write your RandomAlgo as following. public class RandomAlgo { // Why extend Main ??? public int[] randomNum(int g){ // return an int array with random numbers instead Random rand = new Random(); int[] randomNumbers = new int[g]; for (int i = 0; i < g; i++) { int e = rand.nextInt(1000); randomNumbers[i] = e; // if (randomNumbers.size() <= 0) { // if (randomNumbers.size() == 0) { // g = g; // } // g++; // randomNumbers.add(e); // } } // System.out.println("Random numbers Are : " +randomNumbers); return randomNumbers; } } You'll have to change your Main accordingly, public class Main { public static void main(String[] args){ int choice; int g; Scanner input=new Scanner(System.in); System.out.println("Enter how many random no:"); g=input.nextInt(); // RandomAlgo ran=new RandomAlgo(); // g=ran.randomNum(g); RandomAlgo rand=new RandomAlgo(); int[] data=rand.randomNum(g); // load return random numbers array to data System.out.println("Choose Sorting algorithm: \n (1)Selection Sort \n (2)Insertion Sort \n (3)Bubble Sort \n (4)Quick Sort" ); choice=input.nextInt(); A: randomNum() is returning the number of random numbers you initially requested, not the numbers themselves. Change the return type of randomNum() to int[] and inside the method, convert your g HashSet to an array, maybe using one of the methods described here, then return that array.
doc_4825
A: A driver is a set of tests that test the interface of your class (methods, properties, constructor, etc). A stub is a fake object that acts as a stand-in for other functionality like a database or a logger. A mock is a fake object that has asserts in it. Following is an example of a test using a mock object. If you take out the asserts, it becomes a stub. Collectively, these kinds of tests are drivers, because they exercise the methods and properties of your object. Here is the example: [Test] public void TestGetSinglePersonWithValidId() { // Tell that mock object when the "GetPerson" method is called to // return a predefined Person personRepositoryMock.ExpectAndReturn("GetPersonById", onePerson, "1"); PersonService service = new PersonService( (IPersonRepository) personRepositoryMock.MockInstance); Person p = service.GetPerson("1"); Assert.IsNotNull(p); Assert.AreEqual(p.Id, "1"); } http://www.zorched.net/2007/03/10/mocking-net-objects-with-nunit/
doc_4826
I have added the base pixel into my index.html but I want to fire an event from the javascript, how do I fire this fbq('track', 'CompleteRegistration'); Angular will not compile when I have this in my code as it can't find fbq A: Even though fbq is globally-available in your app at runtime, the compiler doesn't know about it because it is defined in index.html (outside of the typescript files known to the compiler). To fix this, add an ambient declaration to the files where you use fbq, like so: declare const fbq: any; // 1. add an ambient declaration @Component({...}) export class ComponentUsingFacebookPixel { fbq('track', 'CompleteRegistration'); // 2. This will compile now } This doesn't change the compiled javascript or overwrite the value of fbq; it's a promise to the compiler that there will be a value by that name available at runtime. You can provide a more specific type than any if you'd like additional help from the compiler, but any is sufficient to avoid the compilation error you're seeing. A: create one service and call it in your app.component.ts import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class FacebookPixelService { constructor() { } load() { (function (f: any, b, e, v, n, t, s) { if (f.fbq) return; n = f.fbq = function () { n.callMethod ? n.callMethod.apply(n, arguments) : n.queue.push(arguments) }; if (!f._fbq) f._fbq = n; n.push = n; n.loaded = !0; n.version = '2.0'; n.queue = []; t = b.createElement(e); t.async = !0; t.src = v; s = b.getElementsByTagName(e)[0]; s.parentNode.insertBefore(t, s) })(window, document, 'script', 'https://connect.facebook.net/en_US/fbevents.js'); (window as any).fbq.disablePushState = true; //not recommended, but can be done (window as any).fbq('init', '<your id>'); (window as any).fbq('track', 'PageView'); } } A: add this in ngOnInit() if you have already added to index.html (window as any).fbq('track', 'CompleteRegistration'); // this Worked for me
doc_4827
I have imported a project from github to my local git-folder. Then i have imported the project to my own project with "Java Build-Path -> Projects-> Add". Then many errors occured in my project and for example the import import dna.graph.datastructures.DataStructure.ListType; says: The import dna cannot be resolved to a type. The curious thing is, if i point the mouse to a underlined classname, it suggets to import the exact class from the linked project. In other word, eclipse knows about the project, but the import doesn't fit. A: It seems pretty much like the problem mentioned here: http://philip.yurchuk.com/software/eclipse-cannot-be-resolved-to-a-type-error/ But none of the tips there fixed my problem.
doc_4828
It's a tree which has a Node and as many subtrees as you want. generateGameTree g p = Node (g,p) [ ((fst x),generateGameTree (snd x) (nextPlayer p)) | x <- (findPossibleMoves p g) ] now the Problem is to find a recursive base case. We have a function called identifyWinner which does pretty much what it says. The idea is, to use this function to determine if someone has won and to stop making subtrees whenever that happend. But that would look something like this: generateGameTree g p = | identifyWinner g p == Nothing = Node (g,p) [ ((fst x),generateGameTree (snd x) (nextPlayer p)) | x <- (findPossibleMoves p g) ] | otherwise = "DO NOTHING" We cant figure out how to actually do nothing. Is there a way to make this happen in Haskell? Thanks in advance! A: First of all it is rather un-Haskell to say that Haskell does something, that's the whole point of declarative programming and lazy programming. You describe the output. How it is actually generated is up to the compiler. To answer your question, you could change your function a bit, such that it allows Maybe: generateGameTree g p = | identifyWinner g p == Nothing = Just $ Node (g,p) $ filter (isJust . snd) [ ((fst x),generateGameTree (snd x) (nextPlayer p)) | x <- (findPossibleMoves p g) ] | otherwise = Nothing the filter will filter out Nothings in the tree. Another (more or less equivalent) solution is generating a list of nodes, and the list is either empty, or a singleton: generateGameTree g p = | identifyWinner g p == Nothing = [Node (g,p) $ concat [ ((fst x),generateGameTree (snd x) (nextPlayer p)) | x <- (findPossibleMoves p g) ] ] | otherwise = [] A: If you have a function nextPositions :: Game -> [Game] which gives all the positions that can result from taking every possible move at the given position then a game tree is a Cofree [] Game from Control.Comonad.Cofree type GameTree = Cofree [] Game and it can be generated with generateGameTree :: Game -> GameTree generateGameTree = coiter nextPositions If positions which are won have no next positions then the generation will automatically stop at won positions. You can then convert this to a more usual Data.Tree representation if you want. A: If there is already a winner and this means the game has ended and there are no more moves, then that is what the result should be, the current state of the game together with a list of no children, so: makeGameTree g p = | identifyWinner g p == Nothing = Node (g,p) [ (fst x, makeGameTree (snd x) (nextPlayer p)) | x <- (findPossibleMoves p g) ] | otherwise = Node (g,p) []
doc_4829
What I tried is to create two instance of a class A (A0 and A1). Class A registers a very simple signal in its _class_init function. file_signals[0] = g_signal_newv("a_signal", G_TYPE_FROM_CLASS(ACLASS), G_SIGNAL_ACTION, NULL /* closure */, NULL /* accumulator */, NULL /* accumulator data */, NULL /* C marshaller */, G_TYPE_NONE /* return_type */, 0 /* n_params */, NULL); /* argument types*/ Then I connect a simple callback function (cb_a) for both instances A0 and A1 to the signal "a_signal". (For example in the _instance_init function) g_signal_connect(A0, "a_signal", (GCallback)cb_a, NULL); g_signal_connect(A1, "a_signal", (GCallback)cb_a, NULL); , where cb_a is a function defined in A.c: static void cb_a(void) { printf("cb_a called!\"); } What happens now is that if I invoke g_signal_emit(A0, file_signals[0], 0); is that only the callback associated to A0 is invoked. I couldn´t figure out how to call the function for each instance of A with e.g. a single call to g_signal_emit(...)? Any help is appreciated. Thanks. A: That’s not how GObject signals work. A signal is a one-to-many notification from a single class instance to all the connected callbacks for that class instance. If you want to emit the A::a_signal signal from several instances of the class, you need to call g_signal_emit() for each of those instances. Note that g_signal_emit() is only meant to be called from within the implementation of a class, not from code outside that class. One approach to your problem is to have a separate class (let’s call it Signaller) with a signal on it, to store a reference to a single instance of Signaller within A0 and A1, and to connect a_cb to that instance within each of A0 and A1. To notify all instances of the A class, emit Signaller::a_signal on the single Signaller instance. However, without more concrete information about the particular problem you’re trying to solve, it’s hard to say what the right architecture is. My suggestion above may not be the most appropriate solution.
doc_4830
When I set one draw in game, then each value probability is the same. It is visible in red colour on attached graph. And I expected that. When I set three or more draws, the middle value probability is high. For example, if I have 3 draw in range from 0 to 100 then I can expect that sum of value will be in range from 0 to 300 and most probable value will be 150. When I draw in on graph, then I get Gauss curve. It is blue in graph. The non intuitive case is when I set two draws. I expected that curve will be the same like in previous case, but I see that output is similar to triangular. It is green curve. --> Graph image <-- The questions are: * *What is fundamental difference between two and more draw and why the output curves is different? *Why when I set two draw then I will not get Gauss curve? Python code: import random import matplotlib.pyplot as plt import collections class GaussGame(): def __init__(self, draw_range = {min: 0, max: 100}, number_of_draws = 5, number_of_games = 100000) -> None: self.draw_range = draw_range self.number_of_draws = number_of_draws self.number_of_games = number_of_games def start(self): #Create win dictionary which contains amounts of possible wins as a key and, number of wins for each possible amounts as a value. win_dict = collections.OrderedDict() for x in range(self.draw_range[min]*self.number_of_draws, self.draw_range[max]*self.number_of_draws+1): win_dict[x]=0 #Loop for all games for x in range(self.number_of_games): #Loop for one game d_sum = 0 #Sum of the drawn values d_sum for x in range(self.number_of_draws): d_sum += random.randrange(self.draw_range[min], self.draw_range[max]+1) win_dict[d_sum] += 1 return win_dict def main(): #When I run game several times, with different number_of_draws parameter and draw it on one graph, then I can get interesting picture :-D g1 = GaussGame({min: 0, max: 100},1,10000000) g2 = GaussGame({min: 0, max: 100},2,10000000) g3 = GaussGame({min: 0, max: 100},3,10000000) g4 = GaussGame({min: 0, max: 100},4,10000000) g5 = GaussGame({min: 0, max: 100},5,10000000) d1 = g1.start() d2 = g2.start() d3 = g3.start() d4 = g4.start() d5 = g5.start() plt.plot(d1.keys(), d1.values(), 'r.') plt.plot(d2.keys(), d2.values(), 'g.') plt.plot(d3.keys(), d3.values(), 'b.') plt.plot(d4.keys(), d4.values(), 'b.') plt.plot(d5.keys(), d5.values(), 'b.') plt.show() if __name__ == "__main__": main() A: That looks about right. What you see, I believe, is Irwin-Hall distribution, or its variation. When you sum small number of samples, it is not gaussian, but converges to it as soon as there are many samples, see CLT
doc_4831
ORIGINAL = path to the original_file folder CONVERTED = path to the converted_file folder for /f "delims=" %%f in ('dir /b %ORIGINAL%') do ( FOR /F "tokens=*" %%B IN ('%ORIGINAL%\%%f') DO ( SET CCC=%%B SET CCC=!CCC:^|=^;! ECHO !CCC! >> '%CONVERTED%\%%f' ) ) My first loop works fine, sends all the file names in the original_folder, yet my second loop isn't used. I tried to play with ' and " for files/path containing spaces. Any ideas on how one would fix this only using classic old batch technics? A: Using this did the trick, thanks @aschipfl for /f "delims=" %%f in ('dir /b %ORIGINAL%') do ( FOR /F "usebackq tokens=*" %%B IN ("%ORIGINAL%\%%f") DO ( SET CCC=%%B SET "CCC=!CCC:%CHAR_TO_REPLACE%=%CHAR_TO_USE%!" ECHO !CCC! >> "%CONVERTED%\%%f" ) )
doc_4832
I created one abc.mxml application which is working fine in the IDE. Now, I want to use the generated abc.swf in one of my application so I copied * *abc.swf *abc.html *and related .js and .css files to some other location in the file system. After that when I tried to launch the abc.html in the browser, nothing was appearing in the browser. After that I copied the whole flex project at some other location and tried to launch the same abc.html file. Even that was also not working. I don't know what's the problem. Edited ============================================================================ A: My money is on sandbox security issue. Either keep the files under bin-debug to prevent it or add your folder and flash file to be allowed in the Flash Security Settings. A: This is cross-site scripting situation, read this: http://kb2.adobe.com/cps/142/tn_14213.html. You launch abc.html (which consist adc.swf) from one domain ("file:///c: ..."), but refers for data from another (is there you red5 installed, probably localhost). Create cossdomain.xml in the root directory in ther server (red5).
doc_4833
A: Not enough information to really help you, but I am going to guess you have the following situation: * *Running vxworks *A standalone vxworks module with your function in it If this is the case then you can just load the module with the ld vxworks command, and then just call the function from the command line. A few things to note, if your function is static then you will not be able to call it, and if it is c++ then you may need to create a C interface to it... Look in the docs for usrLib to read more about the ld command, I would link to it, but I don't know where to find good VxWorks docs online anymore...
doc_4834
<ComboBox ItemsSource="{Binding SelectedError.Suggestions}" Text="{m:Binding Path=SelectedError.SelectedReplacement, Mode=TwoWay}" IsEditable="True" HorizontalAlignment="Stretch"/> i also tried to get the propertychanged private void ViewModelPropertyChanged(SpellcheckViewModel sender, PropertyChangedEventArgs e) { if (e.PropertyName == nameof(sender.SelectedError.SelectedReplacement)) { _correctCommand?.Refresh(); } } A: I try to write a demo project to meet your requirement. Mainly, the enable state is controlled by another boolean property IsButtonEnabled in the view model, the value for that property is controlled by InputText property which is controlled by the text you input in the ComboBox control. Here is the UI: <StackPanel Margin="10"> <ComboBox x:Name="cmb" IsEditable="True" ItemsSource="{Binding AllItems}" TextBoxBase.TextChanged="cmb_TextChanged" TextSearch.TextPath="Name"> <ComboBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Name}" /> </DataTemplate> </ComboBox.ItemTemplate> </ComboBox> <TextBox x:Name="hiddenTextBox" Text="{Binding InputText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Visibility="Collapsed" /> <Button x:Name="btn" Margin="0,10,0,0" Content="Show message" IsEnabled="{Binding IsButtonEnabled}" /> </StackPanel> And here is the main logic in the view model: public ObservableCollection<Item> AllItems { get { return _allItems; } set { _allItems = value; this.RaisePropertyChanged("AllItems"); } } public bool IsButtonEnabled { get { return _isButtonEnabled; } set { _isButtonEnabled = value; this.RaisePropertyChanged("IsButtonEnabled"); } } /// <summary> /// When InputValue changed, change the enable state of the button based on the current conditions /// </summary> public string InputText { get { return _inputText; } set { _inputText = value; this.RaisePropertyChanged("InputText"); // You can control the enable state of the button easily if (AllItems.Any(item => item.Name == value)) { // SelectedItem is not null IsButtonEnabled = true; } else if (!string.IsNullOrEmpty(value)) { // SelectedItem is null IsButtonEnabled = true; } else { IsButtonEnabled = false; } } } Finally, here is the project: ComboBoxDemo
doc_4835
Thanks Shash A: Use octave_map if you want a structure array (in constrast to octave_scalar_map). In that case "contents" returns a Cell which may have more than one element. You should also have a look at oct-map.h and examples/code/structdemo.cc And read the manual part https://www.gnu.org/software/octave/doc/interpreter/Structures-in-Oct_002dFiles.html#Structures-in-Oct_002dFiles
doc_4836
I would like to run Rhipe inside R. After downloading I had installed it: sudo R CMD INSTALL Rhipe_0.73.1.tar.gz Then I exported environment variables: export HADOOP_CONF_DIR="/etc/hadoop/conf" export HADOOP="/usr/lib/hadoop" export HADOOP_BIN=/usr/lib/hadoop/bin export HADOOP_HOME=/usr/lib/hadoop After running R: > library(Rhipe) ------------------------------------------------ | Please call rhinit() else RHIPE will not run | ------------------------------------------------ > rhinit() Rhipe: Using Rhipe.jar file Initializing Rhipe v0.73 14/04/11 12:21:08 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable java.io.IOException: No FileSystem for scheme: hdfs at org.apache.hadoop.fs.FileSystem.getFileSystemClass(FileSystem.java:2385) at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:2392) at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:89) at org.apache.hadoop.fs.FileSystem$Cache.getInternal(FileSystem.java:2431) at org.apache.hadoop.fs.FileSystem$Cache.get(FileSystem.java:2413) at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:368) at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:167) at org.godhuli.rhipe.PersonalServer.run(PersonalServer.java:321) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:616) at RJavaTools.invokeMethod(RJavaTools.java:386) Error in .jcall("RJavaTools", "Ljava/lang/Object;", "invokeMethod", cl, : java.lang.NullPointerException > I am missing something? Java used in system: There are 2 choices for the alternative java (providing /usr/bin/java). Selection Path Priority Status ------------------------------------------------------------ 0 /usr/lib/jvm/java-6-openjdk-amd64/jre/bin/java 1061 auto mode * 1 /usr/lib/jvm/j2sdk1.7-oracle/jre/bin/java 317 manual mode 2 /usr/lib/jvm/java-6-openjdk-amd64/jre/bin/java 1061 manual mode A: The rhinit() function is trying to load hadoop jars that are present in directory specified in HADOOP_HOME variable.Since this function only load those jars in HADOOP_HOME to the class path you have to keep all hadoop specific jars in that directory itself. You can understand this if you look into zzz.R file in rhipe package.
doc_4837
This is how my code looks like std::string data1 uint8_t* data data = (uint8_t*)data1[0] What is wrong here? When I run it it crashed Thanks in advance A: data[0] returns a reference to the first char in the string (provided the string is not empty, otherwise the return value is undefined). You are type-casting the value of that char to a pointer. So, your code crashes when it tries to use the pointer to access an invalid memory address. You need to type-cast the address of that char instead: data = (uint8_t*) &data1[0]; Or, in a more C++-ish (and safer) manner: data = reinterpret_cast<uint8_t*>(&data1[0]); Or, with bounds checking: data = reinterpret_cast<uint8_t*>(&(data1.at(0))); A: For what you want to do you could try: data = (uint8_t*)data1.c_str(); Don't know exactly what are you trying to achieve, but there is for sure a better approach. A: For example if you are doing something like : std::string data1 = "One" then data1[0] gives 'O' whose ASCII value is 79. Now you use this 79 as an address. So, the pointer named data has value 79 in it. So when you use this pointer in your code again, you are actually attempting to read or write protected memory(0x0000004F or 79). Hence, its crashes at run time.
doc_4838
The user will enter the date into the QDateEdit and then when he presses the button, the date will be saved to a variable. How can I do it? A: You can make it simply: var_name = self.dateEdit.date() This will get you a variable in QDate format. If you need it in a format which would be easier to work with then you should use this: temp_var = self.dateEdit.date() var_name = temp_var.toPyDate() The first one gives you: "PyQt4.QtCore.QDate(2011, 11, 8)" While the second returns: "2011-11-08"
doc_4839
<?xml version="1.0" encoding="UTF-8"?> <gbXML xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.gbxml.org/schema xsi.xsd"xmlns="http://www.gbxml.org/schema" temperatureUnit="C" lengthUnit="Meters" areaUnit="SquareMeters"volumeUnit="CubicMeters" useSIUnitsForResults="true" version="0.37"> <Pared id="Pa-1" paredType="Shade"> <Name>P-S-1</Name> <Order> <Direction>0.000000</Direction> <Angle>90.000000</Angle> <Height>3.657818</Height> <Width>15.200000</Width> </Order> </Pared> <Pared id="Pa-2" paredType="Shade"> <Name>P-S-2</Name> <Order> <Direction>90.000000</Direction> <Angle>90.000000</Angle> <Height>2.598076</Height> <Width>14.200000</Width> </Order> </Pared> </gbXML> I want to extract the "Height" and "Width" values of each "Pared id" and sort them out according to the "Direction" and "Angle" values. For example, in "Pared id= "Pa-1", if the "Direction"= 0.000000 AND the "Angle"= 90.000000, then the order of the extracted values of Width and Height should be: (Width, 0.00) (Width, Height) (0.00, Height) (0.00, 0.00) I am new to XSLT and I know how to select the values of Width and Height with: <?xml version="1.0" encoding="UTF-8" ?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0" xmlns:gb="http://www.gbxml.org/schema"> <xsl:output method="xml" indent="yes"/> <xsl:template match="/"> <xsl:template match= "gb:Pared"> <xsl:value-of select="gb:Order/gb:Height/> But I do not know how to sort them manually like I mentioned before. I will really appreciate it if someone could help me with this. I want the following Output (applying the conditions I mentioned before): From Pared id="Pa-1: (15.200000, 0.000000) (15.200000, 3.657818) (0.000000, 3.657818) (0.000000, 0.000000) From Pared id="Pa-2: (0.000000, 0.000000) (14.200000, 0.000000) (14.200000, 2.598076) (0.000000, 2.598076) Think of it as wall coordinates X,Y. The two walls cannot have the same coordinates and the values of height and width act like the coordinate values. According to the "Direction" and the "Angle" of the wall is how those coordinates are paired. You have 0.000 coordinate values because of the 4 X, Y points that describe that wall. Therefore, Pa-1 and Pa-2 cannot have the same coordinates but they might be joined at one coordinate. Like if have two walls than form a L shape, 0.00, 0.00 can be the right bottom coordinate of Pa-1, but if the case of Pa-2, 0.00, 0.00 is the left bottom coordinate. A: Not sure whether I understand correctly. The following XSL, outputs the width and height values, grouped by the Pared section, which is ordered by Direction then Angle (numeric, ascending). Just be careful, in your XML example, I had to separate some of the gbXML's attributes with a space (otherwise it's not valid XML). <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" xmlns:ns0="http://www.gbxml.org/schema"> <xsl:output method="text" version="1.0" encoding="UTF-8" indent="no" omit-xml-declaration="yes"/> <xsl:template match="/"> <xsl:for-each select='//ns0:Pared' > <xsl:sort select=".//ns0:Direction" data-type='number' order="ascending"/> <xsl:sort select=".//ns0:Angle" data-type='number' order="ascending"/> -- Pared: <xsl:value-of select="@id" /> (<xsl:value-of select=".//ns0:Width" />,0.00) (<xsl:value-of select=".//ns0:Width" />,<xsl:value-of select=".//ns0:Height" />) (0.00,<xsl:value-of select=".//ns0:Height" />) (0.00,0.00) </xsl:for-each> </xsl:template> </xsl:stylesheet> Gives -- Pared: Pa-1 (15.200000,0.00) (15.200000,3.657818) (0.00,3.657818) (0.00,0.00) -- Pared: Pa-2 (14.200000,0.00) (14.200000,2.598076) (0.00,2.598076) (0.00,0.00)
doc_4840
After a successfull project build, if I modify a source file and I start build again, it builds the whole project again instead of the only modified file. I noted the following: - I go to another build configuration and I successfull build it; - then I go back to previous configuration and it builds the modifiede file only; But the problem persists: if I restart build it will recompile all even though nothing changed. I hope I was clear. Any suggestions? Best regards, Valter A: Sorry, I didn't understand your question: what do you mean? I click on "build" hammer button. It seems that it started to happen when I simply changed build configuration name because, before this, it has been working properly for months. It seems that make procedure inside Eclipse doesn't recognize that file was already successfully compiled. Thanks a lot. Valter
doc_4841
claimid, customerid, serv-start-date, service-end-date, charge 1, A1, 1-1-14 , 1-5-14 , $200 2, A1, 1-6-14 , 1-8-14 , $300 3, A1, 2-1-14 , 2-1-14 , $100 4, A2, 2-1-14 , 2-1-14 , $100 5, A2, 2-3-14 , 2-5-14 , $100 6, A2, 2-6-14 , 2-8-14 , $100 Problem: Basically to see the maximum total consecutive days Service start date and end date. for customer A1 it would be 8 days (1-5 plus 6-8) and customer A2 it would be 5 6 days (3-5 plus 6-8) ... (claimid is unique PK). Dates are in m-d-yy notation. A: This gets a little messy since you could possibly have customers without multiple records. This uses a common-table-expressions, along with the max aggregate and union all to determine your results: with cte as ( select s.customerid, s.servicestartdate, s2.serviceenddate, datediff(day,s.servicestartdate,s2.serviceenddate)+1 daysdiff from service s join service s2 on s.customerid = s2.customerid and s2.servicestartdate in (s.serviceenddate, dateadd(day,1,s.serviceenddate)) ) select customerid, max(daysdiff) daysdiff from cte group by customerid union all select customerid, max(datediff(day, servicestartdate, serviceenddate)) from service s where not exists ( select 1 from cte where s.customerid = cte.customerid ) group by customerid * *SQL Fiddle Demo The second query in the union statement is what determines those service records without multiple records with consecutive days. A: Here ya go, I think it's the simplest way: SELECT customerid, sum(datediff([serv-end-date],[serv-start-date])) FROM [service] GROUP BY customerid You will have to decide if same day start/end records count as 1. If they do, then add one to the datediff function, e.g. sum(datediff([serv-end-date],[serv-start-date]) + 1) If you don't want to count same day services but DO want to count start/end dates inclusively when you sum them up, you will need to add a function that does the +1 only when start and end dates are different. Let me know if you want ideas on how to do that. A: The only way I could think to solve the issue described by Jonathan Leffler (in a comment on another answer) was to use a temp table to merge contiguous date ranges. This would be best accomplished in an SP - but failing that the following batch may produce the output you are looking for:- select *, datediff(day,servicestartdate,serviceenddate)+1 as numberofdays into #t from service while @@rowcount>0 begin update t1 set t1.serviceenddate=t2.serviceenddate, t1.numberofdays=datediff(day,t1.servicestartdate,t2.serviceenddate)+1 from #t t1 join #t t2 on t2.customerid=t1.customerid and t2.servicestartdate=dateadd(day,1,t1.serviceenddate) end select customerid, max(numberofdays) as maxconsecutivedays from #t group by customerid The update to the temp table needs to be in a loop because the date range could (I assume) be spread over any number of records (1->n). Interesting problem. I've made updates to the code so that the temp table ends up with an extra column that holds the number of days in the date range on each record. This allows the following:- select x.customerid, x.maxconsecutivedays, max(x.serviceenddate) as serviceenddate from ( select t1.customerid, t1.maxconsecutivedays, t2.serviceenddate from ( select customerid, max(numberofdays) as maxconsecutivedays from #t group by customerid ) t1 join #t t2 on t2.customerid=t1.customerid and t2.numberofdays=t1.maxconsecutivedays ) x group by x.customerid, x.maxconsecutivedays To identify the longest block of consecutive days (or the latest/longest if there is a tie) for each customer. This would allow you to subsequently dive back into the temp table to pull out the rows related to that block - by searching on the customerid and the serviceenddate (not maxconsecutivedays). Not sure this fits with your use case - but it may help. A: WITH chain_builder AS ( SELECT ROW_NUMBER() OVER(ORDER BY s.customerid, s.CLAIMID) as chain_ID, s.customerid, s.serv-start-date, s.service-end-date, s.CLAIMID, 1 as chain_count FROM services s WHERE s.serv-start-date <> ALL ( SELECT DATEADD(d, 1, s2.service-end-date) FROM services s2 ) UNION ALL SELECT chain_ID, s.customerid, s.serv-start-date, s.service-end-date, s.CLAIMID, chain_count + 1 FROM services s JOIN chain_builder as c ON s.customerid = c.customerid AND s.serv-start-date = DATEADD(d, 1, c.service-end-date) ), chains AS ( SELECT chain_ID, customerid, serv-start-date, service-end-date, CLAIMID, chain_count FROM chain_builder ), diff AS ( SELECT c.chain_ID, c.customerid, c.serv-start-date, c.service-end-date, c.CLAIMID, c.chain_count, datediff(day,c.serv-start-date,c.service-end-date)+1 daysdiff FROM chains c ), diff_sum AS ( SELECT chain_ID, customerid, serv-start-date, service-end-date, CLAIMID, chain_count, SUM(daysdiff) OVER (PARTITION BY chain_ID) as total_diff FROM diff ), diff_comp AS ( SELECT chain_ID, customerid, MAX(total_diff) OVER (PARTITION BY customerid) as total_diff FROM diff_sum ) SELECT DISTINCT ds.CLAIMID, ds.customerid, ds.serv-start-date, ds.service-end-date, ds.total_diff as total_days, ds.chain_count FROM diff_sum ds JOIN diff_comp dc ON ds.chain_ID = dc.chain_ID AND ds.customerid = dc.customerid AND ds.total_diff = dc.total_diff ORDER BY customerid, chain_count OPTION (maxrecursion 0)
doc_4842
A: Add to dimens.xml following: <dimen name="abc_action_button_min_height_material" tools:override="true">@dimen/abc_action_bar_default_height_material</dimen> <dimen name="abc_action_button_min_width_material" tools:override="true">@dimen/abc_action_bar_default_height_material</dimen>
doc_4843
<tr><td style="background-image:url('search_images/Zyra.png')">Zyra</td></tr> I've tried with different quotes and without the url() but in all cases only the text shows. EDIT: Going to post my php code. echo "<td style='width:100%; background-image: url(search_images/".$row["champion"].".png)'>".$row["champion"]."</td>"; This works in that it shows the images with the text over them except it shows just a single row and the cell size is fit to the text instead of the background image. I want the rows to fill the width of the browser window and the cells to be the size of the background image. A: Your code should work fine, check your browser console for errors, if it says the image is not found then you might be mistyping the image path. If the image and the HTML file being served are in the same directory you can use background-image:url('./image.jpg');, otherwise a full path is needed starting from the HTML page's directory like background-image: url('./firstDir/secondDir/image.jpg');. Here is a working example of your code working: <table> <tr> <td style="height:80px; width:100px; line-height:70px; background-image: url(https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQJbUiuUbKuYmKJfS4dYY0XGtRCGmNTco916Tyfiuf84wkhuWSj); background-size: 100% 100%; color:#F00; font-weight:bold;">This is test</td> </tr> </table> A: Ensure that you are putting <table> tags around your <tr> and <td> tags (this is what makes the snippet work). You can also add a width and height to the if you'd like to show more of the image. td.bg{ background-image:url('https://cdn.pixabay.com/photo/2016/03/28/12/35/cat-1285634_960_720.png') } <table> <tr> <td class="bg">Zyra</td> </tr> </table> A: There is nothing wrong with your code. My guess is that because you are using a png file, which may generate white background for those blank pixels. Below is an example, showing it works. <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8" /> </head> <body> <table> <tr> <td style="background-image:url('https://i.stack.imgur.com/Np80G.jpg?s=48&g=1'); background-size: auto; background-repeat: no-repeat; color: white; font-weight: bold; padding: 20px;"> some text here </td> </tr> </table> </body> </html>
doc_4844
I want to convert each community to a new graph. How should I do this? A: Since you do not provide data, I will use a simplified version of your graph to illustrate. ## Example graph library(igraph) g <- graph_from_literal(1-2-3-4-1, 2-5-4, 2-6, 6-7-10-8-6, 6-9-10) CL = cluster_louvain(g) plot(CL, g) In order to graph the individual communities, you can use induced_subgraph to get the subgraphs and then use the like any other graph, including plotting them. ## Get graphs for each community C1 = induced_subgraph(g, which(membership(CL) == 1)) C2 = induced_subgraph(g, which(membership(CL) == 2)) plot(C1) plot(C2) Note: I combined the graphs by hand. They were printed separately.
doc_4845
I have given the access to /opt/data_upload so that I can make use of this directory to save images uploaded from PHP and fetch it back on Ajax Get Request. My Apache config in /etc/apache2/apache2.conf looks like this Alias /data_uploads "/opt/data_uploads/" <Directory "/opt/data_uploads/"> Options Indexes FollowSymLinks MultiViews Require all granted AllowOverride all Order allow,deny Allow from all </Directory> But the problem is that when I do http://123.45.67.89/data_uploads from browser it is fully accessible to everyone which is dangerous and anyone can see the images uploaded there. To avoid this i tried to Require all denied now i get 403 but also my all Ajax get requests are also failed. Now i want to make my website to access it but if someone tries to access http://123.45.67.89/data_uploads should say 403, How can i overcome with this issue ? A: In your configuration you give access to everyone to your upload directory. You must remove this, or only allow your IP. But in your case, what you want is to permit your users to upload, and download files that they are allowed to. It means you want their http requests be able to upload/download files. These http request won't access the upload directory directly but they will call your php application. Then it's your php application that would be able to upload to this directory (then write to this directory) and read from this directory. For this you have to give read/write permissions to the apache user running process with something like chmod and/or chown. And finally, you'll have to write a PHP controller able to treat upload and download calls. That php code will write and read from your upload directory.
doc_4846
i have two physical machines , one is linux mint and the other is window8 i have a virtual box installed on win8 besides launched centos7. i had sshd service setted up in centos7 and port redirecting from win8 2222 to centos 22. when i typed ssh -p 2222 user@win8's address i got this: ssh_exchange_identification: read: Connection reset by peer however when i establish a connection using XManager with address 127.0.0.1 on port 2222, it connected!
doc_4847
try { await asyncFunction(); // expect error assert(false) // to make 100% fail } catch (err) { assert(err) // means 'assert(true) } Now I need to use "expect" from chai lib and I don't know how to write exactly the same test with 'expect' syntax A: You might try expect.fail("This should've not happenned"); or another "more readable" alternative should.fail("This should've not happenned"); Chai docs In this section looks like there is a cool idiomatic way to perform what you want: const action = function() { yourSyncFunction() } expect(action).to.throw(YourError) And here there's the DSL for testing promises. (You need to install the "As promised" plugin) yourAsyncFunction().should.be.rejectedWith(Error)
doc_4848
A: It might be that the SYSTEM account needs added to Team Foundation Valid Users A: configure build agent with a valid user or use a separate build user.
doc_4849
Here a short example for the template part: <table> <thead> <tr> <th> Check </th> <th> Title </th> </tr> </thead> <list-tbody v-for="element in elements" :element="element"> </list-tbody> </table> and this is the child component <tbody> <tr> <td> <input type="checkbox"> </td> <td> {{element.title}} </td> </tr> </tbody> A: You should really stick to emitting values to maintain separation of your components. That being said, you can do the following if you really wanted to grab the data all at once: First, you'll need a data attribute in your child component that your checkbox uses with v-model. For the sake of this example, let's just call it checkbox_value. Once you've done that, you can do something like the following in your parent component method: var checkbox_values = []; this.$children.forEach(function(child) { //you can check the child type here if you have other non-checkbox children checkbox_values.push(child.$data.checkbox_value); }); Of course, I wouldn't encourage you to do something like this, but you'll have to make that judgement call. Note: The above will return values only. You could push object key/value pairs instead! A: As mentioned in the comments you could handle this in two ways: * *Use Vuex and mutate the elements array from the child component. *Emit an event on each selection click event to the parent and the parent will update the elements array. You prefer the second because you're not using Vuex and that's OK. Once you're having the data "linked" between child component and parent you can use a filter method to only show the selected elements. Please have a look at the demo below or the fiddle from my comment. const listTbodyVuex = { props: ['element'], template: ` <tbody> <tr> <td> <input type="checkbox" @click="selected"> </td> <td> {{element.title}} </td> </tr> </tbody> `, methods: { ...Vuex.mapMutations(['changeSelection']), selected(evt) { //console.log('clicked', evt.target.checked, this.changeSelection) // changeSelection mutation could be also called with-out mapping // this.$store.commit('changeSelection', ...); this.changeSelection({ id: this.element.id, selected: evt.target.checked }); } } } const listTbodyEvents = { props: ['element'], template: ` <tbody> <tr> <td> <input type="checkbox" @click="selected"> </td> <td> {{element.title}} </td> </tr> </tbody> `, methods: { selected(evt) { console.log('clicked', evt.target.checked) this.$emit('selected', { element: this.element, newSelection: evt.target.checked }) } } } const store = new Vuex.Store({ state: { elements: [ { id: 0, title: 'first', selected: false }, { id: 1, title: 'second', selected: false }, { id: 2, title: 'third', selected: false } ] }, mutations: { changeSelection(state, {id, selected}) { let element = state.elements .filter((element) => element.id === id)[0]; element.selected = selected; //console.log('update element', JSON.parse(JSON.stringify(element))); Vue.set(state.elements, element.id, element); } } }) new Vue({ el: '#app', store, data() { return { elements: [ { id: 0, title: 'first', selected: false }, { id: 1, title: 'second', selected: false }, { id: 2, title: 'third', selected: false } ] } }, computed: { ...Vuex.mapState({ vuexElements: (state) => state.elements }) }, components: { listTbodyEvents, listTbodyVuex }, methods: { updateElement(data) { let element = this.elements .filter((element) => element.id === data.element.id)[0]; element.selected = data.newSelection; // console.log('update', element) }, filterSelected(data) { // console.log('filter', data.filter((item) => console.log(item.selected))) return data.filter((item) => item.selected); } } }) <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/3.0.0/vuex.js"></script> <div id="app"> <h1>Example with vuex</h1> <table> <thead> <tr> <th> Check </th> <th> Title </th> </tr> </thead> <list-tbody-vuex v-for="element in elements" :element="element" :key="element.id"> </list-tbody-vuex> </table> <pre>only selected: {{filterSelected(vuexElements)}}</pre> <pre>{{vuexElements}}</pre> <hr/> <h1>Example with events</h1> <table> <thead> <tr> <th> Check </th> <th> Title </th> </tr> </thead> <list-tbody-events v-for="element in elements" :element="element" :key="element.id" @selected="updateElement"> </list-tbody-events> </table> <pre>only selected: {{filterSelected(elements)}}</pre> <pre>{{elements}}</pre> </div>
doc_4850
However, in iOS 7, portrait works fine, but when the user is in landscape, whatever article they choose it always displays the first article in that particular category in the scroll view. Hope that makes sense! I have a method that pushes the information: ArticleViewController* avc = [[[ArticleViewController alloc] initWithNibName: @"ArticleViewController" bundle: nil] autorelease]; avc.section = art.section; avc.articleNumber = [avc.section.articles indexOfObject: art]; [self.navigationController pushViewController: avc animated: YES];
doc_4851
In my abstract class MyCbo_Abstract (derived from ComboBox class), I want to create a custom property that when set will subtract all the control's event handlers, set the base property value, then re-add all the control's event handlers. What I have so far I have a concrete ComboBox class derived from an abstract ComboBox class derived from Microsoft's ComboBox class. public abstract class MyCbo_Abstract : ComboBox { public MyCbo_Abstract() : base() { } } public partial class MyCboFooList : MyCbo_Abstract { public MyCboFooList() : base() { } } My main Form class subscribes to certain base ComboBox events. Note: The designer has: this.myCboFooList = new MyCboFooList(); public partial class FormMain : Form { public FormMain() { myCboFooList.SelectedIndexChanged += myCboFooList_SelectedIndexChanged; } private void myCboFooList_SelectedIndexChanged(object sender, EventArgs e) { // do stuff } } There are times when I want to suppress the invocation of defined event handlers, e.g., when I programmatically set a ComboBox object's SelectedIndex property. Instead of having to remember to write the code to subtract and re-add event handlers each time I want to modify the SelectedIndex property and suppress its events, I want to create a custom property SelectedIndex_NoEvents that when set will subtract all the control's event handlers, set the base property value SelectedIndex, then re-add all the control's event handlers. The problem My problem is that I don't know how to iterate over a EventHandlerList because it has no GetEnumerator. And, in looking at the list in the debugger, saveEventHandlerList is a weird chained thing that I can't figure out how to otherwise traverse. public abstract class MyCbo_Abstract : ComboBox { int selectedIndex_NoEvents; public int SelectedIndex_NoEvents { get { return base.SelectedIndex; } set { EventHandlerList saveEventHandlerList = new EventHandlerList(); saveEventHandlerList = Events; //foreach won't work - no GetEnumerator available. Can't use for loop - no Count poprerty foreach (EventHandler eventHandler in saveEventHandlerList) { SelectedIndexChanged -= eventHandler; } base.SelectedIndex = value; //foreach won't work - no GetEnumerator available. Can't use for loop - no Count poprerty foreach (EventHandler eventHandler in saveEventHandlerList) { SelectedIndexChanged += eventHandler; } saveEventHandlerList = null; } } //Probably don't need this public override int SelectedIndex { get { return base.SelectedIndex; } set { base.SelectedIndex = value; } } public DRT_ComboBox_Abstract() : base() { } } A: Before giving you the solution that I created, let me say that this feels extremely hacky. I urge you to seriously think about another solution. There may be all kinds of crazy edge cases where this code breaks down, I haven't thoroughly tested it beyond the example code shown below. Add the following utility class: public class SuspendedEvents { private Dictionary<FieldInfo, Delegate> handlers = new Dictionary<System.Reflection.FieldInfo, System.Delegate>(); private object source; public SuspendedEvents(object obj) { source = obj; var fields = obj.GetType().GetFields(BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); foreach (var fieldInfo in fields.Where(fi => fi.FieldType.IsSubclassOf(typeof(Delegate)))) { var d = (Delegate)fieldInfo.GetValue(obj); handlers.Add(fieldInfo, (Delegate)d.Clone()); fieldInfo.SetValue(obj, null); } } public void Restore() { foreach (var storedHandler in handlers) { storedHandler.Key.SetValue(source, storedHandler.Value); } } } You can use it like this: var events = new SuspendedEvents(obj); //all event handlers on obj are now detached events.Restore(); // event handlers on obj are now restored. I used the following test setup: void Main() { var obj = new TestObject(); obj.Event1 += (sender, e) => Handler("Event 1"); obj.Event1 += (sender, e) => Handler("Event 1"); obj.Event2 += (sender, e) => Handler("Event 2"); obj.Event2 += (sender, e) => Handler("Event 2"); obj.Event3 += (sender, e) => Handler("Event 3"); obj.Event3 += (sender, e) => Handler("Event 3"); Debug.WriteLine("Prove events are attached"); obj.RaiseEvents(); var events = new SuspendedEvents(obj); Debug.WriteLine("Prove events are detached"); obj.RaiseEvents(); events.Restore(); Debug.WriteLine("Prove events are reattached"); obj.RaiseEvents(); } public void Handler(string message) { Debug.WriteLine(message); } public class TestObject { public event EventHandler<EventArgs> Event1; public event EventHandler<EventArgs> Event2; public event EventHandler<EventArgs> Event3; public void RaiseEvents() { Event1?.Invoke(this, EventArgs.Empty); Event2?.Invoke(this, EventArgs.Empty); Event3?.Invoke(this, EventArgs.Empty); } } It produces the following output: Prove events are attached Event 1 Event 1 Event 2 Event 2 Event 3 Event 3 Prove events are detached Prove events are reattached Event 1 Event 1 Event 2 Event 2 Event 3 Event 3 A: There is no way to easily disable event firing of WinForm controls exposed in the .Net framework. However, the Winform controls follow a standard design pattern for events in that all event signatures are based on the EventHandler Delegate and the registered event handlers are stored in an EventHandlerList that is defined in the Control Class. This list is stored in a field (variable) named "events" and is only publicly exposed via the read-only property Events. The class presented below uses reflection to temporarily assign null to the events field effectively removing all event handlers registered for the Control. While it may be an abuse of the pattern, the class implements the IDisposable Interface to restore the events field on disposal of the class instance. The reason for this is to facilitate the use of the using block to wrap the class usage. public class ControlEventSuspender : IDisposable { private const string eventsFieldName = "events"; private const string headFieldName = "head"; private static System.Reflection.FieldInfo eventsFieldInfo; private static System.Reflection.FieldInfo headFieldInfo; private System.Windows.Forms.Control target; private object eventHandlerList; private bool disposedValue; static ControlEventSuspender() { Type compType = typeof(System.ComponentModel.Component); eventsFieldInfo = compType.GetField(eventsFieldName, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); headFieldInfo = typeof(System.ComponentModel.EventHandlerList).GetField(headFieldName, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); } private static bool FieldInfosAquired() { if (eventsFieldInfo == null) { throw new Exception($"{typeof(ControlEventSuspender).Name} could not find the field '{ControlEventSuspender.eventsFieldName}' on type Component."); } if (headFieldInfo == null) { throw new Exception($"{typeof(ControlEventSuspender).Name} could not find the field '{ControlEventSuspender.headFieldName}' on type System.ComponentModel.EventHandlerList."); } return true; } private ControlEventSuspender(System.Windows.Forms.Control target) // Force using the the Suspend method to create an instance { this.target = target; this.eventHandlerList = eventsFieldInfo.GetValue(target); // backup event hander list eventsFieldInfo.SetValue(target, null); // clear event handler list } public static ControlEventSuspender Suspend(System.Windows.Forms.Control target) { ControlEventSuspender ret = null; if (FieldInfosAquired() && target != null) { ret = new ControlEventSuspender(target); } return ret; } protected virtual void Dispose(bool disposing) { if (!this.disposedValue) { if (disposing) { if (this.target != null) { RestoreEventList(); } } } this.disposedValue = true; } public void Dispose() { Dispose(true); } private void RestoreEventList() { object o = eventsFieldInfo.GetValue(target); if (o != null && headFieldInfo.GetValue(o) != null) { throw new Exception($"Events on {target.GetType().Name} (local name: {target.Name}) added while event handling suspended."); } else { eventsFieldInfo.SetValue(target, eventHandlerList); eventHandlerList = null; target = null; } } } Example usage in the button1_Click method: public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { using (ControlEventSuspender.Suspend(comboBox1)) { comboBox1.SelectedIndex = 3; // SelectedIndexChanged does not fire } } private void button2_Click(object sender, EventArgs e) { comboBox1.SelectedIndex = -1; // clear selection, SelectedIndexChanged fires } private void button3_Click(object sender, EventArgs e) { comboBox1.SelectedIndex = 3; // SelectedIndexChanged fires } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { Console.WriteLine("index changed fired"); System.Media.SystemSounds.Beep.Play(); } } SoapBox Diatribe Many will say that the use of Reflection to access non-public class members is dirty or some other derogatory term and that it introduces a brittleness to the code as someone may change the underlying code definition such that the code that relies on member names (magic strings) is no longer valid. This is a valid concern, but I view it as no different than code that accesses external databases. Reflection can be thought of a query of a type (datatable) from an assembly (database) for specific fields (members: fields, properties, events). It is no more brittle than a SQL statement such as Select SomeField From SomeTable Where AnotherField=5. This type of SQL code is prevent in the world and no one thinks twice about writing it, but some external force could easily redefine the database you code relies on an render all the magic string SQL statements invalid as well. Use of hard coded names is always at risk of being made invalid by change. You have to weigh the risks of moving forward versus the option of being frozen in fear of proceeding because someone wants to sound authoritative (typically a parroting of other such individuals) and criticize you for implementing a solution that solves the current problem. A: I was hoping to write code that would programatically locate all event handler method names created using controlObject.Event += EventHandlerMethodName, but as you see in the other answers, code to do this is complicated, limited, and perhaps not able to work in all cases This is what I came up with. It satisfies my desire to consolidate the code that subtracts and re-adds event handler method names into my abstract class, but at the expense of having to write code to store and manage event handler method names and having to write code for each control property where I want to suppress the event handler, modify the property value, and finally re-add the event handler. public abstract class MyCbo_Abstract : ComboBox { // create an event handler property for each event the app has custom code for [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] private EventHandler evSelectedValueChanged; [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public EventHandler EvSelectedValueChanged { get => evSelectedValueChanged; set => evSelectedValueChanged = value; } public MyCbo_Abstract() : base() { } // Create a property that parallels the one that would normally be set in the main body of the program public object _DataSource_NoEvents { get { return base.DataSource; } set { SelectedValueChanged -= EvSelectedValueChanged; if (value == null) { base.DataSource = null; SelectedValueChanged += EvSelectedValueChanged; return; } string valueTypeName = value.GetType().Name; if (valueTypeName == "Int32") { base.DataSource = null; SelectedValueChanged += EvSelectedValueChanged; return; } //assume StringCollection base.DataSource = value; SelectedValueChanged += EvSelectedValueChanged; return; } } } public partial class MyCboFooList : MyCbo_Abstract { public MyCboFooList() : base() { } } Designer has this.myCboFooList = new MyCboFooList(); Main form code public partial class FormMain : Form { public FormMain() { myCboFooList.SelectedValueChanged += OnMyCboFooList_SelectedValueChanged; myCboFooList.EvSelectedValueChanged = OnMyCboFooList_SelectedValueChanged; } private void OnMyCboFooList_SelectedValueChanged(object sender, EventArgs e) { // do stuff } } And now, if I want to set a property and suppress event(s), I can write something like the following and not have to remember to re-add the event handler method name myCboFooList._DataSource_NoEvents = null;
doc_4852
Sets the main page content and base URL. Can someone please explain this in a more detailed way to me? A: I am pretty certain that the baseURL is used just like in regular web pages to properly load ressources that are referenced using relative links. Now the question is, how to set that base URL to a particular folder in the app directory. A: This is how mainly content is loaded in a webView. either from a local html file or through a url. //this is to load local html file. Read the file & give the file contents to webview. [webView loadHTMLString:someHTMLstring baseURL:[NSURL URLWithString:@""]]; //if webview loads content through a url then [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"]]] A: - (void) loadHTMLString:(NSString *)string baseURL:(nullable NSURL *)baseURL; is used to load local HTML file, parameter string means content of html file, if your HTML file contains some href tag with relative path, you should set the parameter baseUrl with the base address of the HTML file, or set it nil. NSString *cachePath = [self cachePath]; NSString *indexHTMLPath = [NSString stringWithFormat:@"%@/index.html", cachePath]; if ([self fileIsExsit:indexHTMLPath]) { NSString *htmlCont = [NSString stringWithContentsOfFile:indexHTMLPath encoding:NSUTF8StringEncoding error:nil]; NSURL *baseURL = [NSURL fileURLWithPath:cachePath]; [self.webView loadHTMLString:htmlCont baseURL:baseURL]; } - (NSString *)cachePath { NSArray* cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); return [cachePath[0] stringByAppendingPathComponent:@"movie"]; }
doc_4853
# coffee @route 'magnets', path: '/magnets/lesson/:lessonCname' data: -> if @ready() debugger; console.log("route.params", @params) with this code, in the debug console I will get: this.params [] this.params.lessonCname "despite-magnets-01" typeof(this.params) "object" this.params.length 0 this.ready() but in passing the params object to a server method, the methods (ie "lessonCname") disappear. If my understanding is correct, then the near-term question is what is the best way to retrieve/convert these methods to {property:value} so they can be serialized and passed to server calls? A: There are two easy ways of solving your problem, you can either set a global variable from within the data scope (but this is considered bad practice, at least IMO) or you can use the "data" function, which returns the data context for the current template: data: -> window._globalscopedata = @params.whatever #setting global variable return someCollection.findOne #returns data context _id: @params.whatever when proccessing this route I will have the whatever param available in _globalscoredata and my document available in the template context. A: The params property attached to a RouteController is an object with the following properties : * *hash : the value of the URL hash. *query : an object consisting of key/value pairs representing the query string. *a list of URL fragments with their name and actual value. Let's take an example, for this route definition : // using iron:router@1.0.0-pre2 new route definition Router.route("/posts/:slug"); And this URL typed in the browser address bar : /posts/first-post#comments?lang=en We can use the console to find out precisely what params will actually contain : > Router.current().params Which will display this result : Object { hash: "comments", slug: "first-post", query: { lang: "en" } } Here slug is already a property of the params object whose value is "first-post", this is not a method. If you want to extract from params these URL fragments as an object of key/value pairs, you can use underscore omit : // getting rid of the hash and the query string var parameters=_.omit(this.params,["hash","query"]); A: Take a look at the source code for retrieving the parameters from a path. params is an array, but may have named properties. To iterate over everything, you can use the for in loop: for(var x in myArray){ // Do something. } In this way, you can copy over everything to a new object (there may be a simpler way to create a copy).
doc_4854
<Button size="tiny" /> However the Dropdown, which in many cases looks just like a button and is placed on a row with buttons, does not appear to take the "size" parameter. https://react.semantic-ui.com/modules/dropdown Is there a good way to apply the same size to the dropdown as to other elements e.g. Buttons in a row? (i.e. not just fiddling with custom CSS, but something more maintainable). A: I think the right way should be wrap it inside a form, and apply the size classes to the form. The form could be a form tag, but also could be div: <form className='ui form small'> <Dropdown> or <div className='ui form mini'> <Dropdown> A: Assuming your Dropdown has the button option set, you can pass the size you want in the className prop. For example: <Dropdown text='Add Friend' icon='plus' labeled button className='icon tiny'> A: I think this is if you want to create the same size between dropdown and another component like button using size attribut, you can put the dropdown inside the button : import React from 'react' import { Dropdown, Menu, Button } from 'semantic-ui-react' const options = [ { key: 1, text: 'Choice 1', value: 1 }, { key: 2, text: 'Choice 2', value: 2 }, { key: 3, text: 'Choice 3', value: 3 }, ] const DropdownExampleSimple = () => ( <div> <Button size="tiny" > <Dropdown text='Dropdown' options={options} simple item /> </Button> <Button size="tiny"> This is Button </Button> </div> ) export default DropdownExampleSimple this is the result : Maybe can help you, thanks A: I had referenced this answer to find the solution. I had to give a css class of line-height: unset; (which may override a default line-height for the same class). HTML <Dropdown className="equal-dropdown-height" placeholder="State" options={stateOptions} search selection /> CSS .equal-dropdown-height .text { line-height: unset; } A: A flexible way to do this is to pass in icon={null} and then set the trigger property to whatever node you want to display: import React from 'react' import { Dropdown, Icon } from 'semantic-ui-react' const LargeIconDropdown = () => ( <Dropdown icon={null} trigger={ <Icon link name='ellipsis vertical' size='large' /> }> <Dropdown.Menu> <Dropdown.Item icon='pencil' text='Edit' /> </Dropdown.Menu> </Dropdown> ) export default LargeIconDropdown You can find an example of this in the Semantic UI React Dropdown Documentation here
doc_4855
Here's a snippet with the plugin: jQuery.extend({ highlight: function (node, re, nodeName, className, titleVal) { if (node.nodeType === 3) { var match = node.data.match(re); if (match) { console.log('Title after: ' + titleVal); var highlight = document.createElement(nodeName || 'span'); highlight.className = className || 'highlight'; highlight.setAttribute('title', titleVal); var wordNode = node.splitText(match.index); wordNode.splitText(match[0].length); var wordClone = wordNode.cloneNode(true); highlight.appendChild(wordClone); wordNode.parentNode.replaceChild(highlight, wordNode); return 1; //skip added node in parent } } else if ((node.nodeType === 1 && node.childNodes) && // only element nodes that have children !/(script|style)/i.test(node.tagName) && // ignore script and style nodes !(node.tagName === nodeName.toUpperCase() && node.className === className)) { // skip if already highlighted for (var i = 0; i < node.childNodes.length; i++) { i += jQuery.highlight(node.childNodes[i], re, nodeName, className); } } return 0; } }); jQuery.fn.unhighlight = function (options) { var settings = { className: 'highlight', element: 'span' }; jQuery.extend(settings, options); return this.find(settings.element + "." + settings.className).each(function () { var parent = this.parentNode; parent.replaceChild(this.firstChild, this); parent.normalize(); }).end(); }; jQuery.fn.highlight = function (words, options) { var settings = { className: 'highlight', element: 'span', titleVal: 'Default', caseSensitive: false, wordsOnly: false }; jQuery.extend(settings, options); console.log('Title passed:' + settings.titleVal); if (words.constructor === String) { words = [words]; } words = jQuery.grep(words, function(word, i){ return word != ''; }); words = jQuery.map(words, function(word, i) { return word.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); }); if (words.length == 0) { return this; }; var flag = settings.caseSensitive ? "" : "i"; var pattern = "(" + words.join("|") + ")"; if (settings.wordsOnly) { pattern = "\\b" + pattern + "\\b"; } var re = new RegExp(pattern, flag); return this.each(function () { console.log('Title before: ' + settings.titleVal); jQuery.highlight(this, re, settings.element, settings.className, settings.titleVal); }); }; abbr { text-decoration: underline; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p>These are a collection of words for an example. Kthx.</p> <button onclick="$('p').highlight('collection', {element: 'abbr', titleVal: 'A group of things or people'})">What's "collection"?</button> Look at the console. Notice that the title is successfully passed, is defined right before calling the plugin function, then is undefined inside it. I'm pretty sure it's something simple, but I'm not seeing it. A: Changing that line in the for loop i += jQuery.highlight(node.childNodes[i], re, nodeName, className); to i += jQuery.highlight(node.childNodes[i], re, nodeName, className, titleVal); fixes it.
doc_4856
My Code: SELECT DISTINCT T1.FILENUM, T5.OFG, T4.UN FROM T1 LEFT OUTER JOIN T2 ON T1.ID=T2ID LEFT OUTER JOIN T3 ON T1.ID = T3.ID LEFT OUTER JOIN T4 ON T3.ID=T4ID LEFT OUTER JOIN T5 ON T2.ID = T5.ID WHERE DATECondition AND T1.FILENUM LIKE 'S%' AND (T4.UN = 26 OR T4.UN = 25 OR T4.UN = 24 OR T4.UN = 32) Results FILENUM OFG UN S1 S 26 S1 C 25 S1 D 26 S2 S 26 S2 S 24 S3 S 26 S4 S 26 S4 C 25 S5 S 32 S6 S 24 S7 S 25 S7 S 24 What these tables means are that there are complaints of records of filenum that UN are users and routings on the complaint. OFG is the complainant. UN is the user routing the Filenums. * *What I wanted to add extra is, only when (OFG not like '[cd]%' or OFG IS NULL), then I also want to make sure that for a row: if OFG is C or D, please exclude ALL rows even if it has S. *I want to scan these rows and look at the UN. If the count for filenum that UN has 24 and UN is also 26 equals 2 or more, only show the filenum row with un is 26. The result is that, I have a user that is a supervisor is always accessing the complaint and also the same user (UN) who also only handles the complaint alone. I want to show that if that supervisor user access the case with another user, don't include his row because he may be just reading the complaint. There are also 3 other users I want to compare this spervisor user. So another example, if count of filenum of sueprvisor user is 1, include the row in my result. If the count for filenum where un in (25, 24), 2 users one being the supervisor, is greater than 2, then only include the row with un that is 25. Repeat this with un in (26, 24) and un in (32, 24). Results 2: FILENUM OFG UN S2 S 26 S3 S 26 S5 S 32 S6 S 24 S7 S 25 A: Try this. CREATE TABLE #test1 (FILENUM VARCHAR(50),OFG CHAR(1),UN INT) INSERT #test1 VALUES ('S1','S',26),('S1','C',25),('S1','D',26), ('S2','S',26),('S2','S',24),('S3','S',26), ('S4','S',26),('S4','C',25),('S5','S',32), ('S6','S',24),('S7','S',25),('S7','S',24) WITH cte AS (SELECT Row_number()OVER(partition BY filenum ORDER BY un DESC) rn, * FROM #test1 WHERE FILENUM NOT IN(SELECT FILENUM FROM #test1 WHERE OFG IN ( 'C', 'D' ))) SELECT FILENUM,OFG,UN FROM cte WHERE rn = 1 OUTPUT : FILENUM OFG UN ------- --- -- S2 S 26 S3 S 26 S5 S 32 S6 S 24 S7 S 25
doc_4857
the code for the vhosts file is # Virtual Hosts # <VirtualHost *:80> ServerName localhost ServerAlias localhost SetEnv APP_ENV prod SetEnv APP_SECRET b33c77e602bc1bafb66f673c1e31aca3 SetEnv DATABASE_URL mysql://root@127.0.0.1:3306/gpac DocumentRoot "${INSTALL_DIR}/www/gpac/public" <Directory "${INSTALL_DIR}/www/gpac/public/"> Options +Indexes +Includes +FollowSymLinks +MultiViews AllowOverride All Require all granted </Directory> </VirtualHost> the public/index.php is <?php use App\Kernel; use Symfony\Component\Debug\Debug; use Symfony\Component\Dotenv\Dotenv; use Symfony\Component\HttpFoundation\Request; require __DIR__.'/../vendor/autoload.php'; // The check is to ensure we don't use .env in production if (!isset($_SERVER['APP_ENV'])) { if (!class_exists(Dotenv::class)) { throw new \RuntimeException('APP_ENV environment variable is not defined. You need to define environment variables for configuration or add "symfony/dotenv" as a Composer dependency to load variables from a .env file.'); } (new Dotenv())->load(__DIR__.'/../.env'); } $env = $_SERVER['APP_ENV'] ?? 'dev'; $debug = (bool) ($_SERVER['APP_DEBUG'] ?? ('prod' !== $env)); if ($debug) { umask(0000); Debug::enable(); } if ($trustedProxies = $_SERVER['TRUSTED_PROXIES'] ?? false) { Request::setTrustedProxies(explode(',', $trustedProxies), Request::HEADER_X_FORWARDED_ALL ^ Request::HEADER_X_FORWARDED_HOST); } if ($trustedHosts = $_SERVER['TRUSTED_HOSTS'] ?? false) { Request::setTrustedHosts(explode(',', $trustedHosts)); } $kernel = new Kernel($env, $debug); $request = Request::createFromGlobals(); $response = $kernel->handle($request); $response->send(); $kernel->terminate($request, $response); when I run the php bin/console cache:clear --env=prod it gives an error because the .env file does not exist the code for config/services.yaml is # Put parameters here that don't need to change on each machine where the app is deployed # https://symfony.com/doc/current/best_practices/configuration.html#application-related-configuration parameters: locale: 'fr' version: 1.0.0 default_alert: council_meeting: 7 # days project_step: 7 # days resource_report: 1 # years resource_contract: 1 # month resource_capability: 1 # month services: # default configuration for services in *this* file _defaults: autowire: true # Automatically injects dependencies in your services. autoconfigure: true # Automatically registers your services as commands, event subscribers, etc. public: false # Allows optimizing the container by removing unused services; this also means # fetching services directly from the container via $container->get() won't work. # The best practice is to be explicit about your dependencies anyway. # makes classes in src/ available to be used as services # this creates a service per class whose id is the fully-qualified class name App\: resource: '../src/*' exclude: '../src/{Entity,Migrations,Tests,Kernel.php}' # controllers are imported separately to make sure services can be injected # as action arguments even if you don't extend any base controller class App\Controller\: resource: '../src/Controller' tags: ['controller.service_arguments'] # add more service definitions when explicit configuration is needed # please note that last definitions always *replace* previous ones activity: class: App\Service\ActivityLogger public: true arguments: ['@doctrine.orm.entity_manager', '@security.token_storage', '@request_stack'] process: class: App\Service\ProcessProvider public: true arguments: ['%kernel.project_dir%'] App\Listener\LoginListener: arguments: ['@activity'] tags: - { name: kernel.event_subscriber } dpolac.twig_lambda.extension: class: DPolac\TwigLambda\LambdaExtension tags: [ { name: twig.extension } ] # --------------------- # Sonata Admin Services # --------------------- app.admin.user: public: true class: App\Admin\UserAdmin arguments: [~, App\Entity\User, App\Controller\UserAdminController] tags: - { name: sonata.admin, manager_type: orm, group: admin, label: class.User } app.admin.user_function: public: true class: App\Admin\UserFunctionAdmin arguments: [~, App\Entity\UserFunction, SonataAdminBundle:CRUD] tags: - { name: sonata.admin, manager_type: orm, group: admin, label: class.UserFunction } app.admin.skill_matrix: class: App\Admin\SkillMatrixAdmin arguments: [~, App\Entity\SkillMatrix, SonataAdminBundle:CRUD] tags: - { name: sonata.admin, manager_type: orm, label: class.SkillMatrix } app.admin.skill_matrix_category: class: App\Admin\SkillMatrixCategoryAdmin arguments: [~, App\Entity\SkillMatrixCategory, SonataAdminBundle:CRUD] tags: - { name: sonata.admin, manager_type: orm, group: skill, label: class.SkillMatrixCategory } calls: - [ setTemplate, [list, 'CRUD/Skill/list.html.twig']] app.admin.client: class: App\Admin\ClientAdmin arguments: [~, App\Entity\Client, SonataAdminBundle:CRUD] tags: - { name: sonata.admin, manager_type: orm, group: project, label: class.Client } calls: - [addChild, ['@app.admin.client_site']] app.admin.client_site: class: App\Admin\ClientSiteAdmin arguments: [~, App\Entity\ClientSite, SonataAdminBundle:CRUD] tags: - { name: sonata.admin, manager_type: orm, label: class.ClientSite} app.admin.client_numbers: class: App\Admin\ClientNumbersAdmin arguments: [~, App\Entity\ClientNumbers, SonataAdminBundle:CRUD] tags: - { name: sonata.admin, manager_type: orm, label: class.ClientNumbers} app.admin.resource: class: App\Admin\ResourceAdmin arguments: [~, App\Entity\Resource, SonataAdminBundle:CRUD, '@doctrine.orm.entity_manager'] tags: - { name: sonata.admin, manager_type: orm, group: rc, label: class.Resource } public: true calls: - [ setTemplate, [show, 'CRUD/Resource/show.html.twig']] - [addChild, ['@app.admin.resource_capability']] - [addChild, ['@app.admin.resource_contract']] - [addChild, ['@app.admin.resource_education']] - [addChild, ['@app.admin.resource_experience']] - [addChild, ['@app.admin.resource_lang']] - [addChild, ['@app.admin.resource_report']] app.admin.council: public: true class: App\Admin\CouncilAdmin arguments: [~, App\Entity\Council, SonataAdminBundle:CRUD] tags: - { name: sonata.admin, manager_type: orm, group: council, label: class.Council } calls: - [ setTemplate, [list, 'CRUD/Council/list.html.twig']] app.admin.council_meeting: class: App\Admin\CouncilMeetingAdmin arguments: [~, App\Entity\CouncilMeeting, SonataAdminBundle:CRUD] tags: - { name: sonata.admin, manager_type: orm, group: council, label: class.CouncilMeeting } public: true app.admin.resource_capability: class: App\Admin\ResourceCapabilityAdmin arguments: [~, App\Entity\ResourceCapability, SonataAdminBundle:CRUD] tags: - { name: sonata.admin, manager_type: orm , label: class.ResourceCapability} public: true app.admin.resource_contract: class: App\Admin\ResourceContractAdmin arguments: [~, App\Entity\ResourceContract, SonataAdminBundle:CRUD] tags: - { name: sonata.admin, manager_type: orm, label: class.ResourceContract} public: true app.admin.resource_education: class: App\Admin\ResourceEducationAdmin arguments: [~, App\Entity\ResourceEducation, SonataAdminBundle:CRUD] tags: - { name: sonata.admin, manager_type: orm , label: class.ResourceEducation} public: true app.admin.resource_experience: class: App\Admin\ResourceExperienceAdmin arguments: [~, App\Entity\ResourceExperience, SonataAdminBundle:CRUD] tags: - { name: sonata.admin, manager_type: orm , label: class.ResourceExperience} public: true app.admin.resource_lang: class: App\Admin\ResourceLangAdmin arguments: [~, App\Entity\ResourceLang, SonataAdminBundle:CRUD] tags: - { name: sonata.admin, manager_type: orm, label: class.ResourceLang} public: true app.admin.project: class: App\Admin\ProjectAdmin arguments: [~, App\Entity\Project, App\Controller\ProjectAdminController] tags: - { name: sonata.admin, manager_type: orm, group: project, label: class.Project } public: true calls: - [setTemplate, ['list', 'CRUD/Project\list.html.twig']] - [setTemplate, ['show', 'CRUD/Project\show.html.twig']] - [setTemplate, ['edit', 'CRUD/Project\edit.html.twig']] - [addChild, ['@app.admin.project_eval']] - [addChild, ['@app.admin.project_status']] - [addChild, ['@app.admin.project_alert']] app.admin.project_status: class: App\Admin\ProjectStatusAdmin arguments: [~, App\Entity\ProjectStatus, SonataAdminBundle:CRUD] tags: - { name: sonata.admin, manager_type: orm, label: class.ProjectStatus } public: true app.admin.project_eval: class: App\Admin\ProjectEvalAdmin arguments: [~, App\Entity\ProjectEval, SonataAdminBundle:CRUD] tags: - { name: sonata.admin, manager_type: orm, label: class.ProjectEval } public: true calls: - [addChild, ['@app.admin.project_step']] - [addChild, ['@app.admin.project_staff']] app.admin.project_staff: class: App\Admin\ProjectStaffAdmin arguments: [~, App\Entity\ProjectStaff, SonataAdminBundle:CRUD] tags: - { name: sonata.admin, manager_type: orm, label: class.ProjectStaff } public: true app.admin.project_step: class: App\Admin\ProjectStepAdmin arguments: [~, App\Entity\ProjectStep, SonataAdminBundle:CRUD] tags: - { name: sonata.admin, manager_type: orm, label: class.ProjectStep } public: true app.admin.activity: class: App\Admin\ActivityAdmin arguments: [~, App\Entity\Activity, App\Controller\ActivityAdminController] tags: - { name: sonata.admin, manager_type: orm, group: admin, label: class.Activity } public: true app.admin.project_alert: class: App\Admin\ProjectAlertAdmin arguments: [~, App\Entity\ProjectAlert, App\Controller\ProjectAlertAdminController] tags: - { name: sonata.admin, manager_type: orm, label: class.ProjectAlert } public: true app.admin.report_qual_theo: class: App\Admin\ReportQualTheoAdmin arguments: [~, App\Entity\ReportQualTheo, SonataAdminBundle:CRUD] tags: - { name: sonata.admin, manager_type: orm, group: frc, label: class.ReportQualTheo } public: true app.admin.report_qual_prat: class: App\Admin\ReportQualPratAdmin arguments: [~, App\Entity\ReportQualPrat, SonataAdminBundle:CRUD] tags: - { name: sonata.admin, manager_type: orm, group: frc, label: class.ReportQualPrat } public: true app.admin.resource_report: class: App\Admin\ResourceReportAdmin arguments: [~, App\Entity\ResourceReport, App\Controller\ResourceReportAdminController] tags: - { name: sonata.admin, manager_type: orm, group: frc, label: class.ResourceReport } public: true calls: - [addChild, ['@app.admin.resource_report_education']] - [addChild, ['@app.admin.resource_report_forum']] - [addChild, ['@app.admin.resource_report_project']] app.admin.resource_report_education: class: App\Admin\ResourceReportEducationAdmin arguments: [~, App\Entity\ResourceReportEducation, App\Controller\ResourceReportEducationAdminController] tags: - { name: sonata.admin, manager_type: orm, label: class.ResourceReportEducation } public: true app.admin.resource_report_forum: class: App\Admin\ResourceReportForumAdmin arguments: [~, App\Entity\ResourceReportForum, SonataAdminBundle:CRUD] tags: - { name: sonata.admin, manager_type: orm, label: class.ResourceReportForum } public: true app.admin.resource_report_project: class: App\Admin\ResourceReportProjectAdmin arguments: [~, App\Entity\ResourceReportProject, App\Controller\ResourceReportProjectAdminController] tags: - { name: sonata.admin, manager_type: orm, label: class.ResourceReportProject } public: true calls: - ['setTemplate', ['list', 'CRUD/ReportResourceProject\list.html.twig']] app.admin.report_council: class: App\Admin\ReportCouncilAdmin arguments: [~, App\Entity\ReportCouncil, SonataAdminBundle:CRUD] tags: - { name: sonata.admin, manager_type: orm, group: frc, label: class.ReportCouncil } public: true A: For symfony4 console the environment variables given in .htaccess or in webserver has no effect. so you need to provide the environment variable with the command. You should run following command to clear cache in production APP_ENV=prod php bin/console cache:clear If you are running command from windows cmd then you may need to run like: set APP_ENV=prod php bin/console cache:clear A: You could try changing the 'SetEnv APP_ENV prod' to 'SetEnv APP_ENV dev' in your VirtualHost file. # Virtual Hosts # <VirtualHost *:80> ServerName localhost ServerAlias localhost SetEnv APP_ENV dev #<-------------------------------------- here SetEnv APP_SECRET b33c77e602bc1bafb66f673c1e31aca3 SetEnv DATABASE_URL mysql://root@127.0.0.1:3306/gpac DocumentRoot "${INSTALL_DIR}/www/gpac/public" <Directory "${INSTALL_DIR}/www/gpac/public/"> Options +Indexes +Includes +FollowSymLinks +MultiViews AllowOverride All Require all granted </Directory> </VirtualHost>
doc_4858
If I'm unclear, here's a simple example that, hopefully, will help illustrate my question: Ana = red, 1 Beth = blue, 0 Cate = green, 3 David = yellow, 0 How would I, through R, segment the data set to create a new data frame that omits the cases for which the second variable = 0? In this example, I would have a new data frame that only includes Ana and Cate. Likewise, how would I do the opposite, i.e. create a data frame with only Beth and David? Thank you for your help! A: Assume this is your data.frame m <- data.frame(names = c("Ana", "Beth", "Cate", "David"), colors = c("blue", "blue", "green", "yellow"), numbers = c(1, 0, 3, 0)) m # names colors numbers #1 Ana blue 1 #2 Beth blue 0 #3 Cate green 3 #4 David yellow 0 If I understood correctly here are two ways to obtain your result id <- which(m[,"numbers"] > 0) m[id,] #1 Ana blue 1 #3 Cate green 3 or subset(m, numbers > 0) # names colors numbers #1 Ana blue 1 #3 Cate green 3 subset(m, numbers == 0) # names colors numbers #2 Beth blue 0 #4 David yellow 0 A: An alternative is to use split, which would return a list of two data.frames, one for the rows where numbers == 0 and those where "numbers > 0". A trick to use is in how R treats numbers when you convert them to logical values: anything that is not zero becomes TRUE. So, using @javlacalle's sample data, try: out <- split(m, as.logical(m$numbers)) out # $`FALSE` # names colors numbers # 2 Beth blue 0 # 4 David yellow 0 # # $`TRUE` # names colors numbers # 1 Ana blue 1 # 3 Cate green 3 You can access the relevant data.frames by their index position or their names: out[[1]] # names colors numbers # 2 Beth blue 0 # 4 David yellow 0 out[["FALSE"]] # names colors numbers # 2 Beth blue 0 # 4 David yellow 0
doc_4859
Took the get_certificates function from here: def get_certificates(self): from OpenSSL.crypto import _lib, _ffi, X509 """ https://github.com/pyca/pyopenssl/pull/367/files#r67300900 Returns all certificates for the PKCS7 structure, if present. Only objects of type ``signedData`` or ``signedAndEnvelopedData`` can embed certificates. :return: The certificates in the PKCS7, or :const:`None` if there are none. :rtype: :class:`tuple` of :class:`X509` or :const:`None` """ certs = _ffi.NULL if self.type_is_signed(): certs = self._pkcs7.d.sign.cert elif self.type_is_signedAndEnveloped(): certs = self._pkcs7.d.signed_and_enveloped.cert pycerts = [] for i in range(_lib.sk_X509_num(certs)): pycert = X509.__new__(X509) # pycert._x509 = _lib.sk_X509_value(certs, i) # According to comment from @ Jari Turkia # to prevent segfaults use '_lib.X509_dup(' pycert._x509 = _lib.X509_dup(_lib.sk_X509_value(certs, i)) pycerts.append(pycert) if not pycerts: return None return tuple(pycerts) I am using the code as follows: security_directory = pefile.DIRECTORY_ENTRY["IMAGE_DIRECTORY_ENTRY_SECURITY"] ds_address = pe_data.OPTIONAL_HEADER.DATA_DIRECTORY[security_directory].VirtualAddress ds_size = pe_data.OPTIONAL_HEADER.DATA_DIRECTORY[security_directory].Size if 0 == ds_address: return False digital_signature = file_data[ds_address + 8:] pkcs = OpenSSL.crypto.load_pkcs7_data(OpenSSL.crypto.FILETYPE_ASN1, bytes(digital_signature)) cert_list = get_certificates(pkcs) for cert in cert_list: cert_dump = OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, cert) cert_data = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert_dump) algorithm = cert_data.get_signature_algorithm().decode("utf-8") serial = cert_data.get_serial_number() serial_str = "%x" % serial issuer_str = cert_data.get_subject().CN print("[INFO]\t\tSerial: [%s] - Algorithm: [%s] Issuer: [%s]" % (serial_str, algorithm, issuer_str)) But only the sha1 chain is extracted (covered sensitive data with *s): [INFO] Checking: some_file [INFO] Serial: [*******************************] - Algorithm: [sha1WithRSAEncryption] Issuer: [**********************] <- correct [INFO] Serial: [*******************************] - Algorithm: [sha1WithRSAEncryption] Issuer: [DigiCert Assured ID Code Signing CA-1] [INFO] Serial: [*******************************] - Algorithm: [sha256WithRSAEncryption] Issuer: [DigiCert Trusted G4 RSA4096 SHA256 TimeStamping CA] [INFO] Serial: [*******************************] - Algorithm: [sha256WithRSAEncryption] Issuer: [DigiCert Timestamp 2022 - 2] [INFO] Checking: another_file [INFO] Serial: [*******************************] - Algorithm: [sha1WithRSAEncryption] Issuer: [**********************] <- correct [INFO] Serial: [*******************************] - Algorithm: [sha1WithRSAEncryption] Issuer: [DigiCert Assured ID Code Signing CA-1] [INFO] Serial: [*******************************] - Algorithm: [sha256WithRSAEncryption] Issuer: [DigiCert Trusted G4 RSA4096 SHA256 TimeStamping CA] [INFO] Serial: [*******************************] - Algorithm: [sha256WithRSAEncryption] Issuer: [DigiCert Timestamp 2022 - 2] My question is: how do I get the other chain? or that is also not implemented in pyOpenSSL? A: In the end had to resort to sigcheck with subprocess.check_output(), and use the following python regex with finditer(): regex_str = r".*\t {3}(?P<signer>.*)\n" \ r"\t\tCert Status:\s*(?P<status>.*)\n" \ r"\t\tValid Usage:\s*(?P<valid_usage>.*)\n" \ r"\t\tCert Issuer:\s*(?P<issuer>.*)\n" \ r"\t\tSerial Number:\s*(?P<serial>.*)\n" \ r"\t\tThumbprint:\s*(?P<thumbprint>.*)\n" \ r"\t\tAlgorithm:\s*(?P<algorithm>.*)\n" \ r"\t\tValid from:\s*(?P<valid_from>.*)\n" \ r"\t\tValid to:\s*(?P<valid_to>.*)"
doc_4860
My scheme looks like this: auth: { strategies: { social: { scheme: 'oauth2', endpoints: { authorization: 'https://accounts.google.com/o/oauth2/auth', token: 'http://localhost:4000/api/auth/google/token', refresh: 'http://localhost:4000/api/auth/google/refresh' }, user: { autoFetch: false, }, token: { property: 'access_token', type: 'Bearer', }, refreshToken: { property: 'refresh_token', maxAge: 60 * 60 * 24 * 30 }, responseType: 'code', clientId: <clientId>, scope: ['openid', 'profile', 'email'], state: 'UNIQUE_AND_NON_GUESSABLE', codeChallengeMethod: '', responseMode: '', acrValues: '', } } }, I've tried using the this.$auth.loginWith('social') call inside the created or mounted function calls of my login page. This redirects the user to the google login after being redirected to the login page. Unfortunately after google routing me back to my login page, the redirect is also executed, leaving me in a circuit loop between my login page and the google login page. Is there a preferred way of achieving what I want or are there any workarounds?
doc_4861
public static async Task Run([ServiceBusTrigger( "antrox-topic", "antrox-subscritpion", Connection = "ServicebusConnectionString")]string message, IDictionary<string, object> UserProperties, ILogger log) How do we get the value of UserProperties without using TryGetValue? Can we bind to the values? Suppose I know that UserProperties has a key called SourceParty, can I simply change the method signature to something like this: public static async Task Run([ServiceBusTrigger( "antrox-topic", "antrox-subscritpion", Connection = "ServicebusConnectionString")]string message, IDictionary<string, object> UserProperties, string SourceParty, //change made here <----------- ILogger log) A: This is not supported, firstly this is a custom property it's not the service bus message property and then you could check the ServiceBusTriggerBinding.cs , you could find all supported bindings. Here is the binding code, in here you could find some bindings not list in the doc like MessageReceiver, however no custom property or related binding, so you have to use UserProperties binding or bind the message to Message class then get the UserProperties from Message class.
doc_4862
My data: A: X1 1 word1 2 word2 3 word3 4 word4 . . 138 word138 B: term 1 word139 2 word140 3 word141 4 word142 . . 520 word658 They are all different words (from both sets). I want to create a new dataset ("C") which will look like: X 1 word1 2 word2 3 word3 4 word4 . . 139 word139 . . 658 word658 A: You could use rbind after ensuring that they both have the same names: C <- rbind(setNames(A, 'X'), setNames(B, 'X')) Another way is to concatenate the two: C <- data.frame(X = c(A$X1, B$term)) A: We could use bind_rows after renaming the colnames to X library(dplyr) colnames(A) <- "X" colnames(B) <- "X" bind_rows(A, B)
doc_4863
I have written the below code to generate my pdf $('#pdfButton').on('click', function(){ var pdf = new jsPDF('p','in','letter') , source = $('#main')[0] , specialElementHandlers = { '#bypassme': function(element, renderer){ return true } } pdf.fromHTML( source // HTML string or DOM elem ref. , 0.5 // x coord , 0.5 // y coord , { 'width':700 // max width of content on PDF , 'elementHandlers': specialElementHandlers } ) pdf.output('dataurl'); }); }); where main is the id of the div whose content I want to export as pdf. The content is exporting as pdf but not the entire content(the pdf gets cut). It can be dynamic content. Also the css I have in external files are not getting applied , styles like table-row, background-color, etc are not getting applied. How can I get my external css applied to the pdf before it is generated? Is it even possible with jsPDF..? Any suggestions please. Thanks in advance A: As far as I know jsPDF doesnt take external css. It infact doesnt even take inline css. It is currently not suitable to use jspdf for converting html to pdf. Hope this helps. A: Bear in mind that when you are PDF'ing things in HTML, it is essentially printing them to a file. This means you need to create a print stylesheet ideally, but also bear in mind that print stylesheets mean that it ignores things like background color. The way around this would be to have a background image in your print stylesheet that is the color. Also see this article, http://css-tricks.com/dont-rely-on-background-colors-printing/ Hope that helps
doc_4864
Here is for example a list of use-cases that Redis can handle for web-applications. Having mention so, one known disadvantage of Redis is for doing business analytic, but how complex the analytic should be in order to make Redis less efficient in compare for example to MySQL? For example if the following data structure in MySQL: Table: User Columns: Id(PK), Name(VarChar), Age(Int) Table: Message Columns: UserID(FK), Content(VarChar), Importance(Int) and in my application I want to use the following 2 queries: 1. SELECT Content FROM Message WHERE Importance > 2; 2. SELECT Content FROM Message,Users WHERE User.Id=Message.UserID and User.Age > 30; My Question: Can I use Redis to store the Datastructure above and query it in the same (or more) efficiency as in MySQL? A: Short answer: yes. Long answer: Redis is an amazing piece of technology but it is not a relational database. NoSQLs, with Redis included, are built on the premise that data needs to be stored according to the access patterns used with it. Therefore, to accomplish the above you'll first have to store the data "correctly". To store your tables' rows, it appears that you'll want to use the Hash data structure. In Redis' terminology, here's how you'd create a User key for UserID 123: HMSET user:123 id 123 name foo age 31 Note 1: the use of a colon (':') in constructing the key's name is merely a convention. Note 2: while the ID is already a part of the key's name, it is common to include it a field in the Hash for easier access. Similarly, here's how you'll create a Message key (with the ID 987): HMSET message:987 id 987 userid 123 content bar importance 3 Now comes the fun part :) Redis doesn't have FKs or indices, so you'll have to maintain data structures that will assist you in fetching the data per your requirements. For your first query, the best choice is keeping a Sorted Set in which the members are the message IDs and the scores are the importance. Therefore do: ZADD messages_by_importance 3 987 Fetching messages' content with importance greater than 2 will be done with two operations as shown by this pseudo-Pythonic code: messages = r.zrangebyscore('messages_by_importance', '(2', '+inf') for msg in messages: content = r.hget('message:' + msg, 'content') do_something(content) Note 3: this snippet is quite naive and can be optimized for better performance, but it should provide you with the basic gist. For the second query, you'll first need to find users who are older than 30 year - again, the same Sorted Set trick should be used: ZADD users_by_age 31 123 ZRANGEBYSCORE users_by_age (30 +inf This will get you the list of all users that match your criterion, but you'll also need to keep track (index) of all messages per user. To do this, use a Set: SADD user:123:messages 987 To tie everything, here's another pseudo-snippet: users = r.zrangebyscore('users_by_age', '(30', '+inf') for user in users: messages = r.smembers('user:' + user + ':messages') for msg in messages: content = r.hget('message:' + msg, 'content') do_something(content) This should be enough to get you started but once you've got a firm grip on the basics, look into optimizing these flows. Easy gains can be gotten with the use of pipelining, Lua scripting and smarter indices according to your needs... and if you need any further assistance - just ask :)
doc_4865
// main.cpp #include "A.hpp" // A.hpp #pragma once #include "B.hpp" class A { private: const B obj; }; // B.hpp #pragma once #include "A.hpp" // forward declaration class A; using T = A; class B { private: T* t_obj; }; My understanding is that the preprocessor will enter A.hpp first, then enter B.hpp immediately. It will not be able to enter A.hpp again because of #pragma once, and will resume with B.hpp. Then it will hit the forward declaration and so class B should be OK. Then, A.hpp will resume and class A should be OK. However, the compilation error I get is something like: ./A.hpp:5: error: unknown type name 'B' const B obj; Any sort of insight would be appreciated. Thank you. A: main.cpp should be fine with the explanation given up there by yourself. However, you mention in a comment that you have a B.cpp!? My guess would be that the error you cite actually happens during compilation of B.cpp and not main.cpp. If B.cpp includes B.h, then the preprocessor will include B.h which will include A.h. And A.h will try to include B.h, but since B.h already has been included at that point, the compiler will skip that include due to #pragma once and you enter the definition of class A without having seen a definition of class B…
doc_4866
http://jsfiddle.net/xavi3r/4J583/ <div class="cmAuto active a default"></div> $('body').append("<div>" + $('div').hasClass('.active.default') + "</div>"); Output should be TRUE, but it's returning false. EDIT: For those looking for the correct code: http://jsfiddle.net/xavi3r/4J583/8/ A: hasClass takes a single classname. You should use .is, which takes a selector (which can contain multiple classnames). A: I like this one $('body').append("<div>" + ($('div.active.default').length > 0) + "</div>"); A: http://jsfiddle.net/4J583/10/ Use and && :D
doc_4867
void method(){ static int variable; ... } My understanding of this is that variable has a lifetime equal to the execution life of the containing compilation unit but visible only to the method. AFAIK, there is no equivalent for this in Java so I am considering using class level static variables to do the job. I understand the risk of widening the visibility of the variables and the resultant decrease in maintainability but if I carefully check all of the other methods of the class for clashes, I can handle that with judicious commenting. Am I missing anything? Any other risks I should consider? Thanks to all for your contributions to SO. Cheers Simon A: Am I missing anything? Any other risks I should consider? You should really consider what state is logically part of. Is it actually part of the state of an instance of the containing class? If so, make it an instance variable. Is it logically state of the type itself? If so, a static variable is reasonable - but statics are often the enemy of testability, threading etc. Is it actually logically part of state of a different class? Possibly a new one which doesn't exist yet? You might want to have a static final reference to an instance of that new class, for example. Basically, let the natural location of the state inform the location of the variable.
doc_4868
$http({ url: 'url-here', method: 'POST', headers: { 'Content-Type': 'application/json' }, data: JSON.stringify(parameter) }).success(function(data, status) { if (data.status == 'success') { $scope.succ = "success"; var sessionid = data.doctor.doctor_id; $timeout(function() { $window.location.href = 'login?sessionid=' + sessionid + ''; }, 1000); } else if (data.status == 'failure') { $scope.succ = "fail"; } }); A: Here is an example which might help you. Keeping your code clean and reusable is most important. So always keep your common code at service layer. // Using Angular 1 var app = angular.module("Demo", []); app.controller("DemoController", ["$scope", "DemoService", "$window", "$timeout", function($scope, DemoService, $window, $timeout){ $scope.validateUser = function(){ DemoService.userValidation($scope.user, $scope.validateUserSuccess, $scope.validateUserError); } $scope.validateUserSuccess = function(data){ // Success Callback $scope.succ = "success"; var sessionid = data.doctor.doctor_id; $timeout(function() { $window.location.href = 'login?sessionid=' + sessionid + ''; }, 1000); }; $scope.validateUserError = function(data){ // Error Callback $scope.succ = "fail"; }; }]); app.service("DemoService", ["$http", function($http){ this.userValidation = function(parameter, successCB, errorCB){ $http({ url: 'url-here', method: 'POST', headers: { 'Content-Type': 'application/json' }, data: JSON.stringify(parameter) }).success(function(data, status) { if (data.status == 'success') { successCB(data); } else if (data.status == 'failure') { errorCB(data); } }); }; }]); // Using Angular 2 // parent.module.ts import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { HttpModule, JsonpModule } from '@angular/http'; import { LandingComponent } from './view/landing.component'; import { AdminService } from './service/admin.service'; @NgModule({ imports : [ BrowserModule, HttpModule, JsonpModule ], declarations : [ LoginComponent ], providers : [ AdminService ], bootstrap : [ LandingComponent ] }) export class ParentModule {} // admin.service.ts import { Injectable } from '@angular/core'; import { Admin } from '../util/admin'; import { Http, Headers } from '@angular/http'; import 'rxjs/add/operator/toPromise'; @Injectable() export class ValidateUser { adminObj = {}; option = new Headers({ "Content-Type": "application/json" }); constructor (private http: Http) {} validateUser(user: any) : Promise<any> { return this.http.post("http://127.0.0.1:3002/users", JSON.stringify(user), {headers:this.option}).toPromise(); } } // login.component.ts import { Component } from '@angular/core'; import { AdminService } from '../../service/admin.service'; import { Admin } from '../../util/admin'; @Component({ moduleId : module.id, templateUrl : "./login.component.html", styleUrls : ['./login.component.css'] }) export class LoginComponent { adminUser = {}; constructor( private adminService : AdminService ){} validate() : void { this.adminService.validateUser(this.adminUser).then((success)=>{ this.adminService.setAdminDetail(JSON.parse(success._body)); }).catch((err)=>{ alert("Invalid credential") }); } }
doc_4869
Table name is test There are 3 columns: date, high, and five_day_mavg (date is PK if it matters) I have a select statement which properly calculates a 5 day moving average based on the data in high. select date, avg(high) over (order by date rows between 4 preceding and current row) as mavg_calc from test It products output as such: I have 2 goals: * *First to store the output of the query in five_day_mavg. *Second to store this in such a way that when I a new row with data in high, it automatically calculates that value The closest I got was: update test set five_day_mavg = a.mav_calc from ( select date, avg(high) over (order by date rows between 4 preceding and current row) as mav_calc from test ) a; but all that does is sets the value of every row in five_day_mavg to entire average of high A: Thanks to @a_horse_with_no_name I played around with the WHERE clause update test l set five_day_mavg = b.five_day_mavg from (select date, avg(high) over (order by date rows between 4 preceding and current row) as five_day_mavg from test )b where l.date = b.date; a couple of things. I defined each table. The original table I aliased as l, the temporary table created by doing a windows function (the select statement in parenthesis) I aliased as b and I joined with the WHERE clause on date which is the index/primary key. Also, I was using 'a' as the letter for alias, and I think that may have contributed to the issue. Either way, solved now.
doc_4870
As I need to parameterize my source, I can't use ADO.net and instead need to use the OLEDB Source which supports parameters. When I use this OLEDB source, the script component doesnt recognise the BLOB data being passed by OLEDB source. It reports datatype problems i.e., convering nonunicode to unicode. How can this be done. Regards A: Can you confirm what your source database is (SQL Server, Oracle, etc). I had the same problem using the 'Oracle OLEDB provider for Oracle' data source. The provider seems to convert every varcahr into an nvarchar. I solved this by adding a 'data conversion' component, and explicitly converting all nvarchar columns to varchar here. The new columns are incuded in the output of this compnent, so you can link them to the fields on your spreadsheet.
doc_4871
I did a test only through leaflet (without shiny) and the code runs smoothly, but once I bring-in shiny, I'm not able to make it work the idea is that the user can modify these 3 variables on the side panel, and click an action button in order to trigger the calculation. #----------LIBRARIES----------# library(plyr) library(geosphere) library(dbscan) library(osmdata) library(sf) library(tidyr) library(sp) library(rgdal) library(leaflet) library(shiny) #-------LOAD FILES-------# OSM_merged <- read.csv(file = "C:\\Users\\jsainz\\Documents\\R\\Shiny_test\\OSM_merged.csv") OSM_points <- OSM_merged OSM_points$color <- OSM_points$category OSM_points$color <- str_replace_all(OSM_points$color, "Culture", "#3073A") OSM_points$color <- str_replace_all(OSM_points$color, "Educational", "# 887CAF") OSM_points$color <- str_replace_all(OSM_points$color,"Financial", "#540002") OSM_points$color <- str_replace_all(OSM_points$color,"Health", "#D6E899") OSM_points$color <- str_replace_all(OSM_points$color,"Leisure", "#D2D68D") OSM_points$color <- str_replace_all(OSM_points$color,"Office", "#D3696C") OSM_points$color <- str_replace_all(OSM_points$color,"Shop", "#AA9739") OSM_points$color <- str_replace_all(OSM_points$color,"Sport", "#378B2E") OSM_points$color <- str_replace_all(OSM_points$color,"Sustain", "#554600") OSM_points$color <- str_replace_all(OSM_points$color,"Toursim", "#5FAE57") xy <- OSM_points[,c(2,3)] OSM_points <- SpatialPointsDataFrame(coords = xy, data = OSM_points,proj4string = CRS("+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0")) #-------FUNCTIONS-------# assign_clusters <- function(poi_df, minPts = NA) { if(is.na(minPts)) { if(poi_df[1, "category"] %in% c("Culture", "Leisure", "Education", "Health", "Financial")) { minPts <- "minpts" } else minPts <- "maxpts" } eps <- "epsilon" poi_df[c("lng", "lat")] %>% distm(fun = distHaversine) %>% as.dist() %>% dbscan(eps = eps, minPts = minPts) %>% .[["cluster"]] %>% cbind(poi_df, cluster = .) } get_hull<- function(df) { cbind(df$lng, df$lat) %>% as.matrix() %>% st_multipoint() %>% st_convex_hull() %>% st_sfc(crs = 4326) %>% {st_sf(category = df$category[1], cluster = df$cluster[1], geom = .)} } hulls <- function(df) { df %>% split(.$cluster) %>% map(get_hull) } #----------SHINY CODE----------# ui <- fluidPage( titlePanel("Jorge_Test"), sidebarPanel( numericInput(inputId = "epsilon", label = "distance in meters to calculate activity clusters", 200), numericInput(inputId = "minpts", label = "minimum points to calculate clusters", 5), numericInput(inputId = "maxpts", label = "maximum points to calculate clusters", 10), actionButton("run", "Run Calculation"), actionButton("view", "generate plan"), width = 2), mainPanel( leafletOutput("mymap", width = 1550, height = 850) ) ) server <- function(input, output, session) { output$mymap <- renderLeaflet({ leaflet("mymap")%>% setView(lng = 0.0982, lat = 51.7674, zoom = 15)%>% addProviderTiles(providers$CartoDB.Positron, options = providerTileOptions(noWrap = TRUE))%>% addCircleMarkers(data = OSM_points, radius = .7, popup = ~category, color = ~color)}) oberveEvent(input$run, { updateNumericInput(session, "epsilon") updateNumericInput(session, "minpts") updateNumericInput(session, "maxpts") }) Clean_data <- OSM_merged %>% split(OSM_merged$category) %>% map_df(assign_clusters) hulls_cat <- Clean_data %>% group_by(category) %>% summarise() map_cluster_hulls <- Clean_data %>% filter(cluster != 0) %>% select(lng, lat, category, cluster) %>% split(.$category) %>% map(hulls) mdata <- melt(map_cluster_hulls, id = c("category", "cluster", "geom")) mch <- data.frame(mdata$category, mdata$cluster, mdata$geom) observeEvent(input$view, { leafletProxy("mymap", session) %>% addPolygons(data = mch$geom, fill = NA, fillOpacity = .01, weight = 2, color = "red", opacity = .8) } ) } shinyApp(ui, server) any idea of how to solve it? here is a link to the OSM_merged.csv file: https://www.dropbox.com/s/5ok9frcvx8oj16y/OSM_merged.csv?dl=0
doc_4872
Any ideas? A: Languages used for production code inside Google are limited to C++, Java, Python, and JavaScript. Apps Engine already runs Python, so what's next? It's most likely JavaScript. I recall Steve Yegge working on a Rails equivalent for JavaScript. See Stevey's Blog Rants: Rhino on Rails. Java is less likely, but possible. Java servlet containers tend to be heavy-weight. C++ is possible (Native Client and Chrome are two examples of sandboxed C++ code), but unlikely at this point. A: I would say that you have to look at a few factors: The language needs to: * *be sandboxable *be controllable *be expandable *be different from python *appeal to people who want to write massively scalable applications *can be run on developer computers easily *run on Linux Sandboxable The language must be safe to run on Google servers. Portions of the language/VM/modules|libraries must be able to be disabled and/or replaced. Controllable Notice how Google uses languages that are not controlled by companies? Python's BDFL GvR works for Google. Dunno about Javascript. Java is open-sourced enough for their taste I suppose. So the language evolution must allow Google's input at the very least. Expandable Google needs to be able to add stuff to the language, and that nearly implies an open-source language. I don't think they are interested in doing an internal fork of an existing language. Different from Python Python is mature, easy to learn, and powerful. The new language would have to have significant differences with python, otherwise, why not just use Python. Maybe a very functional language? Appeal to massive scalability Execution time would not be necessarily critical, but the language must be able to support easy start and stop, easy provisioning to other servers, and appeal to the sort of people who are into writing massively scalable applications. Developer computers The language needs to be able to be easy to install, maintain, and develop for on Windows, Mac, and Linux. It has to be either fully manageable with text editors or already have rock solid tools for editing and managing on these platforms. Linux Google servers would run the programs, so these must be able to be safely transferred on google servers and run there, and must be able to be controllable by the Google App Engine load-balancer, so they need to be unixy. Brainstorming I don't think it will be Java (too heavy, hard to modify VM), php (too leaky), ruby (hard to modify VM), C++ (can't be sandboxed(that I know of)). I don't think it would be JavaScript either, because it's hard to modularize, and it's not an easy language to learn. That rules out Lisp as well--the hard-to-learn part. So something else. Remember though that they want adoption of the tool, and they need a language that would be adoptable by a lot of people and a lot of businesses. So I lean to C# with mono. I think that makes the most sense. I know it sounds scary but lately the developers of the language are looking at changing C# quite a bit, to incorporate python-like dynamic typing, that sort of thing. Conclusion So that's what I think. And if they can pull that off, they will be able to leapfrog the competition. Mono is under MIT X11 license (as of April 2008), and I guess Miguel de Icaza can be hired by Google in the future, along with key team members. So my prediction is C#. A: I'd say Java, if only for the reason Android (or, at least, the SDK) is written in Java and they went to the trouble of writing their own interpreter/VM. If not Java, then Ruby would be my guess. Not sure why, but it feels like a good fit. A: I would say Java too, so they can support Ruby with JRuby, compatible with Python with Jython, Groovy and so on. A: My guess is C# just to stick it to Microsoft. A: Yup, JavaScript. Why? First, it fits. While there are obvious architectural differences (notably the OOP system) between Python and JavaScript, they are closer than they are farther apart, so converting the GAE Python API to A JS API should not be a dramatic leap in design or implementation. In the end, the JS API will likely have much the same flavor of the Python API. Second, safety. The JS runtime idiom is identical to the Python idiom in that effectively you're going to have JS processes running independently from each other for each request. That is, the classic Apache forking model. As a hosting service, this model is extremely robust and much, much easier to control than something like Java. What you lose in efficiency via a threaded implementation, you gain by simply being Google with a gazillion machines. At Googles scale, administrative overhead trumps performance every day of the week. Simpler and more robust is better, and that's what the process model is. Third, technology speed. JS is moving VERY quickly right now. Look at the larger number of commercial enterprises writing JS interpreter/compiler/runtimes, as well as the advancements of the language itself. JS script has rushed to the front with a vengeance. Finally, popularity. While not popular on the server side, JS is still likely the most deployed language in the world, and thereby the most accessible language in the world. Every hack web designer on the planet is becoming a JS programmer, whether they like it or not. Now, I don't know how many web designers you've met, but most of the ones I have met are NOT programmers. So, adopting JS for them is going to be a cut and paste and painful experience for them, but it's pretty much a requirement for the modern web. Taking that skill to push back and do some lightweight processing on the back end, in the SAME LANGUAGE, will be a boon to these people. Do not discount the power of familiarity in a normally scary environment (and despite the advances, computers are still "scary" to the vast majority of the population). JS, it's not a toy any more, it's a sleeping giant. Really. A: JRuby on Rails. A: Already works with Python. There have been rumors about PHP, which is logical choice considering it's popularity. A: I'm going to throw in my 2 cents on Java as well. They have a heavy number of tools already written in Java (GWT anyone? etc. etc.) Though, Javascript would be most intriguing. A: I`ve heard once that Google likes Python the most!
doc_4873
If I could use it to see all my Mac computers traffic, it would be a good & free alternative to Fiddler I guess. I've searched for a feature like this within the HTTP TOOLKIT docs but I didn't find it mentioning such a feature. So my question is: Is it possible to capture all network traffic on a Mac computer with HTTP TOOLKIT? Thanks for your help! A: Yes, you can use it to intercept all traffic from your computer. The only difference is that unlike other built-in options (for browsers like Chrome/Firefox/etc, for Android, for Docker, and so on) it's not totally automatic. To do this, you just need to manually configure your system to use HTTP Toolkit as your HTTP proxy, and to trust the CA certificate that HTTP Toolkit has generated on your machine. The values you'll need for this are shown in the 'Anything' option on the Intercept page within HTTP Toolkit. Once that's done, all traffic from your system should immediately start appearing in HTTP Toolkit. Remember to disable the system proxy setting when you're done though! If you leave the proxy enabled, and quit HTTP Toolkit, then your internet connection won't work (because your system will keep try to send all network traffic to HTTP Toolkit, which won't work when it's not running).
doc_4874
The buildPhoneModelMenu() appears to be working fine. Can anyone help me figure out why one menu works and not the other? I've been up 6 hours trying to figure it out. Thanks! import javax.swing.*; import java.awt.event.*; import java.awt.*; import java.text.DecimalFormat; public class CellPhoneCalculator extends JFrame{ private JMenuBar menuBar; //Menu bar to hold drop down menus. private JMenu fileMenu; //file menu private JMenu phonePackage; //menu containing phone packages and options private JMenu phoneModels; //menu containing cell phone models. private JMenuItem exit;//Exit button private JRadioButtonMenuItem package300; //300 minute cell phone package private JRadioButtonMenuItem package800; //800 minute cell phone package private JRadioButtonMenuItem package1500; //1500 minute cell phone package. private JRadioButtonMenuItem phone100; //phone model 100 private JRadioButtonMenuItem phone110; //phone model 110 private JRadioButtonMenuItem phone200; //phone model 200 private JCheckBoxMenuItem vmail; //voicemail option private JCheckBoxMenuItem text; //text messaging option private JLabel packageSelected;//Displays the text "Cell Phone Package:" private JLabel modelSelected; //Displays the text "Cell Phone Model:" private JLabel optionsSelected; //Displays the text "Options Selected:" private JLabel subtotal; //Displays the text "Subtotal." private JLabel tax; //Displays the text "Sales Tax (6%) :" private JLabel total; //Displays the text "Total:" private JTextField pSelected; //displays the selected cell phone package. private JTextField mSelected; //displays the selected cell phone model. private JTextField oSelectedV; //Displays the Voice Mail option selected. private JTextField oSelectedT; //Displays the Text option selected. private JTextField dspSub; //displays the subtotal private JTextField dspTax; //displays the sales tax amount on subtotal private JTextField dspTotal; //displays the total after tax. public CellPhoneCalculator() { //call the superclass constructor to instantiate a JFrame //with a String argument to be title. super("Cell Phone Package Pricing Calculator"); //Exit on window close setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); buildPricePane();//builds the price panel to go into content pane buildMenuBar();//Builds the menu bar. buildPhonePackageMenu();//Builds phone package menu buildFileMenu();//Builds the File Menu //pack method to resize JFrame. pack(); //Set visibility of panel. setVisible(true); } private void buildMenuBar() { menuBar = new JMenuBar();//Create the menu bar buildFileMenu(); //build the file menu buildPhonePackageMenu();//build the phone package menu buildPhoneModelMenu();//build the phone model menu //Add the menus to the menuBar. menuBar.add(fileMenu); menuBar.add(phonePackage); menuBar.add(phoneModels); setJMenuBar(menuBar);//sets the menu bar for the window. } private void buildPhonePackageMenu() { phonePackage = new JMenu("Cell Phone Packages");//Drop down containing phone plan //packages and options. //Make the radio buttons for cell phone packages. package300 = new JRadioButtonMenuItem("300 minute package", true); package800 = new JRadioButtonMenuItem("800 minute package"); package1500 = new JRadioButtonMenuItem("1500 minute package"); //Register the action listener PackageListener with the radio buttons. package300.addActionListener(new PackageListener()); package800.addActionListener(new PackageListener()); package1500.addActionListener(new PackageListener()); //Make new button group for packages so buttons are mutually exclusive. ButtonGroup packages = new ButtonGroup(); //Add radio buttons to packages button group. packages.add(package300); packages.add(package800); packages.add(package1500); //Create phone option check boxes. vmail = new JCheckBoxMenuItem("Voice Mail"); text = new JCheckBoxMenuItem("Text Mail"); //Register Item Listener with check box options. vmail.addItemListener(new OptionsListener()); text.addItemListener(new OptionsListener()); //Add components to menu phonePackage.add(package300); phonePackage.add(package800); phonePackage.add(package1500); phonePackage.addSeparator();//Add a separator before phone options phonePackage.add(vmail); phonePackage.add(text); } private void buildFileMenu() { //Instantiate file drop down with text "File." fileMenu = new JMenu("File"); //Create exit button exit = new JMenuItem("Exit"); //register action listener exit.addActionListener(new ExitButtonListener()); //add exit menu item to menu fileMenu.add(exit); } /* * Build the menu to select the phone models. */ private void buildPhoneModelMenu() { //Create Menu drop down with text "Phone Models." phoneModels = new JMenu("Phone Models"); //Create new radio buttons in menu, with model 100 preselected. phone100 = new JRadioButtonMenuItem("Phone Model 100", true); phone110 = new JRadioButtonMenuItem("Phone Model 110"); phone200 = new JRadioButtonMenuItem("Phone Model 200"); //Register the ActionListener modelListener with the buttons. phone100.addActionListener(new ModelListener()); phone110.addActionListener(new ModelListener()); phone200.addActionListener(new ModelListener()); //Create new phone model button group. ButtonGroup phoneModel = new ButtonGroup(); //Add phone model radio buttons to button group, so they're selection is mutually exclusive. phoneModel.add(phone100); phoneModel.add(phone110); phoneModel.add(phone200); //Add the buttons to the menu. phoneModels.add(phone100); phoneModels.add(phone110); phoneModels.add(phone200); } private DecimalFormat dollar = new DecimalFormat("###.##"); /* * Construct the PricePane with all components. */ public void buildPricePane() { //Create the JPanel object and assign to pricePanel. JPanel pricePanel = new JPanel(); setLayout(new GridLayout(13,1)); //Create the text labels for left hand column packageSelected = new JLabel("Cell Phone Package: "); modelSelected = new JLabel("Cell Phone Model: "); optionsSelected = new JLabel("Options Selected: "); subtotal = new JLabel("Subtotal: "); tax = new JLabel("Sales Tax (6%): "); total = new JLabel("Total: "); //Create the Un-Editable text fields to display selected radio button items pSelected = new JTextField("", 10); pSelected.setEditable(false); mSelected = new JTextField("", 10); mSelected.setEditable(false); //Create the Un-Editable text fields to display selected check box items. oSelectedV = new JTextField(10); oSelectedV.setEditable(false); oSelectedT = new JTextField(10); oSelectedT.setEditable(false); //Create the un-editable text fields to display subtotal, tax and total. dspSub = new JTextField("", 10); dspSub.setEditable(false); dspTax = new JTextField("", 10); dspTax.setEditable(false); dspTotal = new JTextField("", 10); dspTotal.setEditable(false); //Add the items and labels to JPanel. add(packageSelected); add(pSelected); add(modelSelected); add(mSelected); add(optionsSelected); add(oSelectedV); add(oSelectedT); add(subtotal); add(dspSub); add(tax); add(dspTax); add(total); add(dspTotal); } /* * ActionListener interface for the cell phone package radio buttons. * Sends text and prices to PricePane, to display and sum respectively. */ private class PackageListener implements ActionListener { public void actionPerformed(ActionEvent e) { if(package300.isSelected()) pSelected.setText("300 minutes per month: $45.00 per month");//Sends display text if(package800.isSelected()) pSelected.setText("800 minutes per month: $65.00 per month"); if(package1500.isSelected()) pSelected.setText("1500 minutes per month: $99.00 per month"); } } /* * ItemListener interface for the cell phone options check boxes. */ private class OptionsListener implements ItemListener { public void itemStateChanged(ItemEvent e) { if(vmail.isSelected()) oSelectedV.setText("Voice mail: $5.00 per month"); if(text.isSelected()) oSelectedT.setText("Text messaging: $10.00"); } } /* * ActionListener for the cell phone model radio buttons. */ private class ModelListener implements ActionListener { public void actionPerformed(ActionEvent e) { if(phone100.isSelected()) mSelected.setText("Model 100: $29.95"); if(phone110.isSelected()) mSelected.setText("Model 110: $49.95"); if(phone200.isSelected()) mSelected.setText("Model 200: $99.95"); } } /* * ActionListener interface for exit button to close application. */ private class ExitButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { System.exit(0); } } /* * Main function to launch GUI. */ public static void main(String[] args) { new CellPhoneCalculator(); } } A: buildPhonePackageMenu();//Builds phone package menu This line in public CellPhoneCalculator() Needs to be removed. I screwed up. Disregard.
doc_4875
What I learned in the last two months is that I have to create a vpn service and use it to sniff data. There are a lot of useful codes on the internet that I tried to understand and run. And I managed to sniff the data of some applications using these codes, which all uses the same concept. * *https://github.com/hexene/LocalVPN *Android firewall with VpnService *http://www.thegeekstuff.com/2014/06/Android-vpn-service/ *Android VpnService to capture packets won't capture packets When using each one of the above code, and with small modifications, I managed to capture packets for all applications, but with applications like facebook, the vpnService made those applications stop working; when I create the vpn service and I try for example to comment on a post or make any action that requires sending/receiving data between Facebook application and Facebook server, this action doesn't happen; looks like somehow Facebook application knows that there's someone sniffing on him. I've been trying in the last two months to find a way to capture Facebook application packets without breaking the Facebook application functionality. I tried to install a certificate following the KeyChain demo in android samples, but it didn't work with me. From my search, I know/I'm sure that there's something I'm missing; I searched for applications that does what I'm trying to accomplish without making applications like facebook detect it. And I found LostNetNoRootFirewall on google play. With LostNetNoRootFirewall, I managed to create a vpn service and sniff packets, and facebook application was working like a charm! My question What should I add to my application to be able to create a vpnService and prevent applications like facebook from detecting that my service is sniffing it's packets? The current code I'm working at. [original source from here] package com.git.firewall; public class GITVpnService extends VpnService implements Handler.Callback, Runnable { private static final String TAG = "GITVpnService"; private String mServerAddress = "127.0.0.1"; private int mServerPort = 55555; private PendingIntent mConfigureIntent; private Handler mHandler; private Thread mThread; private ParcelFileDescriptor mInterface; @Override public int onStartCommand(Intent intent, int flags, int startId) { // The handler is only used to show messages. if (mHandler == null) { mHandler = new Handler(this); } // Stop the previous session by interrupting the thread. if (mThread != null) { mThread.interrupt(); } // Start a new session by creating a new thread. mThread = new Thread(this, "VpnThread"); mThread.start(); return START_STICKY; } @Override public void onDestroy() { if (mThread != null) { mThread.interrupt(); } } @Override public boolean handleMessage(Message message) { if (message != null) { Toast.makeText(this, (String)message.obj, Toast.LENGTH_SHORT).show(); } return true; } @Override public synchronized void run() { try { Log.i(TAG, "Starting"); InetSocketAddress server = new InetSocketAddress( mServerAddress, mServerPort); run(server); } catch (Exception e) { Log.e(TAG, "Got " + e.toString()); try { mInterface.close(); } catch (Exception e2) { // ignore } Message msgObj = mHandler.obtainMessage(); msgObj.obj = "Disconnected"; mHandler.sendMessage(msgObj); } finally { } } DatagramChannel mTunnel = null; private boolean run(InetSocketAddress server) throws Exception { boolean connected = false; android.os.Debug.waitForDebugger(); // Create a DatagramChannel as the VPN tunnel. mTunnel = DatagramChannel.open(); // Protect the tunnel before connecting to avoid loopback. if (!protect(mTunnel.socket())) { throw new IllegalStateException("Cannot protect the tunnel"); } // Connect to the server. mTunnel.connect(server); // For simplicity, we use the same thread for both reading and // writing. Here we put the tunnel into non-blocking mode. mTunnel.configureBlocking(false); // Authenticate and configure the virtual network interface. handshake(); // Now we are connected. Set the flag and show the message. connected = true; Message msgObj = mHandler.obtainMessage(); msgObj.obj = "Connected"; mHandler.sendMessage(msgObj); new Thread () { public void run () { // Packets to be sent are queued in this input stream. FileInputStream in = new FileInputStream(mInterface.getFileDescriptor()); // Allocate the buffer for a single packet. ByteBuffer packet = ByteBuffer.allocate(32767); int length; try { while (true) { while ((length = in.read(packet.array())) > 0) { // Write the outgoing packet to the tunnel. packet.limit(length); debugPacket(packet); // Packet size, Protocol, source, destination mTunnel.write(packet); packet.clear(); } } } catch (IOException e) { e.printStackTrace(); } } }.start(); new Thread () { public void run () { DatagramChannel tunnel = mTunnel; // Allocate the buffer for a single packet. ByteBuffer packet = ByteBuffer.allocate(8096); // Packets received need to be written to this output stream. FileOutputStream out = new FileOutputStream(mInterface.getFileDescriptor()); while (true) { try { // Read the incoming packet from the tunnel. int length; while ((length = tunnel.read(packet)) > 0) { // Write the incoming packet to the output stream. out.write(packet.array(), 0, length); packet.clear(); } } catch (IOException ioe) { ioe.printStackTrace(); } } } }.start(); return connected; } private void handshake() throws Exception { if (mInterface == null) { Builder builder = new Builder(); builder.setMtu(1500); builder.addAddress("10.0.0.2",32); builder.addRoute("0.0.0.0", 0); //builder.addRoute("192.168.2.0",24); //builder.addDnsServer("8.8.8.8"); // Close the old interface since the parameters have been changed. try { mInterface.close(); } catch (Exception e) { // ignore } // Create a new interface using the builder and save the parameters. mInterface = builder.setSession("GIT VPN") .setConfigureIntent(mConfigureIntent) .establish(); } } private void debugPacket(ByteBuffer packet) { /* for(int i = 0; i < length; ++i) { byte buffer = packet.get(); Log.d(TAG, "byte:"+buffer); }*/ int buffer = packet.get(); int version; int headerlength; version = buffer >> 4; headerlength = buffer & 0x0F; headerlength *= 4; Log.d(TAG, "IP Version:"+version); Log.d(TAG, "Header Length:"+headerlength); String status = ""; status += "Header Length:"+headerlength; buffer = packet.get(); //DSCP + EN buffer = packet.getChar(); //Total Length Log.d(TAG, "Total Length:"+buffer); buffer = packet.getChar(); //Identification buffer = packet.getChar(); //Flags + Fragment Offset buffer = packet.get(); //Time to Live buffer = packet.get(); //Protocol Log.d(TAG, "Protocol:"+buffer); status += " Protocol:"+buffer; buffer = packet.getChar(); //Header checksum String sourceIP = ""; buffer = packet.get(); //Source IP 1st Octet sourceIP += buffer; sourceIP += "."; buffer = packet.get(); //Source IP 2nd Octet sourceIP += buffer; sourceIP += "."; buffer = packet.get(); //Source IP 3rd Octet sourceIP += buffer; sourceIP += "."; buffer = packet.get(); //Source IP 4th Octet sourceIP += buffer; Log.d(TAG, "Source IP:"+sourceIP); status += " Source IP:"+sourceIP; String destIP = ""; buffer = packet.get(); //Destination IP 1st Octet destIP += buffer; destIP += "."; buffer = packet.get(); //Destination IP 2nd Octet destIP += buffer; destIP += "."; buffer = packet.get(); //Destination IP 3rd Octet destIP += buffer; destIP += "."; buffer = packet.get(); //Destination IP 4th Octet destIP += buffer; Log.d(TAG, "Destination IP:"+destIP); status += " Destination IP:"+destIP; /* msgObj = mHandler.obtainMessage(); msgObj.obj = status; mHandler.sendMessage(msgObj); */ //Log.d(TAG, "version:"+packet.getInt()); //Log.d(TAG, "version:"+packet.getInt()); //Log.d(TAG, "version:"+packet.getInt()); } }
doc_4876
Can Pipes be called from JavaScript/TypeScript or are they only meant to be used in templates? All the references and tutorials I've looked at show Pipes being used in the templates only. I'm don't have a hard use case for this but I'm playing around with the various elements of Angular2 and could imagine that I might have a need to use a Pipe directly and not recode it in JS/TS A: Yes, a pipe is just code, so you could use it as code without using it in your template. For example, I have a ProductFilterPipe that filters a list of products. We could use that pipe in code as follows: filterProducts() : void { let productFilterPipe = new ProductFilterPipe(); let filteredList = productFilterPipe.transform(this.products, "am"); console.log(filteredList); } So it is possible. A: You can also use the default Angular pipes (e.g. DecimalPipe, CurrencyPipe) by importing: import {DecimalPipe} from '@angular/common'; and then using it by DecimalPipe.prototype.transform(value, formattingString)
doc_4877
Object {medium-editor-1453741508068-0: Object} medium-editor-1453741508068-0: Object value: "this is what i want" This gets the above: this.mediumEditor.editor.serialize(); I need something like: this.mediumEditor.editor.serialize().childObject.value; A: If your top-level object only contains one object, you can simply use Object.keys(topLevelObject) to get the "object's object" name. Something like the following: var objectsObjectName = Object.keys(topLevelObject)[0]; var value = topLevelObject[objectsObjectName].value; The same logic can be used recursively if you have more levels of object nesting, or if the object's object's value's name (wow, this is getting hard to follow) is non-predictable too. You can also iterate on the top-level object: for (var key in topLevelObject) { var value = topLevelObject[key].value; } This works even if you only have one nested object, even though it's arguably weird to write a loop knowing it will only loop once.
doc_4878
if n=3 then aAnnBccD#! AAbbC should match, while AbCdeFgHiJ should fail. Please advise on the same. A: Just try with following regex: ^[^A-Z]*([A-Z][^A-Z]*){0,3}$ A: Just to check, example with lookahead: ^(?!(?:.*?[A-Z]){4}) This fails at strings that contain {4} (more than 3) ...A-Z see test at regex101 A: Something like ^([^A-Z\n]*[A-Z][^A-Z\n]*){0,3}$ Regex Demo
doc_4879
static members : can be accessed in a class & sub-classes of it & all instances of these class members : can be accessed in all instances of (a class & sub-classes of it) Is this right? And are there any other differences? A: Let's check using the --ccode switch of the Vala compiler: public class Test { public static int static_member; public class int class_member; public int instance_member; } When compiled will produce these C data structures (I only show the important parts): struct _Test { gint instance_member; }; struct _TestClass { gint class_member; }; extern gint test_static_member; The static member is not stored in any structure belonging to the class, but is a global variable. It is still scoped using the class prefix (so "test_" is prepended) to avoid name clashes with other global variables or static members of other classes. The class member is stored in the "class structure" and the instance member is stored in the "instance structure". The "class structure" may be extended by deriving classes, but other than that you normally only have one instance of the "class structure" for each class (which is why they are named like this). The "instance structure" holds all the instance data everytime a new instance is created. For the full understanding of these mechanism you have to know some C and have to read the GObject manual.
doc_4880
* *I made a new branch (left-nav) using GitHub and worked on it in VS Code. *As my work is completed in that particular branch (left-nav) I merged it to the master branch using GitHub. *But after merging branch(left-nav) with the master branch in GitHub, when I opened VS Code with the master branch as an active branch, the code of branch (left-nav) was not merged in VS Code whereas when I see the same file in GitHub it has all the code in it. Do I have to merge code separately in GitHub as well as in VS Code, or I am getting it wrong somewhere? A: You need to pull the new changes from GitHub using git pull origin master Note: I would advise you to merge the branches locally & then pushing your changes to GitHub. This will be helpful in case something breaks. A: Do I have to merge code separately in GitHub as well as in VS Code, or I am getting it wrong somewhere? No, you don't need to merge separately; you are just missing a step. Basically your local copy of the repo is out of date. If you perform a git fetch to update your copy of what's on GitHub, and then take a look at origin/master you will see your changes there (this assumes your remote is called "origin", which is the default). If you also want to see those changes on your local copy of master, you need to update that copy of master with what's in origin, and one way to do that is to checkout master and merge the latest commits from origin/master into it. (Note the command pull will do a fetch and merge in a single command.) This is slightly more advanced, but once you get the hang of dealing with origin, you don't really need to keep a local copy of master anymore since you can already view what you wish to see using origin/master instead. Coincidentally, I just answered another question today which explains this concept in more detail, which is definitely relevant to your specific question too.
doc_4881
The problem however, is that the Browse page requires ProjectViewModel, where Upload uses UploadViewModel, etc. etc. So by having these Html.RenderAction elements, the Browse page seems to immediately stop receiving the ProjectViewModel - i'm guessing it switches to the VM of the last RenderAction. Is there something I have to set up in routing to ensure these already strongly typed Views keep their contexts? Update with code: Also, maybe I have to explicitly state that the model going TO "Upload" is a different one? I dunno. Browser (containing Upload and FileBrowser): <%@ Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage<CKD.Web.Files.ViewModels.ProjectViewModel>" MasterPageFile="~/Views/Project/Project.Master" %> <asp:Content runat="server" ID="Main" ContentPlaceHolderID="MainContent"> <table> <tr> <td id="upload" style="width: 180px" class="ui-widget ui-widget-content ui-corner-all"> <% Html.RenderAction("Index", "Upload", new {id = Model.Project.Id}); %> </td> <td id="fileBrowser" style="width: auto" class="ui-widget ui-widget-content ui-corner-all"> <% Html.RenderAction("Index", "FileBrowser", new {id = Model.Project.Id}); %> </td> </tr> </table> </asp:Content> Upload View: <%@ Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage<CKD.Web.Files.ViewModels.UploadViewModel>" MasterPageFile="~/Views/Shared/Control.master" %> <%@ Import Namespace="System.IO" %> <asp:Content runat="server" ID="Scripts" ContentPlaceHolderID="Scripts"> </asp:Content> <asp:Content runat="server" ID="Main" ContentPlaceHolderID="MainContent"> <div class="uploadControl" style="Margin: 8px"> <h2 style="Margin-Bottom: 0px">Upload</h2> <hr /> <div id="accordion" style="display: block;"> <h3><a href="#">Files</a></h3> <div> <div class="ui-widget-content ui-corner-all" style="min-height: 80px; margin: 4px"> <% if(Model.Files != null) %> <% foreach(FileInfo f in Model.Files) {%> <p><%= f.Name %></p> <hr /> <% } %> </div> <ul style="width: 10px; list-style-type:none"> <li class="ui-widget ui-widget-button ui-corners-all">Clear</li> <li class="ui-widget ui-widget-button ui-corners-all">Add</li> </ul> </div> <h3><a href="#">Transmittal</a></h3> <div> <p>File here</p> <p style="width: auto; margin: 8px" class="ui-widget-button">Pick File...</p> </div> <h3><a href="#">Notification</a></h3> <div> <p> Stuff </p> </div> </div> <div> <div class="ui-widget ui-corner-all ui-widget-active">Upload Files</div> </div> </div> </asp:Content> Upload Controller: using System.Web.Mvc; namespace CKD.Web.Files.Controllers { using System.Linq; using Models; using ViewModels; public class UploadController : Controller { private ICKDClientAreaRepository Repository { get; set; } private UploadViewModel _viewModel; private UploadViewModel ViewModel { get { return _viewModel ?? (_viewModel = ViewModel = UploadViewModel.Default(Repository)); } set { _viewModel = value; } } public UploadController(ICKDClientAreaRepository repository) { Repository = repository; } // GET public ActionResult Index(int id) { var project = Repository.Projects.Single(x => x.Id == id); ViewModel = UploadViewModel.ForProject(project, Repository); return View(ViewModel); } } } Upload VM: namespace CKD.Web.Files.ViewModels { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web.Security; using Models; public class UploadViewModel { public Project Project { get; set; } public DirectoryInfo Directory { get; set; } public User Uploader { get; set; } public DateTime Time { get; set; } public List<FileInfo> Files { get; set; } public FileInfo Transmittal { get; set; } public List<User> NotificationList { get; set; } public static UploadViewModel Default(ICKDClientAreaRepository fromRepository) { var project = fromRepository.Projects.First(); return ForProject(project, fromRepository); } public static UploadViewModel ForProject(Project project, ICKDClientAreaRepository fromRepository) { var dir = project.DirectoryName; var uploader = fromRepository.Users.Single(x => x.Username == Membership.GetUser().UserName); var time = DateTime.Now; var notification = project.Users.ToList(); return new UploadViewModel { Project = project, Directory = new DirectoryInfo(dir), Uploader = uploader, Time = time, NotificationList = notification }; } } } A: Try making the view rendered by RenderAction() a partial view. You should also decorate the action with [ChildActionOnly] attribute to prevent it from executing by it's own (when somebody would request http://xxx.com/Upload/Index).
doc_4882
I would like to reshape this 1D array into a multidimensional matrix which has the dimensions of my investigated parameters (to be in the right order), and those dimensions may vary in number. I could came up with a function based on for-loops, but the problem is that with very large arrays I run out of RAM. I am perfectly aware that this is not the smartest way to do this. I was wondering if there is a smarter way to manipulate such a large array and to do the same job as my function does. function [Tensor, n_dimensions]=reshape_array(Data,ndim) n_dimensions=length(ndim); n_elements=prod(ndim); reshape_string=[]; for i=n_dimensions:-1:1 if i==1 reshape_string=strcat(reshape_string, ' ndim(', num2str(i) , ')])'); elseif i== n_dimensions reshape_string=strcat(reshape_string, ' [ndim(', num2str(i) , ')'); else reshape_string=strcat(reshape_string, ' ndim(', num2str(i) , ') '); end end invert_string=[]; for i=1:n_dimensions if i==1 invert_string=strcat(invert_string, 'ndim(', num2str(i) , '),'); elseif i== n_dimensions invert_string=strcat(invert_string, ' ndim(', num2str(i) , ')'); else invert_string=strcat(invert_string, ' ndim(', num2str(i) , '),'); end end reshape_statement=strcat('reshape(Data,',reshape_string); invert_statement=strcat('zeros(',invert_string,');'); Tens1=eval(reshape_statement); Tens2=eval(invert_statement); nLoops=length(ndim); str = ''; str_dim_tens=''; str_dim_indeces=''; for i=1:nLoops str = strcat(sprintf('%s \n for i%d=1:',str,i), sprintf('%d',ndim(i))); if i<nLoops str_dim_tens=strcat(str_dim_tens,'i',num2str(i),','); else str_dim_tens=strcat(str_dim_tens,'i',num2str(i)); end end for i=nLoops:-1:1 if i~=1 str_dim_indeces=strcat(str_dim_indeces,'i',num2str(i),','); else str_dim_indeces=strcat(str_dim_indeces,'i',num2str(i)); end end str = strcat(sprintf('%s \n Tens2(%s)=Tens1(%s);',str,str_dim_tens,str_dim_indeces)); for i=1:nLoops str = sprintf('%s \n end',str); end eval(str) Tensor=Tens2; end as an example, ndim=[2 3]; Data=1:2*3 [Tensor, n_dimensions]=reshape_array(Data,ndim); n_dimensions = 2 Tensor = 1 2 3 4 5 6 I would work with more dimensions (e.g. minimum 4) and Data arrays with millions of elements. An example could be M(10,10,10,300000) This is why I was looking for the least computationally expensive method to do the job. Thank you for your help! A: From your code, you want to fill the elements in the reshaped array using a dimension order which is the opposite of Matlab's column-major default; that is, you start from the last dimenson, then the second last, etc. This can be done by reshaping into an array with the dimensions in reverse order (using reshape) and the reversing the order of dimensions back (using permute). n_dimensions = numel(ndim); Tensor = reshape(Data, ndim(end:-1:1)); % reshape with dimensions in reverse order Tensor = permute(Tensor, n_dimensions:-1:1); % reverse back order of dimensions
doc_4883
import com.itextpdf.kernel.pdf.PdfReader; import com.itextpdf.kernel.pdf.StampingProperties; import com.itextpdf.signatures.BouncyCastleDigest; import com.itextpdf.signatures.IExternalDigest; import com.itextpdf.signatures.IExternalSignature; import com.itextpdf.signatures.PdfSignatureAppearance; import com.itextpdf.signatures.PdfSigner; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.KeyStoreException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; public class Sign { public static void signRemote(String certificate, String password, String token, String module, Long slot, String reason, String location, String contact, String input, String output ) throws CertificateException, FileNotFoundException, IOException, KeyStoreException, GeneralSecurityException { CertificateFactory factory = CertificateFactory.getInstance("X.509"); Certificate[] chain = new Certificate[3]; int i = 0; for(Certificate cert : factory.generateCertificates( new FileInputStream(certificate)) ) { chain[i] = cert; i++; } PdfReader reader; reader = new PdfReader(input); PdfSigner signer = new PdfSigner( reader, new FileOutputStream(output), new StampingProperties() ); signer.setCertificationLevel(PdfSigner.CERTIFIED_NO_CHANGES_ALLOWED); PdfSignatureAppearance sap = signer.getSignatureAppearance(); sap .setReason(reason) .setLocation(location) .setContact(contact); signer.setFieldName("signature"); IExternalDigest digest = new BouncyCastleDigest(); IExternalSignature signature = new PKCS11Signature( password, token, module, slot ); signer.signDetached( digest, signature, chain, null, null, null, 0, PdfSigner.CryptoStandard.CMS ); reader.close(); } import com.itextpdf.signatures.DigestAlgorithms; import com.itextpdf.signatures.IExternalSignature; import java.io.ByteArrayInputStream; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.Security; import java.security.Signature; import java.security.cert.CertificateException; import java.util.logging.Level; import java.util.logging.Logger; import org.bouncycastle.jce.provider.BouncyCastleProvider; import sun.security.pkcs11.SunPKCS11; public class PKCS11Signature implements IExternalSignature { private final String password; private final String token; private final String module; private final Long slot; public PKCS11Signature( String password, String token, String module, Long slot ) { this.password = password; this.token = token; this.module = module; this.slot = slot; } @Override public String getHashAlgorithm() { return DigestAlgorithms.SHA256; } @Override public String getEncryptionAlgorithm() { return "RSA"; } @Override public byte[] sign(byte[] message) throws GeneralSecurityException { try { BouncyCastleProvider providerBC = new BouncyCastleProvider(); Security.addProvider(providerBC); String config = "name = " + this.token + "\n" + "library = " + this.module + "\n" + "slot = " + this.slot; ByteArrayInputStream bais = new ByteArrayInputStream(config.getBytes()); SunPKCS11 providerPKCS11 = new SunPKCS11(bais); Security.addProvider(providerPKCS11); // Load your private key from the key store KeyStore ks = KeyStore.getInstance("PKCS11", providerPKCS11); ks.load(null, this.password.toCharArray()); // load key or chain String alias = ks.aliases().nextElement(); PrivateKey pk = (PrivateKey)ks.getKey(alias, null); // Sign the hash received from the server Signature sig = Signature.getInstance("SHA256withRSA"); sig.initSign(pk); sig.update(message); return sig.sign(); } catch (IOException | NoSuchAlgorithmException | CertificateException ex ) { Logger.getLogger(Signature.class.getName() ).log(Level.SEVERE, null, ex); } return null; } } The exception I have is the following: com.itextpdf.kernel.PdfException: Unknown PdfException. at com.itextpdf.signatures.PdfPKCS7.getEncodedPKCS7(PdfPKCS7.java:934) at com.itextpdf.signatures.PdfSigner.signDetached(PdfSigner.java:648) at com.itextpdf.signatures.PdfSigner.signDetached(PdfSigner.java:538) at pdf.pkcs11.Sign.signRemote(Sign.java:60) at pdf.pkcs11.SignTest.testSignRemote(SignTest.java:90) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:53) at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123) at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164) at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110) at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:172) at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:104) at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:70) Caused by: java.lang.NullPointerException at com.itextpdf.signatures.PdfPKCS7.getEncodedPKCS7(PdfPKCS7.java:857) ... 33 more I don't have much experience with PDF specification, so any guidelines are welcome to correct my program.
doc_4884
The problem is that when I try to type a page directly into the address bar (e.g. example.com/page), it redirects me to the wp-login.php script/page. If I load example.com first, then type in the trailing slash and page (e.g. example.com first, then add /page and hit enter), it works. I have handed this problem over to my web hosting team, and they were not able to resolve the issue. I also worked in web-hosting before. The site is currently not the "primary domain", but does have all of its files in a sub-dir of the main root (eg. parent/public_html/subdir), but its in its own domain and document root. This is site 1, blog 2 (in wp-config.php and DB). The WordPress multi-site install loads everything else fine. Here's my .htaccess: ## EXPIRES CACHING ## <IfModule mod_expires.c> ExpiresActive On ExpiresByType image/jpg "access plus 1 year" ExpiresByType image/jpeg "access plus 1 year" ExpiresByType image/gif "access plus 1 year" ExpiresByType image/png "access plus 1 year" ExpiresByType text/css "access plus 1 month" ExpiresByType application/pdf "access plus 1 month" ExpiresByType text/x-javascript "access plus 1 month" ExpiresByType application/x-shockwave-flash "access plus 1 month" ExpiresByType image/x-icon "access plus 1 year" ExpiresDefault "access plus 2 days" </IfModule> ## EXPIRES CACHING ## RewriteCond %{SERVER_PORT} 80 RewriteCond %{HTTP_HOST} ^domain\.tld$ [OR] RewriteCond %{HTTP_HOST} ^www\.domain\.tld$ RewriteRule ^(.*)$ https://www.domain.tld/$1 [R,L] RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] # add a trailing slash to /wp-admin RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L] RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^ - [L] RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L] RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L] RewriteRule . index.php [L] # Wordfence WAF <Files ".user.ini"> <IfModule mod_authz_core.c> Require all denied </IfModule> <IfModule !mod_authz_core.c> Order deny,allow Deny from all </IfModule> </Files> # END Wordfence WAF A: When I load them with the trailing slash (e.g. /page/), it works; when I load it in the menu, it loads with trailing slash. When I just type without the trailing slash, [it doesn't work]. You missed the trailing slash in your question, so that made this question harder to fathom. To force a trailing slash on all WordPress URLs you can try adding the following directive immediately before the WordPress front-controller. RewriteRule !./$ %{REQUEST_URI}/ [R=302,L] Note that this is 302 (temporary) redirect. Only change it to a 301 (permanent) redirect when you are sure it's working OK. 301s are cached hard by the browser so can make testing problematic. This should go here: # Prevent further processing for existing files/directories RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^ - [L] # >>> HERE <<< # Front controller RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L] RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L] RewriteRule . index.php [L] If you only need to apply to a specific host then added a condition to check this. For example: RewriteCond %{HTTP_HOST} ^www\.example\.com [NC] RewriteRule !./$ %{REQUEST_URI}/ [R=302,L] I've read it's better to have the trailing slash at the end hardcoded, because it can speed up the broswer. This only applies to physical directories, not WordPress URLs. For WP URLs (or any other kind of virtual URL), it makes no difference, it's just personal preference. (FWIW, I prefer not to have the trailing slash, unless linking directly to a filesystem directory.) For physical directories, Apache (mod_dir) will issue a 301 redirect to append the trailing slash. This is necessary, in order to be able to serve the directory index (eg. index.php) from that directory. So, in order to avoid the additional redirect, you should link to directories with a trailing slash.
doc_4885
In month column, there will be 12 months and in count column , I want , addition of number of documents in that month and number of documents till previous month.For e.g.In january I have 20 documents and in Feb there are 10 documents then this Stored Procedure will return me 20+10=30 documents for February Month and likewise.How can I achieve this. A: Based on the partial information you have provided, following pseudo code should help: create table t1 ( month int, [countdocs] int) insert into t1 values (1,20),(2,10) SELECT Cur.month, isnull(Cur.countdocs,0) + isnull(Prv.countdocs,0) AS countdocs FROM t1 AS Cur LEFT OUTER JOIN t1 AS Prv ON Cur.month = Prv.month + 1; A: Look up windowing functions in SQL server. You appear to want a running total and there are techniques to get those from windowing fn.
doc_4886
Error: // ERROR: Cannot specialize non-generic type public static func ObjMappingSerializer<T: Mappable>(_ keyPath: String?) -> DataResponseSerializer<T> { 'DataResponseSerializer' return DataResponseSerializer { request, response, data, error in //LogResponse(response, data: data, error: error) Logger._reqresLogger.logResponse(response, data: data, error: error) guard error == nil else { return .failure(parseErrorResponse(data: data, response: response, errorType: error!)) } guard let _ = data else { return .failure(errorForNilData()) } let JSONToMap = deserializeJSON(request: request, response: response, data: data, error: error, keyPath: keyPath) if let json = JSONToMap as? [String:Any], let parsedObject = Mapper<T>().map(JSON:json) { return .success(parsedObject) } let errorCode = response?.statusCode ?? NSURLErrorCannotParseResponse return .failure(APIError(code: errorCode, errorUserInfo: nil)) } } Fixed by autosuggestion however next error comes Error: Trailing closure passed to parameter of type 'DataPreprocessor' that does not accept a closure public static func ObjMappingSerializer(_ keyPath: String?) -> DataResponseSerializer { return DataResponseSerializer { request, response, data, error in //LogResponse(response, data: data, error: error) Logger._reqresLogger.logResponse(response, data: data, error: error) guard error == nil else { return .failure(parseErrorResponse(data: data, response: response, errorType: error!)) } guard let _ = data else { return .failure(errorForNilData()) } let JSONToMap = deserializeJSON(request: request, response: response, data: data, error: error, keyPath: keyPath) if let json = JSONToMap as? [String:Any], let parsedObject = Mapper<T>().map(JSON:json) { return .success(parsedObject) } let errorCode = response?.statusCode ?? NSURLErrorCannotParseResponse return .failure(APIError(code: errorCode, errorUserInfo: nil)) } } Now in Alamofire many methods have been removed in Alamofire 5. How can I fix these errors? A: You can no longer initialize a DataResponseSerializer with a closure. I suggest you reevaluate your parsing needs and rebuild around responseDecodable. If you need, you can create your own serializer by adopting ResponseSerializer. Your logic would be the same, just copied into the parse method.
doc_4887
I don't see anything about that in the documentation. Any ideas ? Thanks A: hellvinz was right on track. I think that logrotate is a very appropriate solution for this. Here's a fairly solid tutorial on logrotate: The Ultimate Logrotate Command Tutorial with 10 Examples
doc_4888
My problem is: I have angular based application and some of the pages use google maps to display items on the map. Everything was working fine and I didn't change any single line of code and noticed that google maps doesn't work now. I have google script imported in index file and even not using it in main page: <script src="http://maps.google.com/maps/api/js?sensor=true&libraries=places&language=ru-RU"></script> Please open this url http://yuppi.com.ua and go to console, wait for 3 seconds and those errors will be displayed. ReferenceError: google is not defined stat.js ReferenceError: google is not defined util.js ReferenceError: google is not defined common.js A: Apparently those errors occur due to the following code in script.js file: yuppiApp.run(function($rootScope, $window) { $rootScope.$on("$locationChangeStart", function() { Object.keys($window).filter(function(k) { return k.indexOf("google") >= 0 }).forEach(function(key) { delete $window[key] }) }) }); delete $window[key] deletes google property from window object, which in turn breaks the loading of Google Maps libraries (google is a root namespace of Google Maps API). I'm not sure why google property is getting deleted in your case, but once the specified lines, for example, are commented: yuppiApp.run(function($rootScope, $window) { $rootScope.$on("$locationChangeStart", function() { //Object.keys($window).filter(function(k) { // return k.indexOf("google") >= 0 //}).forEach(function(key) { // delete $window[key] //}) }) }); the errors will disappear. A: it seems that you are using google maps before the API is actually loaded. The API is loaded asynchronously so you must be sure to reference it when is loaded. To achieve this i know 2 ways: * *you can use the "callback" query param with a global scoped function in which you will init maps elements: <script src="http://maps.google.com/maps/api/js?sensor=true&libraries=places&language=ru-RU&callback=initMap"></script> *import the Google Loader instead of the API themselves and use it to manage the API load in your JS code: <script type="text/javascript" src="https://www.google.com/jsapi"></script> then google.load('maps', '3.exp', { other_params: 'sensor=true&language=ru-RU&libraries=places', callback: function () { // You can now init your maps } });
doc_4889
public void sendnotification(String username,long user_unique){ try { Sender sender = new FCMSender(fcmKey); Message message = new Message.Builder() .collapseKey(username) .timeToLive(3) .delayWhileIdle(true) .addData(username, "Request to book ticket") .build(); String refreshedToken = FirebaseInstanceId.getInstance().getToken(); System.out.println("Refreshed token: " + refreshedToken); Result result = sender.send(message, iid, 1); System.out.println("Result: " + result.toString()); } catch (Exception e) { e.printStackTrace(); } } This will appear in the device receiving the notification as User=Request to book ticket. I want to get rid of this '=' sign in between
doc_4890
Line1: 2 3 1 6 7 Line2: 9 3 4 5 6 Line3: 2 2 2 3 3 Line4: 1 2 5 6 7 In the mapper function I need to push 2 lines at a time. (the combination will be unique). What I mean is that in the mapper function, I need to get it like: (Line 1 & Line 2) (Line 1 & Line 3) (Line 1 & Line 4) (Line 2 & Line 3) (Line 2 & Line 4) (Line 3 & Line 4) That is total 4C2 = 6 unique combination here. In that case how can I achieve that? What specific input format I need to use?
doc_4891
library(dplyr) d <- data.frame(v1 = c("a","a","b","b"), v2 = c("X","Y","Y","X")) For the "a" group, the v2 column is in the order (X,Y), which I consider the correct order. By opposition, the "b" group the order is incorrect (Y,X). Using dplyr and the do() function, I can check for each group, whether the order is correct or not: filter_fn <- function(my_row){ iX <- filter(my_row, v2 == "X")$i iY <- filter(my_row, v2 == "Y")$i res <- as.logical(iX < iY) return(data.frame(res)) } d %>% group_by(v1) %>% dplyr::mutate(i = row_number()) %>% do(filter_fn(.)) %>% ungroup() But to avoid the multiplication of functions, I want to have the logic directly written in the dplyr chain. I have tried with group_map and group_modify: d %>% group_by(v1) %>% dplyr::mutate(i = row_number()) %>% group_map( ~ { filter(.$v2 == "X")$i < filter(.$v2 == "Y")$i }) But apparently my understanding of group_map is wrong. In the documentation I don't see how a function can be used in do(.) without having to be previously defined as function per se. The expected output would be a following dataframe v1 res a TRUE b FALSE A: You can define the correct order, use match to get position of v2 and diff to calculate the difference of their occurrence in each v1. Make res as TRUE if the order matches. library(dplyr) correct_order = c('X', 'Y') d %>% group_by(v1) %>% summarise(res = all(diff(match(correct_order, v2)) > 0)) # v1 res # <chr> <lgl> #1 a TRUE #2 b FALSE A: We can either reshape to 'wide' format and then do an elementwise comparison for each of columns library(stringr) library(dplyr) library(tidyr) library(data.table) d %>% mutate(rn = str_c('col', rowid(v1))) %>% pivot_wider(names_from = rn, values_from = v2) %>% transmute(v1, res = col1 < col2) # A tibble: 2 x 2 # v1 res # <chr> <lgl> #1 a TRUE #2 b FALSE Or another option is to have an ordered variable, then grouped by 'v1', check whether all the levels of the variable is equal to the unique values in an elementwise comparison d %>% mutate(v2 = ordered(v2, c('X', 'Y'))) %>% group_by(v1) %>% summarise(res = all(levels(v2) == unique(v2))) # A tibble: 2 x 2 # v1 res # <chr> <lgl> #1 a TRUE #2 b FALSE
doc_4892
Anyway, I am trying to get this binding thing to work using DataTemplate. I have a class: public class TranslatorListItem { public string Item { get; set; } public string OriginalMessage { get; set; } public string TranslatedMessage { get; set; } public string Sector { get; set; } } Items are added like this: TranslatorListItem TLI = new TranslatorListItem(); TranslatorLVI.Items.Add(TLI); My XAML DataTemplate: <DataTemplate x:Key="MyDataTemplate"> <Border BorderBrush="#FFA4D5E5" BorderThickness="1,1,0,0" Margin="6"> <StackPanel Margin="6,2,6,2"> <TextBox Text="{Binding}" TextWrapping="Wrap" BorderThickness="0" BorderBrush="#00000000" /> </StackPanel> </Border> </DataTemplate> This is how I'm trying to bind the data but it's returning this error: "Two-way binding requires Path or XPath." <ListView Margin="23,224,27,54" Name="TranslatorLVI" ItemsSource="{Binding}" HorizontalContentAlignment="Stretch" ItemContainerStyle="{StaticResource MyItemContainerStyle}"> <ListView.View> <GridView AllowsColumnReorder="False"> <GridViewColumn Header="Item" DisplayMemberBinding="{Binding Path=Item}" CellTemplate="{StaticResource MyDataTemplate}" /> <GridViewColumn Header="Original Message" Width="300" CellTemplate="{StaticResource MyDataTemplate}" /> <GridViewColumn Header="Translated Message" DisplayMemberBinding="{Binding Path=TranslatedMessage}" CellTemplate="{StaticResource MyDataTemplate}" /> <GridViewColumn Header="Sector" DisplayMemberBinding="{Binding Path=Sector}" /> </GridView> </ListView.View> </ListView> I need TranslatedMessage binding to be editable. So that field wont be Read-Only. I heard I may need to set Two-way binding, but I am not sure how to do so. Any help is appreciated. Thanks! A: I'm trying to switch over to WPF from Winform and so far it's a pain. No, it's not. WPF is the best UI Framework in the history of mankind. winforms (or anything else) can't even be compared with it. Your problem is you're trying to use a winforms approach in WPF and you fail. WPF does not support developers with a winforms mentality. All the horrible code behind hacks you're used to from winforms are completely unneeded in WPF. Please read Rachel's Excellent Answer (and linked blog posts) about the mindshift needed when upgrading from winforms to WPF. As mentioned in @JasRaj's answer, you're missing a DisplayMemberBinding in this case. I tested your code and added that, like this: <GridViewColumn Header="Original Message" DisplayMemberBinding="{Binding OriginalMessage}" Width="300"/> And it worked perfectly. After a second read to your question I realized you wanted to make one of these columns editable. First of all I will say that while what you want can be achieved with a ListView, using a DataGrid is easier. You need to remove the DisplayMemberBindings from the ListView in order to use a CellTemplate, and therefore you need to modify the template slightly: <DataTemplate x:Key="MyDataTemplate"> <Border BorderBrush="#FFA4D5E5" BorderThickness="1,1,0,0" Margin="6"> <TextBox Text="{Binding TranslatedMessage}" TextWrapping="Wrap" BorderThickness="0" BorderBrush="#00000000" /> </Border> </DataTemplate> I have placed a ListView and a DataGrid side by side so you can compare them: Here is the XAML: <UniformGrid Columns="2"> <ListView ItemsSource="{Binding}" HorizontalContentAlignment="Stretch"> <ListView.View> <GridView AllowsColumnReorder="False"> <GridViewColumn Header="Item" DisplayMemberBinding="{Binding Path=Item}"/> <GridViewColumn Header="Original Message" DisplayMemberBinding="{Binding OriginalMessage}" Width="300"/> <GridViewColumn Header="Translated Message" CellTemplate="{StaticResource MyDataTemplate}" /> <GridViewColumn Header="Sector"/> </GridView> </ListView.View> </ListView> <DataGrid ItemsSource="{Binding}" AutoGenerateColumns="False"> <DataGrid.Columns> <DataGridTextColumn Header="Item" Binding="{Binding Path=Item}" IsReadOnly="True"/> <DataGridTextColumn Header="Original Message" Binding="{Binding OriginalMessage}" IsReadOnly="True" Width="300"/> <DataGridTextColumn Header="Translated Message" Binding="{Binding TranslatedMessage}" /> <DataGridTextColumn Header="Sector" Binding="{Binding Sector}"/> </DataGrid.Columns> </DataGrid> </UniformGrid> * *Notice how the ListView requires DataTemplates in order to support edition, and is read-only by default, while the DataGrid is editable by default, does not need any special templats and requires that you add the IsReadOnly="True" to columns that are intended to be read-only. *Also, I noticed you're adding items manually to the ListView using procedural code. This is not desired in WPF. You must use an ObservableCollection<> and manipulate that collection, and let the WPF Binding engine update the UI for you. *It is recommended and desired that you Separate logic/data from UI in WPF. *If you need further clarification please let me know. *WPF Rocks. A: Bind the second columns of Gridview with OriginalMessage property. like :- DisplayMemberBinding="{Binding Path=OriginalMessage}" it should work. A: In my opinion you dont fully use the datatemplate. you just use it to display one property; In fact you can use a DataTemplate to display all data in thie class (TranslatorListItem); such as this <DataTemplate x:Key="MyDataTemplate"> <Border BorderBrush="#FFA4D5E5" BorderThickness="1,1,0,0" Margin="6"> <TextBox Text="{Binding Item}" TextWrapping="Wrap" BorderThickness="0" BorderBrush="#00000000" /> <TextBox Text="{Binding TranslatedMessage}" TextWrapping="Wrap" BorderThickness="0" BorderBrush="#00000000" /> ( ..... follow up) </Border> </DataTemplate> So your ListView can design like this: <ListView ItemsSource="{Binding}" HorizontalContentAlignment="Stretch" ItemTemplate="{StaticResource MyDataTemplate}"> </ListView>
doc_4893
Its loadView method looks like this: - (void) loadView { [super loadView]; // some initializations } I create it from some other view controller like this -(void) createMyViewController { MyViewController *aController = [[MyViewController alloc] initWithNibName: @"MyViewController" bundle: nil ]; self.myController = aController; [aController release]; CGRect rect = CGRectMake(10, 232, 308, 176); myController.view.frame = rect; myController.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin; [self.view addSubview:graphController.view]; } I've noticed, that each time .view notation is called, loadView of MyViewController is called. I set the view property in the xib file, whether File Owner identity is set MyViewController and the view identity is set to MyView. When the view is set it doesn't suppose to call loadView each time. Please shed some light! I'm fighting this for the whole day already... Thanks a lot A: If you're creating the view in a nib file, you should be using viewDidLoad, not loadView.
doc_4894
A: You can find a couple of good examples using media components in ProScalaFX project: https://github.com/scalafx/ProScalaFX/tree/master/src/proscalafx/ch08
doc_4895
Gets called after the ChannelHandler was removed from the actual context and it doesn't handle events anymore. Thanks. A: It can called multiple times as whenever you can recover from an error or not is up to the user code.
doc_4896
article, but I still can't realize how to properly use it. I tried to repeat article's steps to provide pzRDExportWrapper, but after I click "Save" button I get the error: Method: Rule-Obj-Activity instance not found: Sb-FW-CTrackFW-Work.pzRDExportWrapper. Details: Invalid value for Activity name passed to ActivityAssembler. Could anybody give me any suggestions? Thank you. A: You invoke activity from another activity which applies to class Sb-FW-CTrackFW-Work. Rule Resolution use primary context Sb-FW-CTrackFW-Work class and try invoke activity pzRDExportWrapper from it and you get error (because rule resolution can't found invoked activity in this class). Activity pzRDExportWrapper applies to Rule-Obj-Report-Definition class. Try invoke from it. Try activity step as below: Call Rule-Obj-Report-Definition.pzRDExportWrapper Or use step page for this step which defined as applies to Rule-Obj-Report-Definition class(you can declare it on Pages&Classes tab) A: Okay. I have resolved the issue (thank you njc). I have two sections on a lone web page. A context of the first section is my custom data page Co-Name-FW-Data-Search. The Search page has some single value properties which are initialized by an user via an UI. The second section is a repeat grid section, a report definition as a source. My Search page pointed out in a Pages and Classes tab. Also there is a Page, which is created by report definition and contains results. The report definition takes Search’s values as parameters. So, I have created an activity and passed the Search page and a Cods-Pega-List MyResultList as parameters. There are some steps in the activity: * *Check if Search is null. If true- skip step; else - transfer Search properties into Params props with Data Transform. *Set Param.exportmode = "excel" *Call pzRDExportWrapper with Step Page MyResultList.pyReportDefinition. Pass current parameter page. P.S.: If it doesn’t work try to play with report definition’s settings. P.P.S.: An only minus of pzExportWrapper is that it invokes report definition again.
doc_4897
.recyclerview is not updated . In the setOnRefreshListener method, I wrote this command: The recyclerview commands are currently not updated with these commands. (I mean, when I edit the information from the server, it will not be displayed) swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { setupRecyclerView(); swipeRefreshLayout.setRefreshing(false); } }); private void setupRecyclerView() { recyclerView.setLayoutManager(linearLayoutManager); linearLayoutManager.setSmoothScrollbarEnabled(false); recyclerView.setAdapter(postsAdapter); getPosts(1); listemer = new EndlessRecyclerViewScrollListener(linearLayoutManager) { @Override public void onLoadMore(int page, int totalItemsCount, RecyclerView view) { progressBar.setVisibility(View.VISIBLE); getPosts(page); Log.e("PAGe ", "" + page); } }; recyclerView.addOnScrollListener(listemer); public void getPosts(int page) { apiService.getPosts(page, new ApiService.OnPostsReceived() { @Override public void onReceived(List<Post> posts) { openHelper.addPosts(posts); postsAdapter.addpost(posts); postsAdapter.notifyDataSetChanged(); progressDialog.hide(); progressBar.setVisibility(View.GONE); } });
doc_4898
<p-pickList (click)="refresh();" [source]="available" [target]="selected" sourceHeader="Available" targetHeader="Selected" [responsive]="true"> <ng-template let-items pTemplate="item"> <div class="ui-helper-clearfix"> <div>{{item.type}}</div> </div> </ng-template> </p-pickList>
doc_4899
{ mins = timeleft / 60; secs = timeleft % 60; if (secs > 0) { timeleft = timeleft - 1; secs = secs - 1; timerlbl.Text = "Time Left:- " + mins + ":" + secs; } if ((secs == 0) && (mins > 0)) { timeleft = timeleft - 1; mins = mins - 1; secs = 59; timerlbl.Text = "Time Left:- " + mins + ":" + secs; } if ((secs == 0) && (mins == 0)) { timerlbl.Text = "Time Left:- " + mins + ":" + secs; MessageBox.Show("times up"); timer.Stop(); } while((secs < 30) && (mins == 0)) { timerlbl.ForeColor = System.Drawing.Color.Red; } } ** the timer was working fine until i try to change the colour??? why does it get stuck at 30 seconds??? I usually use system drawing to change label colours and it works fine** A: You could simplify A LOT with just: private void timer_Tick(object sender, EventArgs e) { timeleft = timeleft - 1; mins = timeleft / 60; secs = timeleft % 60; timerlbl.Text = "Time Left:- " + mins + ":" + secs; if (timeleft < 30) { timerlbl.ForeColor = System.Drawing.Color.Red; } if (timeleft == 0) { timer.Stop(); MessageBox.Show("times up"); } }