id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23535000
A: The JVM does not use the javac compiler. The process works differently: first, the developer runs javac to compile .java files to Java bytecode (.class files), and then the JVM loads the .class files and executes the bytecode. To compile Kotlin code, you use the kotlinc compiler, which compiles .kt files to .class files. The JVM executes the bytecode from the .class files in exactly the same way; it does not care which compiler produced the .class files. When compiling pure Kotlin projects, javac is not used in any way. When you compile a mixed-language project which contains both Java and Kotlin source files, the javac compiler is used to compile Java, and the kotlinc compiler is used to compile Kotlin.
doc_23535001
While using a simple code trying to copy a cell with format to another new created worksheet, my code seems to run non-stop at the line using api.copy Does anybody know why ? import xlwings as xw workbook = xw.Book(r'my\file\path\myfile.xlsx') def my_function(): sht1 = workbook.sheets.add('Sheet1') sht = workbook.sheets[1] if sht.api.AutoFilterMode == True: sht.api.AutoFilterMode = False lr = sht.range('B' + str(sht.cells.last_cell.row)).end('up').row sht.range('A8').api.copy sht1.activate() sht1.range('A8').api.select sht1.api.paste workbook.app.api.CutCopyMode=False my_function()
doc_23535002
Can somebody tell me do i have to set Environment variable in windows xp Thanks. A: Use this way: import sys then: sys.path.insert(0,"X") Where X is the directory you want to import from. After that you just need to import your custom module: import X Thats all. A: There is a directory DIR containing our module X: /DIR/X import sys sys.path.insert(0,"DIR") import X This imports the module e.g. X =hello. A: If you're trying to make your hello.py a module you need to create a file named __init.py__ in the hello.py folder. Take a look at the Python documentation here.
doc_23535003
$('#add-question').on('click',function(){ $('#questions-container').append("{% include './create-question.twig' %}"); }) But append the literall text, Its possible to include a twig template inside another this way or similar?
doc_23535004
variables.tf variable "notebook" { type = "map" default = { "01" = "a@a.com" "02" = "b@a.com" "03" = "c@a.com" "04" = "d@a.com" ...... } } Below is my module in main.tf module "instance" { instance_ip = ["1.1.1.x", "1.1.2.y", "1.1.1.z","1.1.2.p"] dns = ["x", "y", "z","p"] name = ["a", "b", "c", "d"] } The output should be as below :- module "instance" { instance_ip = ["1.1.1.01", "1.1.2.02", "1.1.1.03","1.1.2.04" and so on] dns = ["01", "02", "03","04" and so on] name = ["a@a.com", "b@a.com", "c@a.com", "d@a.com and so on] } Any suggestions. I tried lookup on variable but getting only the a@a.com and not the Key's. A: You can use the keys and values functions for this: # terraform 0.12 module "instance" { instance_ip = ["1.1.1.${keys(var.notebook)[0]}", "1.1.1.${keys(var.notebook)[1]}", "1.1.1.${keys(var.notebook)[2]}"] dns = keys(var.notebook) name = values(var.notebook) } # terraform 0.11 module "instance" { instance_ip = ["1.1.1.${keys(var.notebook)[0]}", "1.1.1.${keys(var.notebook)[1]}", "1.1.1.${keys(var.notebook)[2]}"] dns = ["${keys(var.notebook)}"] name = ["${values(var.notebook)}"] }
doc_23535005
public delegate void ThreadProc(); [DllImport("UnmanagedTest.dll", EntryPoint = "MyUnmanagedFunction")] public static extern void MyUnmanagedFunction(); [DllImport("kernel32")] public static extern IntPtr CreateThread( IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, out uint dwThreadId); uint threadId; ThreadProc proc = new ThreadProc(MyUnmanagedFunction); IntPtr functionPointer = Marshal.GetFunctionPointerForDelegate(proc); IntPtr threadHandle = CreateThread(IntPtr.Zero, 0, functionPointer, IntPtr.Zero, 0, out threadId); My Question is: how can I simulate this situation, where all managed threads are suspended but unmanaged ones keep on spinning? My first stab: private void button1_Click(object sender, EventArgs e) { Thread t = new Thread(new ThreadStart(delegate { new Hanger(); GC.Collect(2, GCCollectionMode.Forced); })); t.Start(); } class Hanger{ private int[] m_Integers = new int[10000000]; public Hanger() { } ~Hanger() { Console.WriteLine("About to hang..."); //This doesn't reproduce the desired behavior //while (true) ; //Neither does this //Thread.Sleep(System.Threading.Timeout.Infinite); } } Thanks in advance!! A: Finalizers are executed concurrently with "normal" thread execution. We usually say that the GC runs the finalizers, but it would be truer that the GC detects which instances have finalizers which should be run, and stores them in a dedicated queue. A (hidden) thread fetches the instances from the queue and runs the finalizers. Such asynchronism is needed, e.g. because the finalizers may themselves allocate memory and potentially trigger a GC. There are other good reasons why finalizers are necessarily asynchronous. Bottom-line is that you cannot alter, from ~Hanger(), what the VM does during a GC pause, because the thread which will actually run ~Hanger() is also paused at that time. A: I realize that this does not answer your question, but I suspect a deadlock in your code rather than a strange GC issue. I would suggest to check your code for deadlocks, especially indirect cases like Control.Invoke calls when doing UI updates from background threads. Ensure that you are not holding a lock when calling an Invoke - this can cause unexpected deadlocks (as if any deadlock was expected :)) A: The issue DID in fact stem from the Garbage Collector. After many days of debugging and analyzing memory dumps with WinDbg, we realized that there was a deadlock situation, but induced by the GC collecting concurrently. Changing the GC to collect non-concurrently fixed our problem. A: Supporting Marek's answer, this seems much like a design problem with the model of concurrency you are using. Being a design problem, this is something you cannot effectively solve by testing. My advice is to carefully consider the model of concurrency you are employing, and correct the design accordingly. Start by looking into the necessary conditions for a deadlock, e.g.: * *What mutual exclusions do you have? *Which additional resources your processes (which already are using some resources) require? *Which resources need explicit releasing be the process using them? Taking these into account, if you have circular resource allocation structures you're looking into a probable deadlock situation.
doc_23535006
def build_and_test_windows(fail_build_on_test) { boolean run_tests = true build_windows(run_tests, fail_build_on_test) } def get_results_on_failure(failBuildOnFailure) { String buildResult = failBuildOnFailure ? "FAILURE" : "SUCCESS" String stageResult = failBuildOnFailure ? "FAILURE" : "UNSTABLE" return [buildResult, stageResult] } def build_windows(run_tests, fail_build_on_test) { String buildResult String stageResult (buildResult, stageResult) = get_results_on_failure(fail_build_on_test) node("windows"){ setupWorkspace() try{ stage('Windows Build') { timeout(time: 60, unit: 'MINUTES') { bat "${JENKINS_TOOLS_DIR}/platform-specific/windows/windows.bat" } } if (run_tests) { stage('Windows Unit Tests') { catchError(buildResult: buildResult, stageResult: stageResult) { timeout(time: 60, unit: 'MINUTES') { bat "${JENKINS_TOOLS_DIR}/platform-specific/windows/windows.bat TRUE" } } } } }finally{ cleanWorkspace() } and the invoking script which is something like this boolean MANDATORY_TESTS = true ... ... try{ ... parallel 'Windows' : { pipeline_utils.build_and_test_windows(MANDATORY_STAGE) ... ... completed = true }catch(Exception error){ currentBuild.result = "FAILURE" pipeline_utils.notifyPipelineFailed(currentBuild) pipeline_utils.reportBuildResultToCloudwatch("1") throw(error) } finally { if (completed && currentBuild.result != 'FAILURE') { pipeline_utils.upload_stable_sdk() def emailList = SUCCESS_EMAIL_LIST ?: "" pipeline_utils.notifyPipelineSuccess(currentBuild, emailList); pipeline_utils.reportBuildResultToCloudwatch("0") } } Now windows.bat file is failing in both instances and there are compiler issues and its last line is make: *** [Makefile:161: all] Error 2 Now currently even if the bat script is failing I am seeing both stage jobs showing as green on jenkins, I tried adding catchError to the Windows Build stage as well something like this node("windows"){   setupWorkspace()   try{     stage('Windows Build') {       catchError(buildResult: buildResult, stageResult: stageResult) {        timeout(time: 60, unit: 'MINUTES') {          bat "${JENKINS_TOOLS_DIR}/platform-specific/windows/windows.bat"        }       }     }     if (run_tests) {       stage('Windows Unit Tests') {         catchError(buildResult: buildResult, stageResult: stageResult) {           timeout(time: 60, unit: 'MINUTES') {             bat "${JENKINS_TOOLS_DIR}/platform-specific/windows/windows.bat TRUE"           }         }       }     }   }finally{     cleanWorkspace()   } But now the windows build stage job fails on Jenkins and is red but the 'Windows Unit Tests' is still showing green even though logs indicate that it should fail due to compile issues. Would be great if someone can help me understand what is going on and how to debug /fix the script, basically trying to fix the script such that both jobs fail if the bat script have errors. A: The catchError step doesn't stop the build on failure. It means that all code bellow it is executed no matter what was the result of the action executed inside it. Example: stage('1') { catchError { error 'fail build' } } stage('2') { // this stage is executed echo 'stage 2' } stage('3') { // this stage is also executed echo 'stage 3' } The build_and_test_windows method is executed in the try-finally block. The simplest option is to not use the catcheError step at all. When Windows Build fails the whole build should fail. It is given OOTB: stage('Windows Build') { timeout(time: 60, unit: 'MINUTES') { bat "${JENKINS_TOOLS_DIR}/platform-specific/windows/windows.bat" } } The tests you may mark as unstable by using the unstable step: stage('Windows Unit Tests') { timeout(time: 60, unit: 'MINUTES') { try { bat "${JENKINS_TOOLS_DIR}/platform-specific/windows/windows.bat TRUE" } catch(e) { unstable "Tests have failed" } } } However when you mark tests as unstable, the logic from your catch won't be executed: } catch (Exception error){ currentBuild.result = "FAILURE" pipeline_utils.notifyPipelineFailed(currentBuild) pipeline_utils.reportBuildResultToCloudwatch("1") throw(error) } finally { If you have to notify about the unstable tests too, then I don't think marking the stage as yellow instead of red is worth to introduce a lot of hacks. The code without any additional logic does what you need: stage('Windows Unit Tests') { timeout(time: 60, unit: 'MINUTES') { bat "${JENKINS_TOOLS_DIR}/platform-specific/windows/windows.bat TRUE" } }
doc_23535007
I am trying to find a way to enumerate the post IDs from a fan page's wall and loop through them one by one. Because I only know pepsi page's ID, I start from there. I would like to loop through each post ID after enumerating them as a list. Help very much appreciated. A: Well, you can still query the Graph API without logging into Facebook but you will need an access token. You can simply create an application and use the APP_ID|APP_SECRET as an application access token. I think this should be enough for only dealing with public posts. A call to - https://graph.facebook.com/56381779049/posts?access_token=XXX will return JSON data of the public content of/on that page. { "data": [ { "id": "56381779049_10151643119694050", "from": { "category": "Food/beverages", "name": "Pepsi", "id": "56381779049" }, "story": "\"Thanks for sharing Bobby! Love...\" on Bobby Kirchner's photo.", ... "created_time": "2013-03-29T21:35:41+0000", "updated_time": "2013-03-29T21:35:41+0000" }, { "id": "56381779049_10151639464904050", "from": { "category": "Food/beverages", "name": "Pepsi", "id": "56381779049" }, "story": "\"Hi James, sorry to hear that....\" on James Kraus II's photo.", ... "created_time": "2013-03-27T18:23:49+0000", "updated_time": "2013-03-27T18:23:49+0000" }, ... Depending on what language you are using, it would be simple to iterate over all of the data and convert it into a structure that would be easier to perform analysis. In PHP, for example, there is a json_decode() function, that converts JSON data into a normal PHP array. Note that whenever you make a query to the Facebook API's and there is a relatively large amount of data to be returned, there will be a paging mechanism within each request. It look's like this - "paging": { "previous": "https://graph.facebook.com/56381779049/posts?access_token=XXX&limit=25&since=1364592941&__previous=1", "next": "https://graph.facebook.com/56381779049/posts?access_token=XXX&limit=25&until=1362582226" }
doc_23535008
Intellij: 2016.3.2 Java: 1.7 I have a basic Springboot project using Thymeleaf as the templating engine. When I make a change to a Java file I can use menu option Build > Recompile (Ctrl + Shift + F9) to recompile. This option is not available for *.html files. (Note: this used to work). I am using an embedded tomcat as part of Spring. Any idea as to why this option is now grayed out? Assuming it must be a setting thing but I simply couldn't find anything on the web but I did read something about "Update classes and resources" options are only available when the deployment option is an "exploded" war. A: Recompiling thymeleaf files is possible by Ctrl + Shift + F9. What worked for me was to rebuild the project from scratch hence indicating some sort of project setting causing this issue. Looking at .idea/compiler.xml I can see the old file contained: <wildcardResourcePatterns> <entry name="!?*.java" /> <entry name="!?*.class" /> <entry name="!?*.groovy" /> <entry name="!?*.scala" /> <entry name="!?*.flex" /> <entry name="!?*.kt" /> <entry name="!?*.clj" /> <entry name="!?*.aj" /> </wildcardResourcePatterns> which may be the have caused this issue in conjunction with something else.
doc_23535009
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/coordinatorLayout" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true"> <android.support.design.widget.AppBarLayout android:id="@+id/appbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:fitsSystemWindows="true" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"> <android.support.design.widget.CollapsingToolbarLayout android:id="@+id/collapsing_toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:fitsSystemWindows="true" app:contentScrim="?attr/colorPrimary" app:layout_scrollFlags="scroll|exitUntilCollapsed"> <ImageView android:id="@+id/backdrop" android:layout_width="match_parent" android:layout_height="wrap_content" android:minHeight="100dp" android:fitsSystemWindows="true" android:scaleType="centerCrop" android:src="@drawable/pic" app:layout_collapseMode="parallax" app:layout_collapseParallaxMultiplier="0.5" app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed"/> <include android:id="@+id/framelayout" layout="@layout/header_layout" app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed" android:minHeight="100dp"/> </android.support.design.widget.CollapsingToolbarLayout> </android.support.design.widget.AppBarLayout> <!-- Your Scrollable View --> <android.support.v4.widget.NestedScrollView android:id="@+id/nested" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="fill_vertical" app:layout_behavior="@string/appbar_scrolling_view_behavior"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:paddingTop="24dp"> </LinearLayout> </android.support.v4.widget.NestedScrollView> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="#da1b75" android:orientation="horizontal" android:textColor="#ffffff" android:theme="@style/ThemeOverlay.AppCompat.Light" app:layout_anchor="@id/appbar" app:layout_collapseMode="pin" app:title=""> </android.support.v7.widget.Toolbar> A: Make the direct child of nested scrollview clickable ( incase you don't have just one child element,add a layout and put all your UI elements into it and make the layout clickable) android:clickable="true" I was facing similar issue and this worked for me ! Here's the code I have been working on - <?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="test.testrecycler.MaterialActivity" > <android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="300dp" android:theme="@style/AppTheme.AppBarOverlay" android:fitsSystemWindows="true" > <android.support.design.widget.CollapsingToolbarLayout android:id="@+id/collapsing_toolbar" android:layout_width="match_parent" android:layout_height="match_parent" app:contentScrim="?attr/colorPrimary" app:layout_scrollFlags="scroll|exitUntilCollapsed" app:expandedTitleTextAppearance="@style/expandedappbar" app:collapsedTitleTextAppearance="@style/collapsedappbar" app:statusBarScrim="@color/colorPrimaryDark" > <ImageView android:layout_width="match_parent" android:layout_height="match_parent" android:src="@drawable/sample" android:scaleType="centerCrop" app:layout_collapseMode="parallax" /> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" app:layout_collapseMode="pin" /> </android.support.design.widget.CollapsingToolbarLayout> </android.support.design.widget.AppBarLayout> <include layout="@layout/content_material" /> </android.support.design.widget.CoordinatorLayout> And here is the file content_material.xml having NestedScrollView.It has one child element(TextView) which has been made clickable. <?xml version="1.0" encoding="utf-8"?> <android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/content_material" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:context="test.testrecycler.MaterialActivity" tools:showIn="@layout/activity_material"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:clickable="true" android:text="This is an association football club formed in 1983, based in the town of Dover, Kent, England. In the 1989–90 season Dover Athletic won the Southern League championship, but failed to gain promotion to the Football Conference as the club's ground did not meet the required standard. Three seasons later the team won the title again and this time gained promotion to the Conference, where they spent nine seasons before being relegated. The club was transferred to the Isthmian League Premier Division in 2004, but another poor season led the club to a further relegation. After three seasons in the Isthmian League Division One South, the club won the championship and promotion back to the Premier Division, and the following season won another championship and promotion to Conference South. In the 2013–14 season, Dover defeated Ebbsfleet United to return to the Conference Premier after a twelve-year absence. Nicknamed the Whites for their white shirts, they have played at the Crabble Athletic Ground since the club's formation. Their best performance in the FA Cup was reaching the third round proper in both the 2010–11 and 2014–15 seasons. (Full article...) Recently featured: Kalki Koechlin Rogue River (Oregon) Operation Ironside Archive By email More featured articles... his time gained promotion to the Conference, where they spent nine seasons before being relegated. The club was transferred to the Isthmian League Premier Division in 2004, but another poor season led the club to a further relegation. After three seasons in the Isthmian League Division One South, the club won the championship and promotion back to the Premier Division, and the following season won another championship and promotion to Conference South. In the 2013–14 season, Dover defeated Ebbsfleet United to return to the Conference Premier after a twelve-year absence. Nicknamed the Whites for their white shirts, they have played at the Crabble Athletic Ground since the club's formation. Their best performance in the FA Cup was reaching the third round proper in both the 2010–11 and 2014–15 seasons. (Full article...)" /> </android.support.v4.widget.NestedScrollView> A: UPDATE: You can reduce image size by simply right clicking on the image in ANDROID STUDIO and Convert image to webp. This will drastically reduce image size Its very simple. I struggled a lot and finally got to know its a problem with high resolution image I had placed in src of ImageView. Solution: Just lower the resolution of the image keeping dimensions same. (Probably using Photoshop). Worked for me A: I think you forget closing tag for CoordinatorLayout. Also, put toolbar on CollapsingToolbarLayout <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/coordinatorLayout" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true"> <android.support.design.widget.AppBarLayout android:id="@+id/appbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:fitsSystemWindows="true" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"> <android.support.design.widget.CollapsingToolbarLayout android:id="@+id/collapsing_toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:fitsSystemWindows="true" app:contentScrim="?attr/colorPrimary" app:layout_scrollFlags="scroll|exitUntilCollapsed"> <ImageView android:id="@+id/backdrop" android:layout_width="match_parent" android:layout_height="wrap_content" android:minHeight="100dp" android:fitsSystemWindows="true" android:scaleType="centerCrop" android:src="@drawable/pic" app:layout_collapseMode="parallax" app:layout_collapseParallaxMultiplier="0.5" app:layout_scrollFlags="scroll|exitUntilCollapsed" /> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="#da1b75" android:orientation="horizontal" android:textColor="#ffffff" android:theme="@style/ThemeOverlay.AppCompat.Light" app:layout_anchor="@id/appbar" app:layout_collapseMode="pin" app:title="Your title"> </android.support.v7.widget.Toolbar> <!-- What is this for? <include android:id="@+id/framelayout" layout="@layout/header_layout" app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed" android:minHeight="100dp"/> --> </android.support.design.widget.CollapsingToolbarLayout> </android.support.design.widget.AppBarLayout> <!-- Your Scrollable View --> <android.support.v4.widget.NestedScrollView android:id="@+id/nested" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="fill_vertical" app:layout_behavior="@string/appbar_scrolling_view_behavior"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:paddingTop="24dp"> </LinearLayout> </android.support.v4.widget.NestedScrollView> </android.support.design.widget.CoordinatorLayout> A: I was facing a similar issues with layout containing coordinator layout and Fragments which contained RecyclerView. I added following code in CollapsingToolbarLayout to make scrolling smooth. app:layout_scrollFlags="scroll|enterAlways" A: CoordinatorLayout and CollapsingToolbarLayout smooth scroll is a bug and Google still has not fixed it. :| remove NestedScrollView. RecyclerView with app:layout_behavior="@string/appbar_scrolling_view_behavior" That's enough and fix. you can use third party library: https://github.com/henrytao-me/smooth-app-bar-layout A: If your manifest file has a android:hardwareAccelerated="false" line, delete it. A: After several attumpts, i found the right solution, not the right once but it will fixing your issue, just try to change CollapsingToolbarLayout layout_scrollInterpolator from decelerate_interpolator to a liniare one like: linear_interpolator. <com.google.android.material.appbar.CollapsingToolbarLayout android:id="@+id/collapsingtoolbar" android:layout_width="match_parent" android:layout_height="wrap_content" app:expandedTitleMargin="0dp" app:layout_scrollFlags="scroll|exitUntilCollapsed" app:layout_scrollInterpolator="@android:anim/linear_interpolator"> I hope that will help you.
doc_23535010
details on ActiveMQ's JMS transformer over AMQP: http://activemq.apache.org/amqp.html main test app @IntegrationComponentScan @SpringBootApplication public class SpringCloudStreamJmsActivemqSenderExampleApplication implements CommandLineRunner { @Bean public ConnectionFactory connectionFactory() { ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(); connectionFactory.setBrokerURL("tcp://localhost:61616"); connectionFactory.setUserName("admin"); connectionFactory.setPassword("admin"); return connectionFactory; } @Bean public ConnectionFactory connectionFactoryAMQP() { ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(); connectionFactory.setBrokerURL("tcp://localhost:5672"); connectionFactory.setUserName("admin"); connectionFactory.setPassword("admin"); return connectionFactory; } public static void main(String[] args) { SpringApplication.run(SpringCloudStreamJmsActivemqSenderExampleApplication.class, args); } @Autowired JmsGateway gateway; @Override public void run(String... strings) throws Exception { gateway.sendMessage("Hi"); } @Bean(name = PollerMetadata.DEFAULT_POLLER) public PollerMetadata poller() { return Pollers.fixedDelay(1, TimeUnit.SECONDS).get(); } @Bean(name = "outboundChannel") MessageChannel myOutBoundChannel() { return new QueueChannel(); } @Bean(name = "inboundChannel") MessageChannel myInboundChannel() { return new QueueChannel(); } @Bean(name = "errorChannel") MessageChannel myErrorChannel() { return new DirectChannel(); } @Bean IntegrationFlow jmsInboundFlow() { return IntegrationFlows.from(Jms .inboundGateway(connectionFactoryAMQP()) .destination("myCoolQueue") .errorChannel(myErrorChannel())) .handle(this::print) .get(); } @Bean IntegrationFlow jmsOutboundFlow() { return IntegrationFlows.from(myOutBoundChannel()) .handle(Jms.outboundAdapter(connectionFactory()) .destination("myCoolQueue")) .get(); } @Bean IntegrationFlow customErrorFlow() { return IntegrationFlows.from(myErrorChannel()) .handle(this::printStackTrace) .get(); } private void print(Message message) { System.out.println("Message payload: " + message.getPayload()); //throw new RuntimeException("broke it"); } private void printStackTrace(Message errorMessage) { ((ErrorMessage)errorMessage).getPayload().printStackTrace(); } } messaging gateway @MessagingGateway interface JmsGateway { @Gateway(requestChannel = "outboundChannel") void sendMessage(String message); } ActiveMQ.xml <transportConnectors> <transportConnector name="openwire" uri="tcp://0.0.0.0:0?maximumConnections=1000&amp;wireFormat.maxFrameSize=104857600"/> <transportConnector name="amqp" uri="amqp://0.0.0.0:0?maximumConnections=1000&amp;wireFormat.maxFrameSize=104857600&amp;transport.transformer=jms"/> <transportConnector name="mqtt" uri="mqtt://0.0.0.0:0?maximumConnections=1000&amp;wireFormat.maxFrameSize=104857600"/> <transportConnector name="ws" uri="ws://0.0.0.0:0?maximumConnections=1000&amp;wireFormat.maxFrameSize=104857600"/> </transportConnectors> Log output 2017-01-09 08:42:26.158 INFO 24332 --- [ restartedMain] treamJmsActivemqSenderExampleApplication : Started SpringCloudStreamJmsActivemqSenderExampleApplication in 2.676 seconds (JVM running for 3.041) 2017-01-09 08:42:31.143 WARN 24332 --- [enerContainer-1] o.s.j.l.DefaultMessageListenerContainer : Setup of JMS message listener invoker failed for destination 'myCoolQueue' - trying to recover. Cause: Disposed due to prior exception 2017-01-09 08:42:31.150 ERROR 24332 --- [enerContainer-1] o.s.j.l.DefaultMessageListenerContainer : Could not refresh JMS Connection for destination 'myCoolQueue' - retrying using FixedBackOff{interval=5000, currentAttempts=0, maxAttempts=unlimited}. Cause: Cannot send, channel has already failed: tcp://127.0.0.1:5672 2017-01-09 08:42:36.155 ERROR 24332 --- [enerContainer-1] o.s.j.l.DefaultMessageListenerContainer : Could not refresh JMS Connection for destination 'myCoolQueue' - retrying using FixedBackOff{interval=5000, currentAttempts=1, maxAttempts=unlimited}. Cause: Cannot send, channel has already failed: tcp://127.0.0.1:5672 2017-01-09 08:42:41.163 ERROR 24332 --- [enerContainer-1] o.s.j.l.DefaultMessageListenerContainer : Could not refresh JMS Connection for destination 'myCoolQueue' - retrying using FixedBackOff{interval=5000, currentAttempts=2, maxAttempts=unlimited}. Cause: Cannot send, channel has already failed: tcp://127.0.0.1:5672 A: you have to change your Bean definition by 2 ways : JNDI: @Bean public ConnectionFactory connectionFactoryAMQP() { String factoryName = "myFactoryLookup"; Properties props = new Properties(); props.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory"); props.setProperty("connectionfactory." + factoryName, "amqp://localhost:5672"); props.put("property.connectionfactory." + factoryName + ".username", "admin"); props.put("property.connectionfactory." + factoryName + ".password", "admin"); InitialContext ic = new InitialContext(props); ConnectionFactory connectionFactory = (ConnectionFactory) ic.lookup(factoryName ); return connectionFactory; } OR FACTORY: @Bean public ConnectionFactory connectionFactoryAMQP() { org.apache.qpid.jms.JmsConnectionFactory connectionFactory = new JmsConnectionFactory(); connectionFactory.setRemoteURI("amqp://localhost:5672"); connectionFactory.setUsername("admin"); connectionFactory.setPassword("admin"); return connectionFactory; } Add this dependency <dependency> <groupId>org.apache.qpid</groupId> <artifactId>qpid-jms-client</artifactId> <version>0.9.0</version> </dependency> add port in activemq.xml <transportConnector name="amqp" uri="amqp://0.0.0.0:5672?transport.transformer=jms"/> transport.transformer=jms only to convert JMS messages from/to AMQP messages on the broker side between AMQP transport & ActiveMQ, when broker receives an AMQP message through AMQP transport it is converted from AMQP message to JMS message and when a message is dispatched to consumer through AMQP transport it is converted from JMS to AMQP message. A: The ActiveMQ client only speaks the ActiveMQ native protocol OpenWire so trying to connect it to the AMQP port won't work, the connection attempt will fail. You need to use an AMQP client to connect to the AMQP port on the broker to send and receive messages over AMQP. The Apache Qpid project has a number of AMQP v1.0 client to choose from. If you want to stick to JMS type client APIs then the Qpid JMS client is the one for you.
doc_23535011
Here is my CMakeLists.txt: cmake_minimum_required(VERSION 3.0 FATAL_ERROR) project(learned_b VERSION 1.0) add_executable(PROJECT_NAME learned_benchmark.cpp) find_package(Torch REQUIRED) find_package(benchmark REQUIRED) target_link_libraries(PROJECT_NAME "${TORCH_LIBRARIES}") target_include_directories(PROJECT_NAME PUBLIC "${benchmark_INCLUDE_DIRS}") target_link_libraries(PROJECT_NAME "${benchmark_LIBRARIES}") SET(GCC_LINK_FLAGS "-isystem /Users/yhr/Programs/benchmark/include -lbenchmark -pthread") SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${GCC_LINK_FLAGS}") set_property(TARGET PROJECT_NAME PROPERTY CXX_STANDARD 11) It should be noted that with and without the GCC_LINK_FLAGS, I always get a fatal error: 'benchmark/benchmark.h' file not found. My code was compiling and running when it only depended on Pytorch. Is it possible to use find_package with google benchmark? If not how can I go about this properly? EDIT 1: here are the commands I have run. $ cd build $ cmake -DCMAKE_PREFIX_PATH='/Users/yhr/Programs/libtorch;/Users/yhr/Programs/benchmark' .. -- Configuring done -- Generating done -- Build files have been written to: /Users/yhr/Programs/learnedbloomfilters/OpenBloomFilter $ cd .. $ make VERBOSE=1 /usr/local/Cellar/cmake/3.15.4/bin/cmake -S/Users/yhr/Programs/learnedbloomfilters/OpenBloomFilter -B/Users/yhr/Programs/learnedbloomfilters/OpenBloomFilter --check-build-system CMakeFiles/Makefile.cmake 0 /usr/local/Cellar/cmake/3.15.4/bin/cmake -E cmake_progress_start /Users/yhr/Programs/learnedbloomfilters/OpenBloomFilter/CMakeFiles /Users/yhr/Programs/learnedbloomfilters/OpenBloomFilter/CMakeFiles/progress.marks /Applications/Xcode.app/Contents/Developer/usr/bin/make -f CMakeFiles/Makefile2 all /Applications/Xcode.app/Contents/Developer/usr/bin/make -f CMakeFiles/PROJECT_NAME.dir/build.make CMakeFiles/PROJECT_NAME.dir/depend cd /Users/yhr/Programs/learnedbloomfilters/OpenBloomFilter && /usr/local/Cellar/cmake/3.15.4/bin/cmake -E cmake_depends "Unix Makefiles" /Users/yhr/Programs/learnedbloomfilters/OpenBloomFilter /Users/yhr/Programs/learnedbloomfilters/OpenBloomFilter /Users/yhr/Programs/learnedbloomfilters/OpenBloomFilter /Users/yhr/Programs/learnedbloomfilters/OpenBloomFilter /Users/yhr/Programs/learnedbloomfilters/OpenBloomFilter/CMakeFiles/PROJECT_NAME.dir/DependInfo.cmake --color= /Applications/Xcode.app/Contents/Developer/usr/bin/make -f CMakeFiles/PROJECT_NAME.dir/build.make CMakeFiles/PROJECT_NAME.dir/build [ 50%] Building CXX object CMakeFiles/PROJECT_NAME.dir/learned_benchmark.cpp.o /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++ -DAT_PARALLEL_OPENMP=1 -D_THP_CORE -I/Users/yhr/Programs/learnedbloomfilters/OpenBloomFilter -isystem /Users/yhr/programs/libtorch/include -isystem /Users/yhr/programs/libtorch/include/torch/csrc/api/include -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk -mmacosx-version-min=10.14 -Wall -Wextra -Wno-unused-parameter -Wno-missing-field-initializers -Wno-write-strings -Wno-unknown-pragmas -Wno-missing-braces -std=gnu++11 -o CMakeFiles/PROJECT_NAME.dir/learned_benchmark.cpp.o -c /Users/yhr/Programs/learnedbloomfilters/OpenBloomFilter/learned_benchmark.cpp /Users/yhr/Programs/learnedbloomfilters/OpenBloomFilter/learned_benchmark.cpp:4:10: fatal error: 'benchmark/benchmark.h' file not found #include <benchmark/benchmark.h> ^~~~~~~~~~~~~~~~~~~~~~~ 1 error generated. make[2]: *** [CMakeFiles/PROJECT_NAME.dir/learned_benchmark.cpp.o] Error 1 make[1]: *** [CMakeFiles/PROJECT_NAME.dir/all] Error 2 make: *** [all] Error 2 A: You use find_package correctly, but you misuse what it defines. The find_package command don't export XY_LIBRARIES and XY_INCLUDE_DIRECTORIES when using exported packages. You'll notice it if you print the values of those variable. Instead, modern CMake packages export targets. This is true for all projects that uses package exportation instead of find modules. To link to an imported target, you should use target_link_libraries: target_link_libraries(PROJECT_NAME PRIVATE benchmark::benchmark) This will add all necessary flags for all CPP insinde the PROJECT_NAME target to be able to use google benchmark. You can drop flags variable (don't toutch CMAKE_CXX_FLAGS and link flags!) and use more robust constructs instead, like the target based target_link_libraries.
doc_23535012
Lets assume that this calendar is accessible over HTTP at a URL like this http://www.example.com/cal?q=<user query> Everything works fine so far. Now I want to let the users subscribe to this calendar with their favourite calendar client. For ios I can achieve this if I publish the calendar URL with the webcal:// URL scheme. * *Is there an equivalent URL scheme for Android ? *Can I let the user import this calendar into his Google calendar ? *Are there any other options that I didn't think about ? Thank you A: Since this is showing as unanswered, with upvotes on the question, I'm making my comment a more formal answer: * *The 'standard' for calendar files is a http/s url .ics with mime type text/calendar. Webcal is just apple doing their own thing. All calendar applications should accept the open standard *Yes, if your url is publicly accessible, they can subscribe to it. Alternatively they can do a once off import *The RFC 5545 standard is the way to go for calendars and events https://www.rfc-editor.org/rfc/rfc5545#section-8.1
doc_23535013
It was obvious for our initial facilities because the code is named after our city (America/Edmonton). How can I more generally determine the correct timezone code to use in Java via the call DateTimeZone.forID("timeZone") ex DateTimeZone.forID("America/Edmonton")? Specifically we are opening a facility in Atlanta Georgia and I am unsure which code to use? Is it one of these? * *"Atlantic/South_Georgia" *US/Eastern" *"EST5EDT" *"EST" A: The IANA standard timezone identifier for Eastern Time is America/New_York. Presumably this is the standard Joda time is using, since (1) everyone uses it and (2) the city-name-as-identifier gives it away. A: This kind of information can be really tricky (not to mention tricky to keep current). It can actually vary county by county (there is an excellent West Wing scene about this :). Google Maps API recently included support to go from lat+lon to TimeZone A: You can get a list with: for (String string : TimeZone.getAvailableIDs(TimeZone.getTimeZone( "GMT-05:00").getRawOffset())) { System.out.println(string); } And it will include (among many others) "US/Eastern". A: You can list the available timezone id's using this method: http://docs.oracle.com/javase/7/docs/api/java/util/TimeZone.html#getAvailableIDs() The time zone data seems to come from this database: http://en.wikipedia.org/wiki/Tz_database You can do lookups in it here: http://twiki.org/cgi-bin/xtra/tzdatepick.html
doc_23535014
* *Native library is built *Native library is copied to output directory to my main application Is it possible to do that with project.json and "dotnet build/publish" command? A: Open the property window of your native C++ project. Find Build Events/Post-Build Event/Command Line. Then input the following commands to copy the built dll and pdb files to the output directory of your main application. xcopy /Y /S "$(OutDir)*.dll" "E:\output_directory_to_my_main_application" xcopy /Y /S "$(OutDir)*.pdb" "E:\output_directory_to_my_main_application"
doc_23535015
<filter> <filter-name>GZipFilter</filter-name> <display-name>Jetty's GZip Filter</display-name> <description>Filter that zips all the content on-the-fly</description> <filter-class>org.mortbay.servlet.GzipFilter</filter-class> <init-param> <param-name>mimeTypes</param-name> <param-value>text/html</param-value> </init-param> </filter> <filter-mapping> <filter-name>GZipFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> I'm just starting to use Jetty, so the solution might be ridiculously simple. If you can link me to documentation that might help me, that would be great too. A: GZIP Compression GZIP Compression can be used to reduce the amount of data being sent "over the wire". Compression is applied as a transport encoding. This can greatly improve webapplication performance, however it can also consume more CPU and some content (eg images) cannot be well compressed. Static Content The Jetty Default Servlet can serve precompressed static content as a transport encoding and avoid the expense of on-the-fly compression. If the "gzip" init parameter is set to true, then Jetty will look for compressed static resources. So if a request for "foo.txt" is received and the file "foo.txt.gz" exists, then it will be served as "foo.txt" with a gzip transport encoding. GzipFilter The Jetty Gzip Filter is a compression filter that can be applied to almost any dynamic resource (servlet). It fixes many of the bugs in commonly available compression filters (eg handles all ways that content length may be set) and has been testing with Jetty continuations and suspending requests. Some user-agents may be excluded from compression, so as to avoid some common browser bugs (yes this means IE!). refer from jetty doc: http://docs.codehaus.org/display/JETTY/GZIP+Compression you can look Gzipfilter source code,here is a lot of useful comments : http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/servlets/GzipFilter.html A: I'm gonna answer this too, since I've had a huge headake trying to make this work, and I finally did it. Also, I'm not a major expert in the fine details of HTTP so I'll give a non-professional answer. First, here's how I checked if my GZipFilter was working or not. Started Firefox, made sure I had the Firebug addon, started the Firebug addon, went to the "Net" tab. Then I accessed the URL which should return a GZipped response. Here's what Firebug shows: The "Size" column shows the size of the response. If you hover over the "Size" column label with your mouse, it will tell you that if the response is compressed, then it will display the compressed size of the response. This all was done with the GZip filter enabled in Jetty. I then removed the GZip filter declaration from my web.xml, restarted Jetty and repeated the test. This time around the response had the exact same size as before, which clearly indicated that the GZip compression was not working. After multiple trial and errors, what I did is look in Firebug at the "Request Headers" section to see the value for the "Accept" header. I've noticed that here this had values such as "application/xml" and "text/xml", but the way I had configured my GZIp filter's init param "mimeTypes" only contained "text/xml" (and was missing "application/xml"). It was configured like so: <filter> <filter-name>GzipFilter</filter-name> <filter-class>org.eclipse.jetty.servlets.GzipFilter</filter-class> <init-param> <param-name>mimeTypes</param-name> <param-value>text/html,text/plain,text/xml,application/xhtml+xml,text/css,application/javascript,image/svg+xml,application/json,application/xml; charset=UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>GzipFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> After adding the "application/xml" value to the list like so: <filter> <filter-name>GzipFilter</filter-name> <filter-class>org.eclipse.jetty.servlets.GzipFilter</filter-class> <init-param> <param-name>mimeTypes</param-name> <param-value>text/html,text/plain,text/xml,application/xhtml+xml,application/xml,text/css,application/javascript,image/svg+xml,application/json,application/xml; charset=UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>GzipFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> I redid my previous test, and sure enough now the reported size of the response was much smaller: Also notice that now, the reported Response Headers contain an extra field called "Content-Encoding" with a value of "gzip". So basically the idea is to check what kind of values you send in your Request "Accept" header and make sure that all those values are configured in the GZip filter's "mimeTypes" init param. A: Sometimes using Gzipfilter has some problems, depending on how you are handling buffers and flushing. As such, using org.eclipse.jetty.servlets.IncludableGzipFilter (which actually an extends GzipFilter) may solve your problems. A: On jetty 9.3: * *edit jetty.conf and include the xml file "jetty-gzip.xml" *edit start.ini and add "--module=servlets" *edit jetty-gzip.xml and configure the mime-types you want. *Restart jetty and test again. A: What was the error? Are you getting classpath problems or something else? If classpath, you need to make sure the gzipfilter class is available to the jetty runtime or it will die. A: Are you sending the request with the "Content-Encoding: gzip" request header?
doc_23535016
I am thinking of two options Option 1: Plugin based architecture: Create a single api that will load specific plugins. Each client requirement is implemented in class library and load the desired plugin based on request. Like a request is made by client A. client A plugin to be loaded and then this will handle the request. Option 2: Separate Api for each client: Each client requirement is implemented in a separate Api. The authentication scheme is same to provide and redirect to this url. What is best way to handle this?
doc_23535017
struct ukai { int val[1]; }; struct kai { struct ukai daddr; struct ukai saddr; }; struct kai *k, uk; uk.saddr.val[0] = 5; k = &uk; k->saddr.val[0] = 6; unsigned int *p = (unsigned int *)malloc(sizeof(unsigned int)); p[0] = k; int *vp; vp = ((uint8_t *)p[0] + 4); printf("%d\n", *vp); This produces a segmentation fault. However if we replace the last line with printf("%u\n", vp) it gives the address i.e. &(k->saddr.val[0]). However I am unable to print the value present at the address using p[0] but able to print it using k->saddr.val[0]. I have to use p pointer in some way to access value at val[0], I can't use pointer k. I need help here, whether it is even possible or not please let me know. A: The code makes no sense: * *p[0] = k; converts the value of a pointer k to an int as p is a pointer to int. This is implementation defined and loses information if pointers are larger than type int. *vp = ((uint8_t *)p[0] + 4); converts the int pointed to by p to a pointer to unsigned char and makes vp point to the location 4 bytes beyond this pointer. If pointers are larger than int, this has undefined behavior. Just printing the the value of this bogus pointer might be OK, but dereferencing it has undefined behavior. *printf("%u\n", vp) uses an incorrect format for pointer vp, again this is undefined behavior, although it is unlikely to crash. The problem is most likely related to the size of pointers and integers: if you compile this code as 64 bits, pointers are larger than ints, so converting one to the other loses information. Here is a corrected version: struct ukai { int val[1]; }; struct kai { struct ukai daddr; struct ukai saddr; }; struct kai *k, uk; uk.saddr.val[0] = 5; k = &uk; k->saddr.val[0] = 6; int **p = malloc(sizeof *p); p[0] = k; int *vp = (int *)((uint8_t *)p[0] + sizeof(int)); printf("%d\n", *vp); // should print 6 A: There is a lot of "dirty" mess with the addresses done here. Some of this stuff is not recommended or even forbidden from the standard C point of view. However such pointer/addresses tweaks are commonly used in low level programming (embedded, firmware, etc.) when some compiler implementation details are known to the user. Of course such code is not portable. Anyway the issue here (after getting more details in the comments section) is that the machine on which this code runs is 64 bits. Thus the pointers are 64 bits width while int or unsigned int is 32 bits width. So when storing address of k in p[0] p[0] = k; while p[0] is of type unsigned int and k is of type pointer to struct kai, the upper 32 bits of the k value are cut off. To resolve this issue, the best way is to use uintptr_t as this type will alway have the proper width to hold the full address value. uintptr_t *p = malloc(sizeof(uintptr_t)); Note: uintptr_t is optional, yet common. It is sufficient for a void*, but maybe not a function pointer. For compatible code, proper usage of uintptr_t includes object pointer --> void * --> uintptr_t --> void * --> object pointer.
doc_23535018
Dim dte As String, db As Database, tableName As String, DataDump As Recordset, clientTable As Recordset Set db = CurrentDb dte = InputBox("What date was the Data Dump run?", "Please Input a date") tableName = "FN_DataDump_ALL_" & dte Set DataDump = db.OpenRecordset(tableName, dbOpenDynaset, dbEditAdd) Set clientTable = db.OpenRecordset("Clients", dbOpenDynaset, dbEditAdd) MySQL = "SELECT DISTINCT DD.[Client ID] " & _ "INTO Clients " & _ "FROM " & tableName & "as DD " & _ "Where CL.[Client ID] NOT IN (SELECT DD.[Client ID] ""FROM"" & tableName & ""as DD"") " db.Execute MySQL A: Misplaced quotes around FROM and a missing space produced TABLENAMEAS, instead: = "SELECT DISTINCT DD.[Client ID] " & _ "INTO Clients " & _ "FROM " & tableName & " as DD " & _ "Where CL.[Client ID] NOT IN (SELECT DD.[Client ID] FROM " & tableName & " as DD)"
doc_23535019
I'd run firebase setup:web --json > ./src/firebase-config.json in my package.json and then read from the config during initializeApp. But now, setup:web is deprecated and no longer works. So you're supposed to use apps:sdkconfig web [project-id] instead, but I can't get it to work like I did before. If I downgrade firebase-tools, I can get it to work again the old way. * *In the new setup (using apps:sdkconfig), you must pass the project id and I'd like a way to auto pass this (i.e. it should know the project I switched to via firebase use). *And the second issue, is that even when testing this by passing my current project id explicitly, I'm getting scope errors: [debug] [2020-05-09T16:18:57.519Z] > command requires scopes: ["email","openid","https://www.googleapis.com/auth/cloudplatformprojects.readonly","https://www.googleapis.com/auth/firebase","https://www.googleapis.com/auth/cloud-platform"] [debug] [2020-05-09T16:18:57.519Z] > authorizing via signed-in user [debug] [2020-05-09T16:18:57.526Z] > refreshing access token with scopes: ["email","https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/cloudplatformprojects.readonly","https://www.googleapis.com/auth/firebase","openid"] [debug] [2020-05-09T16:18:57.527Z] >>> HTTP REQUEST POST https://www.googleapis.com/oauth2/v3/token <request body omitted> [debug] [2020-05-09T16:18:57.722Z] <<< HTTP RESPONSE 200 {"content-type":"application/json; charset=utf-8","vary":"X-Origin, Referer, Origin,Accept-Encoding","date":"Sat, 09 May 2020 16:18:57 GMT","server":"scaffolding on HTTPServer2","cache-control":"private","x-xss-protection":"0","x-frame-options":"SAMEORIGIN","x-content-type-options":"nosniff","alt-svc":"h3-27=\":443\"; ma=2592000,h3-25=\":443\"; ma=2592000,h3-Q050=\":443\"; ma=2592000,h3-Q049=\":443\"; ma=2592000,h3-Q048=\":443\"; ma=2592000,h3-Q046=\":443\"; ma=2592000,h3-Q043=\":443\"; ma=2592000,quic=\":443\"; ma=2592000; v=\"46,43\"","accept-ranges":"none","transfer-encoding":"chunked"} [debug] [2020-05-09T16:18:57.738Z] >>> HTTP REQUEST GET https://firebase.googleapis.com/v1beta1/projects/-/webApps/[projectId]/config [debug] [2020-05-09T16:18:57.969Z] <<< HTTP RESPONSE 400 {"vary":"X-Origin, Referer, Origin,Accept-Encoding","content-type":"application/json; charset=UTF-8","date":"Sat, 09 May 2020 16:18:57 GMT","server":"ESF","cache-control":"private","x-xss-protection":"0","x-frame-options":"SAMEORIGIN","x-content-type-options":"nosniff","alt-svc":"h3-27=\":443\"; ma=2592000,h3-25=\":443\"; ma=2592000,h3-Q050=\":443\"; ma=2592000,h3-Q049=\":443\"; ma=2592000,h3-Q048=\":443\"; ma=2592000,h3-Q046=\":443\"; ma=2592000,h3-Q043=\":443\"; ma=2592000,quic=\":443\"; ma=2592000; v=\"46,43\"","accept-ranges":"none","transfer-encoding":"chunked"} [debug] [2020-05-09T16:18:57.969Z] <<< HTTP RESPONSE BODY {"error":{"code":400,"message":"Request contains an invalid argument.","status":"INVALID_ARGUMENT"}} [debug] [2020-05-09T16:18:57.972Z] HTTP Error: 400, Request contains an invalid argument. [debug] [2020-05-09T16:18:57.975Z] FirebaseError: HTTP Error: 400, Request contains an invalid argument. Anyone have a nice way to switch configuration in their Firebase React projects? Here is the full info on the old way I used to do it: https://stackoverflow.com/a/59592541/2946924 A: You can indeed use firebase apps:sdkconfig, like this: firebase apps:sdkconfig web --json > ./firebase-config.json. More info here
doc_23535020
define("DB_USER","root"); define("DB_PASSWORD",""); define("DB_DB","exotic_live"); define("DB_HOST", "localhost"); throwing an error Parse error: syntax error, unexpected T_STRING, expecting T_FUNCTION in C:\xampp\htdocs\test\config\db.php on line 5 complete code is class Database{ //define('DB_HOST','localhost'); define("DB_USER","root"); define("DB_PASSWORD",""); define("DB_DB","exotic_live"); define("DB_HOST", "localhost"); private function db_connect(){ $this->dbconnect(); } private function dbconnect() { $conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die ("<br/>Could not connect to MySQL server"); mysql_select_db(DB_DB,$conn) or die ("<br/>Could not select the indicated database"); return $conn; } } $obj_db=new Database(); $obj_db->db_connect(); A: Constants made with define() are global constants, and define()s cannot appear in a class definition (unless they're in one of its methods). Class constants are defined like this: const DB_USER = "root"; const DB_PASSWORD = ""; const DB_DB = "exotic_live"; const DB_HOST = "localhost"; And referenced within the same class like this: private function dbconnect() { $conn = mysql_connect(self::DB_HOST, self::DB_USER, self::DB_PASSWORD) or die ("<br/>Could not connect to MySQL server"); mysql_select_db(self::DB_DB,$conn) or die ("<br/>Could not select the indicated database"); return $conn; } And referenced outside the class with Database:: instead of self:: (like static members). A: You cannot place define inside a propriety class declaration. Put them out //define('DB_HOST','localhost'); define("DB_USER","root"); define("DB_PASSWORD",""); define("DB_DB","exotic_live"); define("DB_HOST", "localhost"); class Database{ [...] } A: You can't define constants inside a class definition. Either define them outside, or define them as class constants. A: To define constants within an class use the following syntax: class Foo { const Bar = 'value'; }
doc_23535021
#include <vector> #include <iostream> #include <algorithm> //Create predicate for find_if template<typename T> struct eq { eq(const T _x) : x(x) { }; //Does not work bool operator()(typedef std::vector<T>::iterator it) const { // return *it <= x && x < *(++it); } private: T x; }; //Make vector std::vector<double> vDouble; vDouble.push_back(1.5); vDouble.push_back(3.1); vDouble.push_back(12.88); vDouble.push_back(32.4); double elemVal = *std::find_if(vNumeric.begin(), vNumeric.end(), eq<double>(13.0)); A: With std::adjacent_find, you may simply do: const auto x = 13.0; auto it = std::adjacent_find(v.begin(), v.end(), [x](double lhs, double rhs){ return lhs <= x && x < rhs; }); Demo
doc_23535022
int main(){ unsigned char mask = 192; //1100 0000 unsigned char* bitmap; bitmap[0] = 0x80; bitmap[1] = 0xC8; bitmap[2] = 0x2F; bitmap[3] = 0x0; int num_frames = 16; int frame_size_in_bits = 2; int desired_hole = 0; int hole_counter = 0; for(int i = 0; i < 4; ++i){ for(int j = 0; j < 4; ++j){ if((mask & bitmap[i]) == mask){ //std::cout << std::hex << int(mask) << " " << std::hex << int(bitmap[i]) << std::endl; hole_counter++; } mask = mask/4; } mask = 192; } std::cout << "Num holes: " << hole_counter << std::endl; } I am trying to check the number of times that 11 occurs in each byte of my bitmap. I have designated 11 as free for allocation. I check the byte with the mask, bitshift the mask to the right two times, and repeat. I have populated the bitmap with 3 "holes" where 11 occurs and satisfies my search. However, when I run this code with the std::cout line commented out, I get that the number of holes is zero. I'm thinking "okay, my logic is off". But when I enable the comment, I get my desired output. Does anyone know why disabling/enabling this comment alters the value of hole_counter during code execution? This is leaving me scratching my head. Thanks! A: You never allocated memory to "char* bitmap" in C you can do it like char *bitmap= NULL; /* declare a pointer, and initialize to NULL */ bitmap= malloc (5 * sizeof *bitmap); in C++ unsigned char* bitmap= new unsigned char[4]; int main(){ unsigned char mask = 192; //1100 0000 unsigned char* bitmap= new unsigned char[4]; bitmap[0] = 0x80; bitmap[1] = 0xC8; bitmap[2] = 0x2F; bitmap[3] = 0x0; int num_frames = 16; int frame_size_in_bits = 2; int desired_hole = 0; int hole_counter = 0; for(int i = 0; i < 4; ++i){ for(int j = 0; j < 4; ++j){ if((mask & bitmap[i]) == mask){ //std::cout << std::hex << int(mask) << " " << std::hex << int(bitmap[i]) << std::endl; hole_counter++; } mask = mask/4; } mask = 192; } std::cout << "Num holes: " << hole_counter << std::endl; }
doc_23535023
This works fine: electron-builder --x64 --publish never But this don't: electron-builder --x64 Build fails • electron-builder version=22.7.0 os=5.4.0-1020-azure • loaded configuration file=package.json ("build" field) • packaging platform=linux arch=x64 electron=9.1.1 appOutDir=releases/linux/x64/linux-unpacked • downloading url=https://github.com/electron/electron/releases/download/v9.1.1/electron-v9.1.1-linux-x64.zip size=73 MB parts=4 • downloaded url=https://github.com/electron/electron/releases/download/v9.1.1/electron-v9.1.1-linux-x64.zip duration=1.219s • building target=7z arch=x64 file=releases/linux/x64/PasswordTool • publishing publisher=Github (owner: rockg688, project: rock_test, version: 0.0.0) ⨯ ENOENT: no such file or directory, stat '/home/runner/work/rock_test/rock_test/PasswordTool_GUI/releases/linux/x64/PasswordTool' stackTrace=Error: ENOENT: no such file or directory, stat '/home/runner/work/rock_test/rock_test/PasswordTool_GUI/releases/linux/x64/PasswordTool' If we look closely rock_test/rock_test rock_test is repo folder. But I don't know why it is repeating twice and how to fix it...
doc_23535024
private void ConfigureAuthPipeline(IAppBuilder app) { var listener = (HttpListener)app.Properties[typeof(HttpListener).FullName]; //Exception happens here!! listener.AuthenticationSchemes = AuthenticationSchemes.Ntlm; } The problem is it does not find a property with that name, or anything with HttpListener. here's the content of the app.Properties: [0]: {[builder.AddSignatureConversion, System.Action1[System.Delegate]]} [1]: {[builder.DefaultApp, System.Func2[System.Collections.Generic.IDictionary[System.String,System.Object],System.Threading.Tasks.Task]]} [2]: {[host.Addresses, System.Collections.Generic.List1[System.Collections.Generic.IDictionary2[System.String,System.Object]]]} [3]: {[host.AppName, MyDLL.WebAPI.Tests.Startup, MyDLL.WebAPI.Tests, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]} [4]: {[host.AppMode, development]} [5]: {[host.TraceOutput, Microsoft.Owin.Hosting.Tracing.DualWriter]} [6]: {[host.TraceSource, System.Diagnostics.TraceSource]} [7]: {[server.LoggerFactory, System.Func2[System.String,System.Func6[System.Diagnostics.TraceEventType,System.Int32,System.Object,System.Exception,System.Func3[System.Object,System.Exception,System.String],System.Boolean]]]} [8]: {[host.OnAppDisposing, System.Threading.CancellationToken]} The test method I'm trying to run is: [Fact] public async void TestGetValuesWithAuthorize() { const string baseAddress = "http://localhost:9050/"; // Start OWIN host using (WebApp.Start<Startup>(url: baseAddress)) { using (var client = new HttpClient()) { client.BaseAddress = new Uri(baseAddress); var response = await client.GetAsync("/api/Values"); var result = await response.Content.ReadAsAsync<List<string>>(); Assert.Equal(2, result.Count); } } } A: was missing passing the HttpClientHandler with UseDefaultCredentials = true Working solution: // Start OWIN host using (WebApp.Start<Startup>(url: baseAddress)) { var handler = new HttpClientHandler { UseDefaultCredentials = true }; using (var client = new HttpClient(handler)) { client.BaseAddress = new Uri(baseAddress); var response = await client.GetAsync("/api/Values"); response.EnsureSuccessStatusCode(); var result = await response.Content.ReadAsAsync<List<string>>(); Assert.Equal(2, result.Count); } }
doc_23535025
But now I'm curious to find the without beautifulsoup with recompile method How should I find the import re </head> <body> <a href="https://programmers.co.kr/learn/courses/4673"></a>#!MuziMuzi!)jayg07con&& </body> I tried re.findall('<body>(.*?)</body>', html, re.DOTALL) but nothing to find A: If you have to, it seems it might be just missing the r: import re exp = """ </head> <body> <a href="https://programmers.co.kr/learn/courses/4673"></a>#!MuziMuzi!)jayg07con&& </body> """ print(re.findall(r"<body>(.*?)</body>", exp ,re.DOTALL)) Output ['\n<a href="https://programmers.co.kr/learn/courses/4673"></a>#!MuziMuzi!)jayg07con&&\n\n']
doc_23535026
special_keys = ["`", "~", "!", "@", " ", "#", "$"] while True: num1 = input("Enter First Number: ") if num1.isalpha(): print("Invalid, Try Again.") continue # elif num1 contains an element or part of an # element in special_keys do the following: # print("Invalid, Try Again.") # continue else: num1 = float(num1) break A: All of this is not necessary. You can simply try to convert the input to a float. If it throws an error, it means that the input is not a valid number. You can catch this error using a try-except block and print Invalid: while True: num1 = input("Enter First Number: ") try: num1 = float(num1) break except ValueError: print("Invalid") Output: Enter First Number: >? 1` Invalid Enter First Number: >? 1-0-0 Invalid Enter First Number: >? 100 A: Instead of checking whether the string contains an alphabetic character or a special character, you can check directly whether it represents a number or not: def input_number(prompt_msg, err_msg): we_got_a_number = False while not we_got_a_number: num_string = input(prompt_msg) try: num = int(num_string) we_got_a_number = True except ValueError: print(err_msg) return num num1 = input_number("Enter First Number: ", "Invalid, Try Again.") If you want to use floats instead of ints, just replace int(num_string) with float(num_string). A: Instead of warn for alpha, you can warn for non digit : if !num1.isisdigit(): print("Invalid, Try Again.") continue
doc_23535027
That's a method in the Social.framework. The document say that the method returns a Boolean value indicating whether the service is accessible and at least one account is set up. But when I installed Twitter client, the method always return true whether or not the account is added in the Settings. I run a demo on real devices such as iPhone 6s with iOS 9.3, iPhone 6 Plus with iOS 9.0, iPhone 5s with iOS 8.2. A: I have the same problem.and I use ACAccountStore to judge whether user has already set system twitter account ACAccountStore *accountStore = [[ACAccountStore alloc] init]; ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter]; NSArray *twitterAccounts = [accountStore accountsWithAccountType:accountType];
doc_23535028
<a href="http://example.com/privacy/">Privacy</a> I'm planning to clone this site and would like to have a way so that the domain part of this link will automatically change when I deploy it to a different site. The name of the web page will remain the same. For example, if I deploy it to MySite2, it would be: <a href="http://example2.com/privacy/">Privacy</a> Is there Wordpress variable that I can use? I suspect I need something like: <a href="[WordPress Site Var]/privacy/">Privacy</a> Does anyone happen to have the exact link that I would use? A: Seems you want a function that gets your URL dynamically. Something like <a href="<?php echo site_url(); ?>/privacy/">Privacy<\a> Find more about this function at https://codex.wordpress.org/Function_Reference/site_url A: If you want a dynamic URL that is in a shortcode - that's what I thnk you mean with the brackets around [WordPress Site Var] that will go in page/post content - than you're talking about a shortcode. You can't execute PHP in post/page content without a plugin; and a shortcode is much better for portability, anyway. Create a shortcode for the whole <a href... link, not just the URL, i.e.: function shortcode_for_a_url() { ob_start();?> <a href="https://codex.wordpress.org/Function_Reference/bloginfo"> Function Reference/bloginfo « WordPress Codex </a> <?php return ob_get_clean(); } add_shortcode('my_url_shortcode', 'shortcode_for_a_url'); in your theme functions.php file. Use [my_url_shortcode] in post/page content. That shortcode will output the html <a href="https://codex.wordpress.org/Function_Reference/bloginfo">Function Reference/bloginfo « WordPress Codex</a> You can also throw that function into a simple plugin to make the shortcode portable and outside of the theme: <?php /* Plugin Name: My Shortcodes Description: My URL Shortcodes Version: 1.0 License: GPL Author: Blah Blah Author URI: http://example.com */ function shortcode_for_a_url() { blah blah blah... If you need a PHP function to go in a theme file, then see Function Reference/bloginfo « WordPress Codex for all the standard Wordpress parameters, i.e. using <?php bloginfo( $show ); ?> and the variable: admin_email = admin@example.com atom_url = http://www.example.com/home/feed/atom charset = UTF-8 comments_atom_url = http://www.example.com/home/comments/feed/atom comments_rss2_url = http://www.example.com/home/comments/feed description = Just another WordPress blog home = http://www.example.com/home (DEPRECATED! use url option instead) html_type = text/html language = en-US name = Testpilot pingback_url = http://www.example.com/home/wp/xmlrpc.php rdf_url = http://www.example.com/home/feed/rdf rss2_url = http://www.example.com/home/feed rss_url = http://www.example.com/home/feed/rss siteurl = http://www.example.com/home (DEPRECATED! use url option instead) stylesheet_directory = http://www.example.com/home/wp/wp-content/themes/largo stylesheet_url = http://www.example.com/home/wp/wp-content/themes/largo/style.css template_directory = http://www.example.com/home/wp/wp-content/themes/largo template_url = http://www.example.com/home/wp/wp-content/themes/largo text_direction = ltr url = http://www.example.com/home version = 4.2.1 wpurl = http://www.example.com/home/wp
doc_23535029
Can you give me a schema for constructing such an engine? My idea is to make a program that: * *read the code section of a file *encrypts it in a buffer, *make space at the beginning (is it possible?) to add the decrypt routine *write the new buffer inside the code section of the program. Is that right? Does it reflect the operation of such an engine? A: The basic schema is quite different from that you've described. Usually only the virus body is encrypted, an not the whole code section. Consider a simple virus that either extends code section, either creates a new one for its body. Now, to make it polymorphic, you have to add encryption and make the decryptor code to be non-constant, eg: 1) insert nops randomly (nop, add reg, 0, push reg; pop reg, etc) 2) change the program flow with ( jmp next, clc; jc next, etc) 3) use instructions with the same arithmetic effect (add eax, 3 -> add eax, 9; sub eax, 6) Polymorphic means that it could have a fixed number of encodings, so the simpliest way to create one is to break the decryptor code in several blocks, and provide several encoding with the same length for each. EDIT: Yes, it's a part of the virus body. In order to use it you put all these "bricks" in the virus body, and when another file is infected, you create a random version of the decriptor for it.
doc_23535030
So, here is my solution: public class MyTask extends TimerTask { public void run(){ //do process file stuff if(scheduledExecutionTime() != 0){ TimerHelper.restartMyTimer(); } } } public class TimerHelper { public static HashTable timersTable = new HashTable(); public static void restartMyTimer(){ Calendar runDate = Calendar.getInstance(); runDate.set(Calendar.DAY_OF_MONTH, 1); runDate.set(Calendar.HOUR_OF_DAY, 4); runDate.set(Calendar.MINUTE, 0); runDate.add(Calendar.MONTH, 1);//set to next month MyTask myTask = new MyTask(); Timer myTimer = new Timer(); myTimer.schedule(myTask, runDate.getTime()); timersTable = new HashTable();//keeping a reference to the timer so we timersTable.put("1", myTimer);//have the option to cancel it later } } The problem I think I'm going to run into is that because the first TimerTask creates the second Timer, will the first Timer be kept around because it created the second? After the code finishes on the first Timer, will that thread and object be taken care of by garbage collection? Over time I don't want to build up a bunch of Threads that aren't doing anything but aren't being removed. Maybe I don't have a proper understanding of how Threads and Timers work... I'm open to suggestions of other ways to create a monthly timer as long as I don't have to use third party JARs. Thanks! A: I would suggest simply using Quartz and scheduling jobs via a CronTrigger which will allow you to specify you want the job executed on the first day-of-the-month, and let Quartz handle the timing logic. Here is a further code example of how to use CronTrigger. Quartz is a dead-simple easy library to use. A: If what worries you is to create unneeded objects you can alway create an object which in turn creates/"destroy" all the references, so the objects created may be gc'ed. In the worst case, you'll have 12 unneeded objects in a year, which, I think is bearable. Still your concern is valid. Here's my attempt following Joel's suggestion of schedule at the end of the execution. Notice, the current Timer is replaced by a new one, so, both, the timer and the timer task could be gc'ed. package monthly.schedule; import java.util.Timer; import java.util.TimerTask; import java.util.Date; import java.util.Calendar; public class MonthlyTimer { // What to do private final Runnable whatToDo; // when private final int dayOfMonth; private final int hourOfDay; // The current timer private Timer current = new Timer();//to avoid NPE public void cancelCurrent() { current.cancel();// cancel this execution; current.purge(); // removes the timertask so it can be gc'ed } // create a new instance public static MonthlyTimer schedule( Runnable runnable, int dayOfMonth, int hourOfDay ) { return new MonthlyTimer( runnable, dayOfMonth, hourOfDay ); } private MonthlyTimer(Runnable runnable, int day, int hour ) { this.whatToDo = runnable; this.dayOfMonth = day; this.hourOfDay = hour; schedule(); } // Schedules the task for execution on next month. private void schedule() { // Do you mean like this? cancelCurrent(); current = new Timer(); // assigning a new instance // will allow the previous Timer to be gc'ed current.schedule( new TimerTask() { public void run() { try { whatToDo.run(); } finally { schedule();// schedule for the next month } } } , nextDate() ); } // Do the next date stuff private Date nextDate() { Calendar runDate = Calendar.getInstance(); runDate.set(Calendar.DAY_OF_MONTH, dayOfMonth); runDate.set(Calendar.HOUR_OF_DAY, hourOfDay); runDate.set(Calendar.MINUTE, 0); runDate.add(Calendar.MONTH, 1);//set to next month return runDate.getTime(); } } class UseIt { public static void main( String [] args ) { int the1st = 1; int at16hrs = 16; MonthlyTimer t = MonthlyTimer.schedule( new Runnable() { public void run() { System.out.println( "Hola" ); }}, the1st, at16hrs ); // will print "Hola" every 1st at 16:00 hrs. // if needed you can cancel with: t.cancelCurrent(); } } A: What about just using a scheduled timer, and as you complete the currently scheduled task schedule the next: ScheduledExecutorService es = Executors.newSingleThreadScheduledExecutor(); es.schedule(new MyTask(), numberOfDaysRemaining(), TimeUnit.DAYS); class MyTask implements Runnable { public void run() { try { // do it } finally { es.schedule(new MyTask(), numberOfDaysRemaining(), TimeUnit.DAYS); } } } You can use JodaTime to do the date calculations more easily. A: the simplest solution might be to use cron or equivalent to schedule a stand-alone program execution... A: The Quartz scheduler library allows you to schedule based on cron job expressions. A: I think you could also create one single thread and read from DelayQueue to do this. But it's not as easy as ScheduledExecutorService. A: Why do you need to recreate Timer every time? Timer is just thread with glue code around. Cancelling it cause terminating of other tasks running on that Timer. It is better to use the following: MonthlyTimer extends Timer { public void execute(TimerTask task, Date date, int dayOfMonth) { this.schedule(new TimerTaskWithCallback(task, dayOfMonth, this), date); } void taskCallback(TimerTaskWithCallback task) { this.schedule(new TimerTaskWithCallback(task.getImpl()), nextDate(task.getDayOfMonth())); //next date could be used from Oscar's post. } } TimerTaskWithCallback just executes MonthlyTimer.taskCallback after original task execution. Could have "try { } catch {} finally {}" glue code.
doc_23535031
REACT CODE: form- <form onSubmit={handleSubmit}> <label>Name:</label> <input type="text" required value={name} onChange={handleNameChange} name="name" placeholder="name"/> <label>Password:</label> <input type="password" required value={password} onChange={handlePasswordChange} name="password" placeholder="password"/> <input type="submit" value="Create Account"/> </form> methods - const [name, setName] = useState("") const [password, setPassword] = useState("") const handleNameChange = (e) => { setName(e.target.value); } const handlePasswordChange = (e) => { setPassword(e.target.value); } const handleSubmit = (e) => { e.preventDefault(); const data = {name, password} fetch("http://localhost:3000/users", { method: 'POST', body: JSON.stringify(data), headers: { Content_Type: "application/json", } }) RAILS CODE: users controller- def create user = User.create(user_params) if user.valid? payload = {user_id: user.id} token = encode_token(payload) render json: { user: user, jwt: token } else render json: { error: 'failed to create user' }, status: :not_acceptable end end private def user_params params.permit(:name, :password) end error - backend error A: It looks like user.valid? returns false, so your else statement kicks in: render json: { error: 'failed to create user' }, status: :not_acceptable The status: :not_acceptable generates the 406 error. You should probably include the reason why user is not valid, and return a bad request response instead: render json: { error: user.errors.full_messages}, status: :bad_request
doc_23535032
I've tried like this class Test : TestBase { [NameAttribute("Name of the Person")] public string PersonName { get; set; } private DateTime Birthday { get; set; } [NameAttribute("Birthday of the Person")] public string PersonBDay { get { return this.bDay.ToShortDateString(); } } } ... [AttributeUsage(AttributeTargets.Property)] public class NameAttribute : Attribute { public string Name { get; private set; } public NameAttribute(string name) { this.Name = name; } } Is there a possibility to look in my object for all properties which has the attribute NameAttribute and get the string form the Name property of NameAttribute? A: You can inspect each property from Type.GetProperties and then filter the ones that have the required attribute with the MemberInfo.GetCustomAttributes method. With a little bit of LINQ, this would look like: var propNameTuples = from property in typeof(Test).GetProperties() let nameAttribute = (NameAttribute)property.GetCustomAttributes (typeof(NameAttribute), false).SingleOrDefault() where nameAttribute != null select new { Property = property, nameAttribute.Name }; foreach (var propNameTuple in propNameTuples) { Console.WriteLine("Property: {0} Name: {1}", propNameTuple.Property.Name, propNameTuple.Name); } By the way, I also recommend declaring the attribute to be single-use only with AllowMultiple = false in the AttributeUsage decoration.
doc_23535033
the variable model.inverter_power should be in the i-th iteration bigger than model.inverter_power[i].lb + model.fcr_power[i] but also smaller than model.inverter_power[i].ub - model.fcr_power[i]) How can i implement this? Unfortuntately my idea is not working.... def fcr_inverter_reduction(model, i): return (model.inverter_power[i] >= model.inverter_power[i].lb + model.fcr_power[i], model.inverter_power[i] <= model.inverter_power[i].ub - model.fcr_power[i]) model.fcr_inverter_rule = pyo.Constraint(model.i, rule = fcr_inverter_reduction) I tried various versions of this code, not only is this code not linear anymore, so I used ipopt as a solver but no solution can be found, i got this error message: File "D:\.conda\envs\PythonEnviromentV2\lib\site-packages\pyomo\opt\base\solvers.py", line 596, in solve raise ApplicationError( pyomo.common.errors.ApplicationError: Solver (ipopt) did not exit normally A: This is very doable if you reformulate just a bit. Also, I don't think it is possible to return a tuple of 2 constraints like you are doing with that function, so you should break it up... it is clearer as well. You probably could access the upper/lower bound and use that within the constraint because they are fixed/constant with respect to the solver, but I think it is probably clearer to break out your min/max values as parameters. Some variation of this works. (also, in the future, you are more likely to get better help/results if you post a fully minimal-reproducible example instead of just 1-line.) Code: import pyomo.environ as pyo model = pyo.ConcreteModel() model.I = pyo.Set(initialize=[1,2,3]) # power parameters... model.min_inverter = pyo.Param(model.I, initialize={1:10, 2:15, 3:22}) model.max_inverter = pyo.Param(model.I, initialize={1:55, 2:45, 3:80}) # vars... model.inverter_power = pyo.Var(model.I) model.fcr_power = pyo.Var(model.I) def fcr_inverter_min(model, i): return model.inverter_power[i] >= model.min_inverter[i] + model.fcr_power[i] model.fcr_inverter_rule_min = pyo.Constraint(model.I, rule=fcr_inverter_min) def fcr_inverter_max(model, i): return model.inverter_power[i] <= model.max_inverter[i] - model.fcr_power[i] model.fcr_inverter_rule_max = pyo.Constraint(model.I, rule=fcr_inverter_max) model.pprint() Output: 1 Set Declarations I : Size=1, Index=None, Ordered=Insertion Key : Dimen : Domain : Size : Members None : 1 : Any : 3 : {1, 2, 3} 2 Param Declarations max_inverter : Size=3, Index=I, Domain=Any, Default=None, Mutable=False Key : Value 1 : 55 2 : 45 3 : 80 min_inverter : Size=3, Index=I, Domain=Any, Default=None, Mutable=False Key : Value 1 : 10 2 : 15 3 : 22 2 Var Declarations fcr_power : Size=3, Index=I Key : Lower : Value : Upper : Fixed : Stale : Domain 1 : None : None : None : False : True : Reals 2 : None : None : None : False : True : Reals 3 : None : None : None : False : True : Reals inverter_power : Size=3, Index=I Key : Lower : Value : Upper : Fixed : Stale : Domain 1 : None : None : None : False : True : Reals 2 : None : None : None : False : True : Reals 3 : None : None : None : False : True : Reals 2 Constraint Declarations fcr_inverter_rule_max : Size=3, Index=I, Active=True Key : Lower : Body : Upper : Active 1 : -Inf : inverter_power[1] - (55 - fcr_power[1]) : 0.0 : True 2 : -Inf : inverter_power[2] - (45 - fcr_power[2]) : 0.0 : True 3 : -Inf : inverter_power[3] - (80 - fcr_power[3]) : 0.0 : True fcr_inverter_rule_min : Size=3, Index=I, Active=True Key : Lower : Body : Upper : Active 1 : -Inf : 10 + fcr_power[1] - inverter_power[1] : 0.0 : True 2 : -Inf : 15 + fcr_power[2] - inverter_power[2] : 0.0 : True 3 : -Inf : 22 + fcr_power[3] - inverter_power[3] : 0.0 : True
doc_23535034
Eg: CheckBoxList chkIrList = new CheckBoxList(); chkIrList.DataValueField = "UserId"; chkIrList.DataTextField = "Name"; chkIrList.DataSource = DT; chkIrList.DataBind(); The generated html does not holds the value field: <input id="ctl26_0" type="checkbox" name="ctl26$0"> <label for="ctl26_0">XYZ</label> A: For now I have inserted a checkboxlist control in the page and then added listitem data to that checkboxlist from code behind. Now the value property is available.
doc_23535035
I kill them by first running thisProcess.kill(leinProcess.pid); (defaults to SIGTERM), waiting 1 second and then calling leinProcess.kill("SIGKILL");. All the processes and the main process are run under the same user. Running killall -9 java from command line works. A: The problem was with orphaned java sub-sub-processes. See this readme for an explanation and solution: https://github.com/indexzero/ps-tree A: I've been doing the same thing, launching multiple instances of lein run on different microservices. In order to kill them, I've been using npm install tree-kill Basic Example var kill = require('tree-kill'); var spawn = require('child_process').spawn; var proc = spawn("lein", ["run"], {cwd: './some-dir', detached: true}); setTimeout(function(){kill(proc.pid); console.log('Take that!');}, 5000); More Real-World Example var kill = require('tree-kill'); var chalk = require('chalk'); exports.killIfAlive= function(pid) { try { kill(pid); } catch(ex) { console.error(ex); } }; exports.kill = function(projects) { var pids = exports.readPIDFile(); projects.forEach(function(project) { if (pids[project]) { console.log('Killing', chalk.cyan(project), chalk.magenta('(pid:', pids[project], ')')); exports.killIfAlive(pids[project]); } else { console.log(chalk.cyan(project), chalk.grey('is not running.')); } delete pids[project]; }); return exports.writePIDFile(pids); }; After starting each project, I store its pid into a simple object like {project1: 12352, project2: 50943} and then write that to the file system. Since I run spawn('lein' ... etc) with the detached option, my current node process can die without taking out my leiningen processes. Whenever I revive my node process, it can use the pid file to look up and terminate one or more projects. When taking this approach, there is the chance for a race condition such that your lein process with the given pid has already died and a new process has started under that pid which I'll leave for someone else to handle.
doc_23535036
and hopefully, it could be presented something like this. it's a bit complicated (at least for me) than the other sample I found and tried ...
doc_23535037
The following error originated from your application code, not from Cypress. ev.element is not a function This is happening on a line of code where it is simply clicking an element cy.get('#report_submit').click()
doc_23535038
integrand = @(x1,x2) mvnpdf([x1,x2],[0,0],[1,0;0,1]); integral2(integrand,-10,10,-10,10) but receive the error X and MU must have the same number of columns. I know I need to specify the integrand function to perform element-wise operations but my attempts have been futile. Any help would be appreciated... A: Try the following: integrand = @(x1, x2) reshape(mvnpdf([x1(:), x2(:)],[0,0],[1,0;0,1]), size(x1)); Matlab documentation of integral2 states that: All input functions must accept arrays as input and operate elementwise. The function Z = FUN(X,Y) must accept arrays X and Y of the same size and return an array of corresponding values. For example for the case above, integral2 passes two 14 by 14 matrices to integrand. The x(:) makes a one-dimensional vector out of the matrix passed by integral2. This is needed in order to provide mvnpdf with two column vectors as it is expected in this case. mvnpdf then returns a column vector of density values which must be reshaped (using reshape) to make the dimensions the way integral2 is expecting them to be.
doc_23535039
I know (correct me if I'm wrong) override's sole purpose is to be able to have polymorphic behavior, so that run-time can resolve a method depending on the actual type of an instance - as opposed to the declared type. Consider the following code: type TBase = class procedure Proc1; virtual; procedure Proc2; virtual; end; TChild = class(TBase) procedure Proc1; override; procedure Proc2; // <- [DCC Warning] end; procedure TBase.Proc1; begin Writeln('Base.Proc1'); end; procedure TBase.Proc2; begin Writeln('Base.Proc2'); end; procedure TChild.Proc1; begin inherited Proc1; Writeln('Child.Proc1'); end; procedure TChild.Proc2; begin inherited Proc2; Writeln('Child.Proc2'); end; var Base: TBase; begin Base := TChild.Create; Base.Proc1; Writeln; Base.Proc2; Base.Free; Readln; end. Which outputs: Base.Proc1Child.Proc1Base.Proc2 The warning on TChild.Proc2 states that this method "will hide access to the base's method of the same name". What I see is, if I don't override Proc2 I loose the ability of the method's resolving to its actual type, not of its base type. How's that hiding access to base's method? Further, down the documentation on the warning as a solution to the warning, it is stated that: First, you could specify override to make the derived class' procedure also virtual, and thus allowing inherited calls to still reference the original procedure. Now, if I create a 'TChild' instance from a 'TChild' (no polymorphism), the inherited call in the non-overridden method clearly refers to the original procedure. If I create the 'Child' instance from a 'TBase', the call does not even resolve to a 'TChild' method, how could I call 'Inherited' that would refer to anything at all? What am I misunderstanding? A: Amongs other thing, you won't be able to define TGrandChild = class(TChild) procedure Proc2; override; end; because Proc2 that TGrandChild sees is the one from TChild that is not virtual. The TChild.Proc2 hide TBase.Proc2 from descendants. EDIT: In answer to Sertac's comment: var Base: TBase; Child : TChild begin Child := TChild.Create; Base := Child; Base.Proc2; Child.Proc2; Base.Free; Readln; That will output Base.Proc2 Base.Proc2 Child.Proc2 So, what seems to be a call to the same method twice is actually a call to 2 different methods. That makes code harder to understand (which is not practical) and yield unexpected behavior. A: You are thinking too complicated. Hiding doesn't mean you completely lose access to the original. It simply means (and you already noted this yourself) if you have an object of static type TChild, and you call Proc2 on it, it calls the one in TChild, and not the one in TBase. Also what Ken said is true. It is warning you because the original is virtual and hiding is most likely not what people intend when writing code like that. At the very least it's bad coding style. A: Use 'reintroduce' to suppress the warning.
doc_23535040
My Show Action in the ShopProfilesController looks like this: def show @comments = @shop_profile.comments @comment = @shop_profile.comments.new end And I am rendering the comment form and comments in the show view with: <% if user_signed_in? %> <%= render 'comments/form' %> <% end %> <%= render @comments %> My Create action on my comment controller is: def create @comment = @user.comments.build(comment_params) @commentable = Comment.find_commentable(params[:comment][:commentable_type], params[:comment][:commentable_id]) if @comment.save redirect_to @commentable end end and my _comment partial is: <p> <strong>Title:</strong> <%= comment.title %> </p> <p> <strong>Comment:</strong> <%= comment.comment %> </p> <p> <small>By:</small> <%= comment.user.username %> </p> The new @comment for the form keeps getting included in the @comments and is thus causing an error "undefined method `username' for nil:NilClass" because the new @commentn has no user_id. How can I display my @comments without including this new @comment for the form_for? Thanks for any help A: You're creating an additional comment in your collection, and that new comment doesn't have an associated user yet, and isn't saved in the database yet. If you want the new comment to be skipped entirely, you can do this: <%= render @comments.reject{|c| c == @comment } %> If you want the new comment to show up, but skip the "By" section, you can do this: <% if comment != @comment %> <p> <small>By:</small> <%= comment.user.username %> </p> <% end %> A: Unfortunately (in this case) new/build adds the built object to the association's collection. So you'll need to declare your intent that you only want items stored in the database for the @comments collection. You have two options I know of off the top of my head: def show @comment = @shop_profile.comments.new @comments = @shop_profile.comments(true) end This forces the @comments to be loaded cleanly, so it will only contain the original list. Unfortunately you're hitting the database twice for the same list, that's silly. Even better, I think, for this would be to do: def show @comments = @shop_profile.comments.to_a @comment = @shop_profile.comments.new end So now you detatch the @comments collection from the active record association by making it an array, so the new call later on won't modify anything you still are holding on to.
doc_23535041
Step 22/42 : RUN JDEPS="$(jdeps --multi-release base --print-module-deps --ignore-missing-deps ${FUSEKI_JAR})" && jlink --compress 2 --strip-debug --no-header-files --no-man-pages --output "${JAVA_MINIMAL}" --add-modules "${JDEPS},${JDEPS_EXTRA}" which is Error: java.io.IOException: Cannot run program "objcopy": error=0, Failed to exec spawn helper: pid: 64, exit value: 1 1 error occurred: * Status: The command '/bin/sh -c JDEPS="$(jdeps --multi-release base --print-module-deps --ignore-missing-deps ${FUSEKI_JAR})" && jlink --compress 2 --strip-debug --no-header-files --no-man-pages --output "${JAVA_MINIMAL}" --add-modules "${JDEPS},${JDEPS_EXTRA}"' returned a non-zero code: 1, Code: 1 If I add the following command platform: linux/amd64 also to the docker compose file, this step runs infinitely. Can anyone help me?
doc_23535042
This is one of my methods: public static void IncrementInvalidLoginColumn(string login) { User user; using (DTContext context = new DTContext()) { try { user = context.Users.Where(u => u.Login.CompareTo(login) == 0).FirstOrDefault(); if (user.InvalidLogins < 3) { user.InvalidLogins = user.InvalidLogins + 1; } context.SaveChanges(); } catch { } } } Maybe someone will have idea what should i do. A: It depends on what you mean by "unit" test. If you don't want your test to hit the database then your method is not testable (or at least not without some refactoring). If hitting the database is acceptable (which would actually be an integration test) then you can definitely test your method. Here are some steps: 1. Arrange the initial data. You use an instance of the DTContext directly in the test to put the system in a predefined state (basically you write some user records in the database) * *You run the method you want to test (which in fact uses its own instance of the DTContext) *You use DTContext again to read the user information directly from the database and assert that the InvalidLogins property has incremented. *You need to make sure you delete any data that you put in manually. This is the gist of DI: public class Example { private IDatabaseGateway myDatabase; public Example(IDatabaseGateway myDb) { myDatabase = myDb; } public void DoStuff() { ... myDatabase.GetData(); ... } } You give your business class an abstraction of the database via the constructor, that is you inject your dependencies in the class that needs them. Once you have this in place, in production code you pass in the constructor a concrete instance of IDatabaseGateway that goes to the actual database. In the case of a unit test you pass it a mock instance of the same interface. The mock is a special object that you can setup/configure to return what you want. Various libraries exist for mocking (an easy one is Moq). However without modifying your code too much, it is better to stick with integration testing that hits the database. It will give you a simple and valid test. Especially since there are some pitfalls in mocking the DbContext in EF (ex. some queries may not work when you will use them in production, testing updates in EF with mocks is a bit trickier). A: Ok so i read all of your posts and they was very helpful. I use MOQ framework and this is example how i do it. This is how Liviu M. told me to do for example: public class CRUDclass { private DTContext _context; public CRUDclass(DTContext myObj) { _context = myObj; } } We have CRUD Class which are doing operations directly on our database. We have constructor with one argument and private field. This our context :) This is (for example) my method in CRUDclass: public bool AddUser(User user) { try { _context.Users.Add(user); _context.SaveChanges(); return true; } catch { return false; } } Ovecourse he have our DTContext class witch DBSet becouse i using entity framework. And after that i am able to write some test method: [TestMethod] public void Should_Add_User() { var mockSet = new Mock<DbSet<User>>(); var mockContext = new Mock<DTContext>(); mockContext.Setup(m => m.Users).Returns(mockSet.Object); var usrCRUD = new UserCRUD(mockContext.Object); var usr = new User(); usr.Login = "Login_Name"; usr.Email = "loginName@test.com"; usr.Password = "***"; usr.InvalidLogins = 0; usr.RememberID = 0; usrCRUD.AddUser(usr); mockSet.Verify(m => m.Add(It.Is<User>(arg => arg.Login == "Login_Name"))); mockContext.Verify(m => m.SaveChanges(), Times.Once()); } At first a have to set my fake object (Mock>). This test method checks if our user was added to Mock :) I hope it can help somebody, if anything will be unclear please write a question :) A: The idea of unit tests is to test your ifs, switches, etc., not the database operations. In your case you need an interface that is an abstration of DTContext. In the simplest case it might look as the following. public interface IObjectContext : IDisposable { IEnumerable<User> Users { get; } } In more complicated cases you may need to use IQueryable<T> or IObjectSet<T> instead of IEnumerable<T>. Add a partial class declaration of DTContext and make it implement IObjectContext. Add a constructor to the class that contains the method IncrementInvalidLoginColumn with a parameter of type IObjectContext. Now you can inject any instance of IObjectContext instead of creating it in your class. This instance can be a DTContext or a mock for testing. Your class is ready to be tested without connection to a real database. NB. In case of instances of IDisposable it's better to inject a Func<IObjectContext> instead of IObjectContext. Then you can create an instance for each operation and dispose it immediately after. A: If there are CRUD operations in your code then I will recommend to use MOQ framework for unit testing. Below links are quite helpful: Quick Start Code Project A: Ideally you would inject your DTContext rather than creating a new one every time that the method is called. That way you could mock that object in your unit test and verify that it is called as expected. Your constructor would look something like: private readonly IDTContext _context; public CrudClass(IDTContext context) { _context = context } With your method now looking like public static void IncrementInvalidLoginColumn(string login) { User user; try { user = _context.Users.Where(u => u.Login.CompareTo(login) == 0).FirstOrDefault(); if (user.InvalidLogins < 3) { user.InvalidLogins = user.InvalidLogins + 1; } _context.SaveChanges(); } catch { // Handle errors } } And then in your test, if you were using a framework like Moq, you would basically script how that object would behave and test against that. For instance, setting up the mocked IDTContext to always return the same user for your Users collection and SaveChanges() method will write the number of invalid logins to a variable that you could then test against.
doc_23535043
- (UIColor *) getPixelColorAtLocation:(CGPoint)point { UIColor* color = nil; @try{ { CGImageRef inImage = drawImage.image.CGImage; // Create off screen bitmap context to draw the image into. Format ARGB is 4 bytes for each pixel: Alpa, Red, Green, Blue CGContextRef cgctx = [self createARGBBitmapContextFromImage:inImage]; if (cgctx == NULL) { return nil; /* error */ } size_t w = CGImageGetWidth(inImage); size_t h = CGImageGetHeight(inImage); CGRect rect = {{0,0},{w,h}}; // Draw the image to the bitmap context. Once we draw, the memory // allocated for the context for rendering will then contain the // raw image data in the specified color space. CGContextDrawImage (cgctx, rect, inImage); // Now we can get a pointer to the image data associated with the bitmap // context. unsigned char *data = {0}; data=(unsigned char*) calloc(CGImageGetHeight(inImage) * CGImageGetWidth(inImage) , CGBitmapContextGetHeight(cgctx)*CGBitmapContextGetWidth(cgctx)); data= CGBitmapContextGetData (cgctx); if( data !=NULL ) { //offset locates the pixel in the data from x,y. //4 for 4 bytes of data per pixel, w is width of one row of data. int offset = 4*((w*round(point.y))+round(point.x)); // NSLog(@"%s111111",data); int alpha = data[offset]; /////// EXC_BAD_ACCESS(CODE=1,address=0x41f6864) int red = data[offset+1]; int green = data[offset+2]; int blue = data[offset+3]; //NSLog(@"offset: %i colors: RGB A %i %i %i %i",offset,red,green,blue,alpha); color = [UIColor colorWithRed:(red/255.0f) green:(green/255.0f) blue:(blue/255.0f) alpha:(alpha/255.0f)]; } // When finished, release the context //CGImageRelease(*data); CGContextRelease(cgctx); // Free image data memory for the context if (data) { free(data); } } @catch (NSException *exception) { } return color; } A: The memory management in your code appears to be wrong: Declare data and pointlessly assign a value to it: unsigned char *data = {0}; Allocate a memory block and store a reference to it in data - overwriting the pointless initialisation: data = (unsigned char *)calloc(CGImageGetHeight(inImage) * CGImageGetWidth(inImage), CGBitmapContextGetHeight(cgctx) * CGBitmapContextGetWidth(cgctx)); Now get a reference to a different memory block and store it in data, throwing away the reference to the calloc'ed block: data = CGBitmapContextGetData (cgctx); Do some other stuff and then free the block you did not calloc: free(data); If you are allocating your own memory buffer you should pass it to CGBitmapContextCreate, however provided you are using iOS 4+ there is no need to allocate your own buffer. As to the memory access error, you are doing no checks on the value of point and your calculation would appear to be producing a value of offset which is incorrect. Add checks on the values of point and offset and take appropriate action if they are out of bounds (you will have to decide what that should be). HTH A: The problem may cause by the point is out of image rect,so you can use try{ int offset = 4*((w*round(point.y))+round(point.x)); int alpha = data[offset]; int red = data[offset+1]; int green = data[offset+2]; int blue = data[offset+3]; color = [UIColor colorWithRed:(red/255.0f) green:(green/255.0f) blue:(blue/255.0f) alpha:(alpha/255.0f)]; }catch(NSException e){ } to avoid the EXC_BAD_ACCESS
doc_23535044
URI could not be determined Here is my code: WebProxy proxy = new WebProxy(); proxy.Address = new Uri("myproxyaddress"); proxy.UseDefaultCredentials = true; proxy.BypassProxyOnLocal = false; WebClient client = new WebClient(); client.Proxy = proxy; string doc = client.DownloadString("http://www.google.com/"); A: This error happens when you try creating a URI and the constructor can't determine what format to parse the URI as (Relative or Absolute). Normally, if you are specifying a full valid URL you won't have this issue. If for some reason you can specify the kind of URI you are trying to create (UriKind.Absolute or UriKind.Relative) For your purposes, you will need an absolute URI, which can be created like this: var url = new Uri("myproxyaddress", UriKind.Absolute); proxy.Address = url; Odds are that you might get an error calling new Uri("myproxyaddress", UriKind.Absolute) because the underlying issue is that "myproxyaddress" isn't a valid absolute URI.
doc_23535045
SECONDEXPANSION: /tmp/foo.o: %.o: $$(addsuffix /%.c,foo bar) foo.h @echo $^ My question was if a target has an empty list and no explicit rule then the next line following a pattern rule, like in this case "the target foo.o : has no dependency list and no explicit rule " then the make will automatically goes for %.o: rule or it ignores. This is what I want to know please explain?
doc_23535046
Therefore, I wrote myself a few regex matches (which work just fine, they are not the focus of this question). However, I have a rather large number of different test files, and I already at this point - just having started - have 6 different match/replacement-pairs that I would like to apply. Now obviously, being a computer scientist, I would love to automate this, instead of going through every file, pressing Ctrl+F, pasting the matching regex, pasting the replacement regex, pressing the replace button, repeating this cycle 5 more time, and then moving to the next file. So, let's say for the sake of simplicity, that these are my regexes: //matches the existing framework OldClass (.*?) = new OldClass("string"); //replacement regex: NewClass $1 = new NewClass("string"); //example replacement: OldClass foo = new OldClass("string"); //becomes: NewClass foo = new NewClass("string"); So, If I want to replace several of these match/replace-pairs in lots of different files - can I use any built-in eclipse function, or is there an extension that provides this functionality? Note that I'm aware that I could write a simply java program that just skims through all my source code and applies the regexes as desired. I'd much rather avoid spending that time, though, and especially would also like to get a chance to apply them individually to each file, so I can re-run the tests afterwards and make sure nothing is broken - which will happen, as not all of the old framework code can be replaced automatically, due to too complex & specific cases. Since I'm also removing the old imports, though, this will break any still existing non-replaced code relying on now-no-longer-existing imports. A: Eclipse should have a simple file search option with a "Replace.." button at the bottom. You can search as you would normally specifying the file endings that you'd like to search (probably in this case you'd want *.java). The replace button lets you replace each search result with a replacement using regular expressions. Granted, this will change your source one replace at a time and that is awkward I know, but my recommendation is to perform small steps, minimizing time in which your code is broken. For instance if you move your class to a new location with a new name, just focus on renaming the class first (verifying that the code then works afterwards), and only then focus on changing its package. Word to the wise, click Preview first! Alternatively, consider using ctrl+shift+R to rename methods/variables/classes. Assuming the code is under a source folder, it will automatically rename everywhere it is used. Generally it is preferable to using regular expressions. But again, you can't perform multiple changes at the same time. Though this is probably for the best. Just make a backup of the project and organize the changes that need to be made before starting. Good luck!
doc_23535047
Script and Css: <link href="@Url.Content("~/Content/jquery-ui-1.8.18.custom.css")" rel="stylesheet"type="text/css" /> <script src="@Url.Content("~/Scripts/jquery-ui-1.8.18.custom.min.js")" type="text/javascript"></script> Input text: @Html.TextBoxFor(model => model.Filter.HouseName, new { style = "width: 205px", onKeyUp = "updateHouseNames()" }) Javascript: function updateHouseNames() { var houseArray = new Array(); $.post('@Url.Action("LoadHouses")', { houseName: $("#Filter_HouseName").val() }, function(houses) { houseArray = houses; }); $("#Filter_HouseName").autocomplete({ source: houseArray }); } Controller method: [HttpPost] public JsonResult LoadHouses(string houseName) { var houses = this.HouseService.SelectByName(houseName).Select(e => new String(e.Name.ToCharArray())).ToArray(); return Json(houses); } I debug the javascript and the houses are selected.. but the results are not displayed in autocomplete. Why? A: I don't really think you should be doing it this way. If you need to customize the logic then use a callback on the autocomplete method: $(function () { $('#Filter_HouseName').autocomplete({ minLength: 1, source: function (request, response) { var term = request.term; var houseArray = new Array(); $.post('@Url.Action("LoadHouses")', { houseName: term }, function(houses) { houseArray = houses; response(houseArray); }); } }); });
doc_23535048
Additionally, one thing I noticed is the dates that google search console found these errors seem to coincide with when I installed an ssl certificate on my site. I am not entirely sure if there is a possible correlation. A: I too keep getting these errors from time to time especially when I change the theme or plugin. The simplest way to get rid of these errors is to mark them as "fixed" and wait for the next crawl. They usually become zero on the next crawl, but anytime if I make changes in my theme or plugins, they again start appearing. So I guess it is related to the deletion or installation of themes and plugins.
doc_23535049
CGImageRef imageRef = CGImageCreate(serverInit.rfbWidth,serverInit.rfbHeight,bitsPerComponent,bitsPerPixel,bytesPerRow,colorSpaceRef,bitmapInfo,provider,NULL,NO,renderingIntent); screenImage = [UIImage imageWithCGImage:imageRef]; CFRelease(imageRef); [view performSelector:@selector(replaceImage:) onThread:[NSThread mainThread] withObject:screenImage waitUntilDone:NO]; A: Try use this, it prevent screenImage to be released CGImageRef imageRef = CGImageCreate(serverInit.rfbWidth,serverInit.rfbHeight,bitsPerComponent,bitsPerPixel,bytesPerRow,colorSpaceRef,bitmapInfo,provider,NULL,NO,renderingIntent); screenImage = [UIImage imageWithCGImage:imageRef]; CFRelease(imageRef); dispatch_sync(dispatch_get_main_queue(), ^{ [view replaceImage:screenImage]; });
doc_23535050
I have no problem with the first one, but I have with the last one. I think is the image, I wrote: <tabBarItem key="tabBarItem" title="Stations" image="ico_paradas.png" id="J2M-ix-HLu"/> It works, this is the first one. the last one: <tabBarItem key="tabBarItem" title="Info" image="ico_info.png" id="hnR-0m-dE0"/> it made a mistake: Command /Applications/Xcode.app/Contents/Developer/usr/bin/ibtool failed with exit code 255 But if I change the image value for another one, it works. I also check the image, and add it to another tab, with mainStoryBoard in graphic mode, and it works, it just doesn't work when I add it from source code, I cant add it whith the graphic mode because is a TAB BAR CONTROLLER into a TAB BAR CONTROLLER. Thank you in advance A: Subclass your tab bar controller and set its title and image programmatically. Using storyboard source code is pretty much never a good idea.
doc_23535051
float px,py,vx,vy,ax,ay; boolean canJump = false; void setup(){ size(600, 400); ax = 0; ay = .32; vx = 0; vy = 0; px = 300; py = 200; } int x = 50; int y = 520; void draw(){ background(0); ellipse(px-15, py-30, 60, 60); vx+=ax; vy+=ay; px+=vx; py+=vy; if( py > height ){ py = height; vy = 0; canJump = true; } player(); } void player(){ fill(255); rect(0, 550, 1000, 50); } void keyPressed(){ if(keyCode == RIGHT || key == 'd'){ px += 10; } if(keyCode == LEFT || key == 'a'){ px -= 10; } if(keyCode == UP){ if(canJump) { vy = -10; canJump = false; } } } A: So you can make your ball go both up and right or up and left by checking that both keys are pressed and then you can add to the velocity instead of the position to affect the trajectory of the ball. However, then you must slow down the x component of the velocity when it hits the ground, so I added a friction variable. float px, py, vx, vy, ax, ay; boolean canJump = false; float bounce = 0.2; float friction = 0.2; void setup() { size(600, 400); ax = 0; ay = .32; vx = 0; vy = 0; px = 300; py = 200; } int x = 50; int y = 520; void draw() { background(0); ellipse(px-15, py-30, 60, 60); vx+=ax; vy+=ay; px+=vx; py+=vy; if ( py > height ) { py = height; vy = -bounce*vy; vx = friction*vx; canJump = true; } } void keyPressed() { if (keyCode == RIGHT && keyCode == UP) { if (canJump) { vy = -10; vx += 5; canJump = false; } } else if (keyCode == LEFT && keyCode == UP) { if (canJump) { vy = -10; vx += -5; canJump = false; } } else { if (keyCode == RIGHT || key == 'd') { vx += 5; } if (keyCode == LEFT || key == 'a') { vx -= 5; } if (keyCode == UP) { if (canJump) { vy = -10; canJump = false; } } } } You can improve the implementation of your program by taking a look at processing's PVector class. PVector pos; PVector vel; PVector acc; float friction = 0.3; float bounce = 0.5; float diameter = 60; boolean canJump = false; void setup() { size(600, 400); pos = new PVector(300, 200); vel = new PVector(0, 1); acc = new PVector(0, 0.32); } void draw() { background(0); circle(pos.x, pos.y, diameter); vel.add(acc); pos.add(vel); if (pos.y + diameter/2 > height) { pos.set(pos.x, height-diameter/2); vel.set(vel.x*friction, -vel.y*bounce); canJump = true; } } void keyPressed() { boolean right = keyCode == RIGHT || key == 'd'; boolean left = keyCode == LEFT || key == 'a'; boolean up = keyCode == UP || key == 'w'; if (up && right && canJump) { vel.add(5, -10); canJump = false; } else if (up && left && canJump) { vel.add(-5, -10); canJump = false; } else { if (up && canJump) { vel.add(0, -10); canJump = false; } if (right) { vel.add(5, 0); } if (left) { vel.add(-5, 0); } } }
doc_23535052
file {'/tmp/motd': source => '/tmp/motd', } On the agent, I issue: puppet agent -t which errors out as: Error: /Stage[main]/Main/File[/tmp/motd]: Could not evaluate: Could not retrieve information from environment production source(s) file:/tmp/motd The file motd exists on the puppet server in /tmp/ directory Any idea what might be going on here? If I replace source attribute with content => 'Testing 1 2 3', the puppet agent -t runs successfully creating a catalogue and I see the file motd on the client with the content Testing 1 2 3 A: As explained in the docs here, the source attribute refers to a local file, i.e. local on the Puppet Agent node. If you wish to source the file from the Puppet Server, it would be best to place the file content in the module's files directory as explained here.
doc_23535053
So this is what Facebook returns for the leadgen field: Array ( [entry] => Array ( [0] => Array ( [changes] => Array ( [0] => Array ( [field] => leadgen [value] => Array ( [ad_id] => 0 [form_id] => 1109138149146076 [leadgen_id] => 1109157429144148 [created_time] => 1467887375 [page_id] => 152161181508654 [adgroup_id] => 0 ) ) ) [id] => 152161181508654 [time] => 1467887376 ) ) [object] => page ) Is it possible to somehow get campaign ID from these values that Facebook returns? There is no clue to campaign in leadgen itself and in the form that I fetched with leadgen_id and form_id. I also tried to fetch all ad account campaigns with /v2.6/<ad_account_id>/campaigns endpoint and thought that I will see some connection there with form or leadgen, but nothing there as well. So, I need to fetch it so that I can group leadgen forms in Facebook. With current implementation, unfortunately it is not possible - I guess Facebook didn't thought of that :( A: Just in case someone will struggle with this as well: We can grab ad id info from: 'https://graph.facebook.com/v2.6/<AD_ID>?access_token=<ACCESS_TOKEN>&fields=campaign_id'; And this will return us campaign id. Reason why I didn't try this in first place, was because in initial response, Facebook returned ad_id as 0, but after some while I realised that this is probably because it was a test lead from https://developers.facebook.com/tools/lead-ads-testing
doc_23535054
node1 : application1 : client1,client2,client3 node2 : application1 : client3,client5,client9 node3 : application1 : client1,client7,client8 Thanks in advance. A: You can put this information inside the node configuration itself. So, inside nodes/node1-hostname.json you would have: { "application1": { "clients": ["client1", "client2", "client3"], }, "run_list": [ "recipe[webserver]", "recipe[your_recipe]" ] } Then inside nodes/node2-hostname.json and nodes/node3-hostname.json you would have their specific configuration.
doc_23535055
When building my project, I get a list of errors like this: error LNK2001: unresolved external symbol "__declspec(dllimport) void __cdecl UserTracking(void *)" (__imp_?UserTracking@@YAXPEAX@Z) error LNK2001: unresolved external symbol "public: bool __cdecl EACServer::Destroy(void)const " (?Destroy@EACServer@@QEBA_NXZ) error LNK2001: unresolved external symbol "public: bool __cdecl EACServer::Initialize(void)const " (?Initialize@EACServer@@QEBA_NXZ) ... All of the functions listed are from imported libraries. As an example, the EACServer::Initialize method is defined as so in EACServer.h: bool Initialize() const; In the code I am compiling, this function is used as so (the appropriate header files are imported in the .h file ofc): this->eacServer = EACServer(); this->eacServer.Initialize(); The class definition of EACServer is basic: class EACServer : IRoot { ... } I have been told that these errors are thrown because I am missing the macro which correctly sets the __declspec. How can I find/implement this macro? A: Turns out that although I added the paths to my libraries in the linker additional library directories, I had neglected to add the .lib files in the linker additional dependencies.
doc_23535056
const pathname = this.props.location.pathname; const lastPathPart = pathname.split('/').slice(-1)[0]; const requestedJobId = Number(lastPathPart); The code above gets the requested job id from the end of the route as needed/expected but is there a more proper or structured way to do this in React? A: 1. If it's a functional component, You can use react-router's useParams hook. Example: Let's assume this is your route. <Router> <Switch> <Route path="/:id" children={<User />} /> </Switch> </Router> Now you can use the useParams hook to extract the id inside the User component like this. import { useParams } from "react-router"; function User() { let { id } = useParams(); return <h2>User {id}</h2>; } 2. If it's a class component you can refer to this solution.
doc_23535057
controller.js angular.module('starter.controllers', []) .controller('MainCtrl', function($scope, $firebaseObject) { var ref = new Firebase("https://list-detail-001.firebaseio.com/"); var syncObject = $firebaseObject(ref); // synchronize the object with a three-way data binding // click on `index.html` above to see it used in the DOM! syncObject.$bindTo($scope, "users"); $scope.newUser={}; $scope.add=function(){ console.log($scope.newUser); console.log($scope.users); console.log(syncObject); $scope.users.$add($scope.newUser); $scope.newUser=''; } }) index.html: <body ng-app="starter"> <ion-pane> <ion-header-bar class="bar-positive"> <h2 class="title">Blank Starter</h2> </ion-header-bar> <ion-content> <div class="list"> <div class="item item-input-inset" ng-controller="MainCtrl"> <label class="item-input-wrapper"> <input type="text" placeholder="Name" ng-model="newUser.title"> </label> <button class="button button-small" ng-click="add()"> Add </button> </div> </div> </ion-content> </ion-pane> </body> My app.js is standard for ionic except I injected the firebase module: angular.module('starter', ['ionic','starter.controllers','firebase']) .run(function($ionicPlatform) { $ionicPlatform.ready(function() { // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard // for form inputs) if(window.cordova && window.cordova.plugins.Keyboard) { cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); } if(window.StatusBar) { StatusBar.styleDefault(); } }); }) I just want to be able to add one name at a time from my index.html to firebase. The firebase is currently empty. I want to use this app to be able to add in some dummy data. I just cannot seem to get it to work. $scope.users.$add or even $scope.users.push seems to be an undefined function. Please help! Thanks. A: According to Firebase documentation you should be using $firebaseArray in your case $firebaseObject. Is it possible that you're missing Firebase concept? Firebase object is not a collection. If you want to store data you do it on key/value basis. Arrays in Firebase is a sweetener for {0: val1, 1: val2 ....}. Read Firebase warnings about arrays before using them A: Fixed it with this: controller.js: angular.module('starter.controllers', []) .controller('MainCtrl', function($scope, $firebaseArray) { var ref = new Firebase("https://list-detail-001.firebaseio.com/users"); $scope.users = $firebaseArray(ref); $scope.add=function(){ $scope.users.$add({ text: $scope.newUser }); } }); only change I made to index.html was this line: <input type="text" placeholder="Name" ng-model="newUser">
doc_23535058
TARGET=fmake TARGET2=test_second f:f echo Some text clean: rm -f fmake test_second CC=$(VAR2) VAR2=gcc After make command I have: make: Circular f <- f dependency dropped. echo Some text Some text What does mean make: Circular f <- f dependency dropped. Is it true that f:f echo Some text just equivalent to f: echo Some text A: No, it's not true that f: f is the same as f:. The latter defines a target f which doesn't depend on any other files. The former defines a target f which depends on a file f (the same file). This is an impossible situation, because f cannot be updated before itself. Before f can be built make will try to build its prerequisites, which are f. But before the prerequisite f can be built make must build its prerequisite, which is f. And before that can be built make must build its prerequisite which is also f. Etc. forever and ever. There are different things make could do when it finds this impossible situation. It could, for example, just fail with an error code. But instead what make chooses to do is drop the prerequisite to avoid the recursion. That's what the warning message you see means. So in effect although they are not the same thing, make does end up treating f:f as if it were just f.
doc_23535059
(I dont want to use Adobe Reader) I've read gswin32c.exe which can do the job. I experimented with many commands and coudn't find the way how to force gs to print PDF on my (windows default) network drive. I don't need point exact network printer- default can be used. But if there is no such option I'm happy to pass printer name as well. (I've tried with param -SDevice="\server_IP\printer_name" but this didnt work as well...) Command working under Windows cmd: gswin32c -dPrinted -dBATCH -dNOPAUSE -dNOSAFER -q -dNumCopies=1 -sDEVICE=ljet4 -sOutputFile="\\spool\\\Server_Name\Printer_name" "C:\test.pdf" Method created base on above - doesnt work and thorws exception. (Error code = 1) /// <summary> /// Prints the PDF. /// </summary> /// <param name="ghostScriptPath">The ghost script path. Eg "C:\Program Files\gs\gs8.71\bin\gswin32c.exe"</param> /// <param name="numberOfCopies">The number of copies.</param> /// <param name="printerName">Name of the printer. Eg \\server_name\printer_name</param> /// <param name="pdfFileName">Name of the PDF file.</param> /// <returns></returns> public bool PrintPDF (string ghostScriptPath, int numberOfCopies, string printerName, string pdfFileName) { ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.Arguments = " -dPrinted -dBATCH -dNOPAUSE -dNOSAFER -q -dNumCopies=" + Convert.ToString(numberOfCopies) + " -sDEVICE=ljet4 -sOutputFile=\"\\\\spool\\" + printerName + "\" \"" + pdfFileName + "\""; startInfo.FileName = ghostScriptPath; startInfo.UseShellExecute = false; Process process = Process.Start(startInfo); return process.ExitCode == 0; } Any idea how to make it working under C#? A: Not sure if it helps anyone, but to add the printing documents to a queue instead of immediately printing make changes to the above section with startInfo.Arguments = " -dPrinted -dNoCancel=true -dBATCH -dNOPAUSE -dNOSAFER -q -dNumCopies=" + Convert.ToString(numberOfCopies) + " -sDEVICE=mswinpr2 -sOutputFile=%printer%" + printerName + " \"" + pdfFullFileName + "\""; Pre-requisites: Configure your printer's job type to "Hold Print": In our case we have a Rico Aficio MP 4000 Printer and our usage is to run a nightly job to print a bunch of PDF files generated through SSRS. A: You should test your options from the command line first, and then translate the successes into your code. A PDF file usually does already include page margins. You "often cut" page content may result from a PDF which is meant for A4 page size printed on Letter format. PDF also uses some internal boxes which organize the page (and object) content: MediaBox, TrimBox, CropBox, Bleedbox. There are various options to control for which "media size" Ghostscript renders a given input: -dPDFFitPage -dUseTrimBox -dUseCropBox With PDFFitPage Ghostscript will render to the current page device size (usually the default page size). With UseTrimBox it will use the TrimBox (and it will at the same time set the PageSize to that value). With UseCropBox it will use the CropBox (and it will at the same time set the PageSize to that value). By default (give no parameter), Ghostscript will render using the MediaBox. Note, you can additionally control the overall size of your output by using -sPAPERSIZE (select amongst all pre-defined values Ghostscript knows) or (for more flexibility) use -dDEVICEWIDTHPOINTS=NNN -dDEVICEHEIGHTPOINTS=NNN to set up custom page sizes. A: Adding only -dPDFFitPage to my arguments fixed the same issue with the "top page content is often cut." A: I've finally made it working and easy for debugging. My final method code for those interested: /// <summary> /// Prints the PDF. /// </summary> /// <param name="ghostScriptPath">The ghost script path. Eg "C:\Program Files\gs\gs8.71\bin\gswin32c.exe"</param> /// <param name="numberOfCopies">The number of copies.</param> /// <param name="printerName">Name of the printer. Eg \\server_name\printer_name</param> /// <param name="pdfFileName">Name of the PDF file.</param> /// <returns></returns> public bool PrintPDF (string ghostScriptPath, int numberOfCopies, string printerName, string pdfFileName) { ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.Arguments = " -dPrinted -dBATCH -dNOPAUSE -dNOSAFER -q -dNumCopies=" + Convert.ToString(numberOfCopies) + " -sDEVICE=ljet4 -sOutputFile=\"\\\\spool\\" + printerName + "\" \"" + pdfFileName + "\" "; startInfo.FileName = ghostScriptPath; startInfo.UseShellExecute = false; startInfo.RedirectStandardError = true; startInfo.RedirectStandardOutput = true; Process process = Process.Start(startInfo); Console.WriteLine( process.StandardError.ReadToEnd() + process.StandardOutput.ReadToEnd() ); process.WaitForExit(30000); if (process.HasExited == false) process.Kill(); return process.ExitCode == 0; }
doc_23535060
The stack trace says: Devart.Data.Linq.ChangeConflictException: Row not found or changed. at Devart.Data.Linq.Engine.b4.a(IObjectEntry[] A_0, ConflictMode A_1, a A_2) at Devart.Data.Linq.Engine.b4.a(ConflictMode A_0) at Devart.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode) at Devart.Data.Linq.DataContext.SubmitChanges() at Billing.Eway.EwayInternal.SuccessCustomerRenewal(String username, Bill bill, EwayTransaction transaction) in c:\Users\Ian\Source\Repos\billing-class-library\Billing\Billing\Eway\EwayInternal.cs:line 552 at Billing.Eway.Eway.BillAllUsers() in c:\Users\Ian\Source\Repos\billing-class-library\Billing\Billing\Eway\Eway.cs:line 138 And my code for Billing.Eway.EwayInternal.SuccessCustomerRenewal: internal static void SuccessCustomerRenewal(string username, Bill bill, EwayTransaction transaction) { // Give them their points! ApplyBillToCustomerAccount(username, bill, true); BillingEmail.SendRenewalSuccessEmail(username, bill, transaction); using (MsSqlDataClassesDataContext msSqlDb = new MsSqlDataClassesDataContext()) { // TODO: Remove this logging msSqlDb.Log = new StreamWriter(@"logs\db\" + Common.GetCurrentTimeStamp() + "-MsSQL.txt", true) { AutoFlush = true }; EwayCustomer ewayCustomer = msSqlDb.EwayCustomers.First(c => c.Username == username); ewayCustomer.NextBillingDate = Common.GetPlanExpiry(bill.BillPlan); using (MySqlDataContext mySqlDb = new MySqlDataContext()) { // TODO: Remove this logging mySqlDb.Log = new StreamWriter(@"logs\db\" + Common.GetCurrentTimeStamp() + "-MySQL.txt", true) { AutoFlush = true }; BillingMySqlContext.Customer grasCustomer = mySqlDb.Customers.First(c => c.Username == username); // Extend their membership date out so that the plan doesn't expire because of a failed credit card charge. grasCustomer.MembershipDate = ewayCustomer.NextBillingDate.AddDays(1); mySqlDb.SubmitChanges(); // <-- This is line 552 } msSqlDb.SubmitChanges(); } } I know that the issue occurs on the mySqlDb.SubmitChanges() line, since that DB context is the one using Devart (Linq solution for MySQL databases): the other context uses pure MS Linq. Not only is the change written to the MySql DB (inner using block), but it is also written to the MsSql DB (outer using block). But that's where the magical success ends. If I could I would write a Minimal, Complete and Verifiable example, but strangely I'm unable to generate a Devart ChangeConflictException. So, why does the change get saved to the database after a Devart.Data.Linq.ChangeConflictException? When I previously encountered System.Data.Linq.ChangeConflictException changes weren't saved. Edit 1: I've also now included the .PDB file and gotten line number confirmation of the exact source of the exception. Edit 2: I now understand why I can't generate a ChangeConflictException, so how is it happening here? These are the attributes for MembershipDate:_ [Column(Name = @"Membership_Date", Storage = "_MembershipDate", CanBeNull = false, DbType = "DATETIME NOT NULL", UpdateCheck = UpdateCheck.Never)] I know I can explicitly force my changes through to override any potential conflict, but that seems undesirable (I don't know what I would be overriding!). Similarly I could wrap the submit in a try block, and retry (re-reading each time) until success, but that seems clunky. How should I deal with this intermittent issue? Edit 3: It's not caused by multiple calls. This function is called in one place, by a single-instance app. It creates log entries every time it is run, and they are only getting created once. I have since moved the email call to the top of the method: the email only gets sent once, the exception occurs, and database changes are still made. I believe it has something to do with the using blocks. Whilst stepping through the debugger on an unrelated issue, I entered the using block, but stopped execution before the SubmitChanges() call. And the changes were still written to the database. My understanding was that using blocks were to ensure resources were cleaned up (connections closed, etc), but it seems that the entire block is being executed. A new avenue to research... But it still doesn't answer how a ChangeConflictException is even possible given Devart explicitly ignores them. Edit 4: So I wasn't going crazy, the database change did get submitted even after I ended execution in the middle of the using block, but it only works for websites. Edit 5: As per @Evk's suggestion I've included some DB logging (and updated the stacktrace and code snippet above). The incidence rate of this exception seems to have dropped, as it has only just happened since I implemented the logging. Here are the additional details: Outer (MS SQL) logfile: SELECT TOP (1) [t0].[id], [t0].[Username], [t0].[TokenId], [t0].[PlanId], [t0].[SignupDate], [t0].[NextBillingDate], [t0].[PaymentType], [t0].[RetryCount], [t0].[AccountStatus], [t0].[CancelDate] FROM [dbo].[EwayCustomer] AS [t0] WHERE [t0].[Username] = @p0 -- @p0: Input NVarChar (Size = 4000; Prec = 0; Scale = 0) [dyonis] -- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 4.0.30319.18408a (It just shows the SELECT call (.First()), none of the updates show). Inner (MySQL) logfile: SELECT t1.Customer_ID, t1.Username, t1.Account_Group, t1.Account_Password, t1.First_Name, t1.Last_Name, t1.Account_Type, t1.Points, t1.PromoPoints, t1.Phone, t1.Cell, t1.Email, t1.Address1, t1.Address2, t1.City, t1.State, t1.Country, t1.Postcode, t1.Membership_Group, t1.Suspend_On_Zero_Points, t1.Yahoo_ID, t1.MSN_ID, t1.Skype_ID, t1.Repurchase_Thresh, t1.Active, t1.Delete_Account, t1.Last_Activity, t1.Membership_Expires_After_x_Days, t1.Membership_Date, t1.auth_name, t1.created_by, t1.created_on, t1.AccountGroup_Points_Used, t1.AccountGroup_Points_Threashold, t1.LegacyPoints, t1.Can_Make_Reservation, t1.Gallery_Access, t1.Blog_Access, t1.Private_FTP, t1.Photometrica, t1.Promo_Code, t1.Promo_Expire_DTime, t1.Gift_FirstName, t1.Gift_LastName, t1.Gift_Email, t1.Gift_Phone, t1.Gift_Active, t1.NoMarketingEmail, t1.Can_Schedule, t1.Refered_By, t1.Q1_Hear_About_Us, t1.Q2_Exp_Level, t1.Q3_Intrests, t1.GIS_DTime_UTC, t1.Membership_Expire_Notice_Sent, t1.Promo_Expire_Notice_Sent, t1.isEncrypted, t1.PlanId FROM grasbill.customers t1 WHERE t1.Username = :p0 LIMIT 1 -- p0: Input VarChar (Size = 6; DbType = AnsiString) [dyonis] -- Context: Devart.Data.MySql.Linq.Provider.MySqlDataProvider Mapping: AttributeMappingSource Build: 4.4.519.0 UPDATE grasbill.customers SET Membership_Date = :p1 WHERE Customer_ID = :key1 -- p1: Input DateTime (Size = 0; DbType = DateTime) [8/3/2016 4:42:53 AM] -- key1: Input Int (Size = 0; DbType = Int32) [7731] -- Context: Devart.Data.MySql.Linq.Provider.MySqlDataProvider Mapping: AttributeMappingSource Build: 4.4.519.0 (Shows the SELECT and UPDATE calls) So the log files don't really give any clue as to what's happening, but again the MS SQL database has been updated! The NextBillingDate field has been set correctly, as per this line: ewayCustomer.NextBillingDate = Common.GetPlanExpiry(bill.BillPlan); If it hadn't been updated, the user would have been billed again on the next timer tick (5 mins later), and I can see from logging that didn't happen. One other interesting thing to note is the log file timestamps. As you can see from the code above I grab the current (UTC) time for the log filename. Here is the information shown by Windows File Explorer: The MS SQL logfile was created at 04:42 (UTC) and last modified at 14:42 (UTC+10, Windows local-time), but the MySQL logfile was last modified at 15:23 (UTC+10), 41 minutes after it was created. Now I assume the logfile StreamWriter is closed as soon as it leaves scope. Is this delay an expected side effect of the exception? Did it take 41 minutes for the garbage collector to realise I no longer needed a reference to the StreamWriter? Or is something else going on? A: Well 6 months later I finally got to the bottom of this problem. Not sure if it will ever help anyone else, but I'll detail it anyway. There were 2 problems in play here, and 1 of them was idiocy (as they usually are), but one was legitimately something I did not know or expect. Problem 1 The reason the changes were magically made to the database even though there was an exception was because the very first line of code in that function ApplyBillToCustomerAccount(username, bill, true); updates the database! <facepalm> Problem 2 The (Devart) ChangeConflictException isn't only thrown if the data has changed, but also if you're not making any changes. MS SQL stores DateTimes with great precision, but MySQL (or the one I'm running at least) only stores down to seconds. And here's where the intermittency came in. If my database calls were quick enough, or just near the second boundary, they both got rounded to the same time. Devart saw no changes to be written, and threw a ChangeConflictException. I recently made some optimisations to the database which resulted in far greater responsiveness, and massively increased incidence of this exception. That was one of the clues. Also I tried changing the Found Rows parameter to true as instructed in the linked Devart post but found it did not help in my case. Or perhaps I did it wrong. Either way now that I've found the source of the issue I can eliminate the duplicate database updates.
doc_23535061
<h2><a id='eg' rel="nofollow">Example</a></h2> Now from HTML 5 specification we know that this is allowed (for example if link is completed later through JavaScript code), it's also allwed in HTML 4.01 (thanks to this post for references). In short it's useful if a link may be placed there but for any reason it has not been (server side) or it has been removed (client side). OK it's clear as it's also well summarized here. Another (kind of) subtle difference is styling: even if link isn't rendered as link (by default underline and hand cursor) it'll inherit custom CSS styles for links such as: a { font-weight: bold; } Question: what I don't understand is the reason it's used in that page. There isn't any client-side JavaScript to add/remove href for that links and (more or less reasonably) I suppose such simple page is plain HTML and it's not generated server side. That said...why that links? Is there any other use I'm missing? Is it something related to SE? A: Check http://sscce.org/#eg and you will now. It was an old way to create links to a specific part of the page. Back then, you couldn't reference any element on the page, just anchors. Now it works the same with divs having an id.
doc_23535062
Now I have this code, which detects a single key press: while(1) [keyIsDown,~,keyCode]=KbCheck; if keyIsDown if keyCode(SOME_KEY) exitExperiment(); end break; end end I wish that SOME_KEY would refer to a key combination, like ctrl+r or shift+ESC. Any other solution that will allow to refer to a combination of key presses will surely help. Thanks. A: You can check for a combination of keys, by checking that all of the appropriate key codes in the keyCode logical array are true. Here is an example that requires pressing the left control key and the r key at the same time: % setup KbName('UnifyKeyNames'); needed_key_names = {'LeftControl', 'r'}; needed_key_codes = KbName(needed_key_names); while(1) [keyIsDown,~,keyCode]=KbCheck(); if keyIsDown if all(keyCode(needed_key_codes)) break; end end end
doc_23535063
I am trying to use the cref variable in one of the subqueries, but I am getting an error that the cref column does not exist. If I take the subquery out it will display the column, so the column definitely exists. Also if there are any other mistakes, would appreciate the heads up :) SELECT DISTINCT (contractorsRef) AS cref, RIDGROUP AS ridg, ( SELECT count(*) FROM ( SELECT DISTINCT subcontractorRef FROM request INNER JOIN request_config ON request_config.RIDGROUP = request.RIDGROUP WHERE request_config.contractorsRef = cref --### ERROR HERE AND currenttaxyear =2011 AND weekno =31 ) AS xx ) as xxx FROM request_config WHERE currenttaxyear =2011 AND weekno =32 AND contractorsRef <>132 A: try this (note that I labeled the request_config in the outer select as outer_config and I qualified the reference in the inner select with the label SELECT DISTINCT (contractorsRef) AS cref, RIDGROUP AS ridg, (select count(DISTINCT subcontractorRef) FROM request INNER JOIN request_config ON request_config.RIDGROUP = request.RIDGROUP WHERE request_config.contractorsRef = outer_config.contractorsRef AND currenttaxyear =2011 AND weekno =31) AS xxx FROM request_config outer_config WHERE currenttaxyear =2011 AND weekno =32 AND contractorsRef <>132 EDIT pls try again, I removed 1 unnecessary layer from the subselect A: Subqueries are executed first and their results are used as input to the outer query. So while you are creating the coulmn cref in your outer query, it does not yet exist when your subquery is being executed. You can probably solve your problem by merging the two queries. Start with your subquery, and join with request_config. Then add the appropriate conditions, and the appropriate columns
doc_23535064
I have written a regular expression to be used to match all of the general pages on my web application. The regular expression was working absolutely fine when the application was running on IIS with a web.config file, but I have since moved the site to a Linux server and am now running under Apache. The strings I am trying to match are as follows: section 1/ section 1/section 2/ section 1/section 2/section 3/ I want each match to be captured by the pattern, with the following limitations: * *The final '/' is always optional *I want each match to match any character, apart from an underscore for the first two sections This is what I have tried: ^([^(?!_)\/]+)\/?([^(?!_)\/]+)?\/?([^\/]+)?\/?$ Whilst the above works in a Regex Tester, it causes my server to produce an 'Internal Server Error' when I put it in my .htaccess file, it didn't when I ran it in my web.config. Can anyone suggest a new pattern to use? Further Information Here are a few examples of other requests: Match Examples test/testing SOME/REQUEST/to a page anything can/be matched/ Don't Match Examples unless it has/an underscore_/in the/ first_section/or_second_section/ Please note the 'Internal Server Error' is not being caused by other errors in my .htacess, everything works fine until I uncomment my rewrite rule with this particular regex. Update Just to be clearer, these are further examples of rewrites that I would like my regex to match: http://example.com/property/ http://example.com/property.php http://example.com/property/manage/ http://example.com/property.php?request=manage http://example.com/property/edit/1234/ http://example.com/property.php?request=edit&id=1234 http://example.com/_property/ Does NOT Match http://example.com/property/_edit/ Does NOT Match Update 2 The following is working but I don't like that I have specified the allowed characters: ^([a-z0-9\s]+)\/?([a-z0-9\s]+)?\/?([a-z0-9\s\_]+)?\/?$ A: The problem with your Regex is that it is matching it's own results. For example: http://example.com/property/ Will be matched as: http://example.com/property.php Which will be matched again by the RewriteEngine as: http://example.com/property.php.php Which will be matched as: http://example.com/property.php.php.php and so on............... Solution: Make the last slash be a must or forbid a character on the url or add an underscore (_) to the url. Using your regex: ^([^(?!_)\/]+)\/?([^(?!_)\/]+)?\/?([^\/]+)?\/?$ Change it to: ^([^(?!_)\/]+)\/?([^(?!_)\/]+)?\/?([^\/]+)?\/$ As in the comments, I have proposed the following one as solving the issue: ^(?!(?:\.\.\/?)+)([^_\/]+)(?:\/([^_\/]+)(?:\/([^_\/]+))?)?\/?$ But it won't, but is a simplified version. To solve this, using the solutions I have said with my Regex: Disallowing the chars .?: ^(?!(?:\.\.\/?)+)([^_\/\.\?]+)(?:\/([^_\/]+)(?:\/([^_\/]+))?)?\/?$ Making \ to be a must as the last char: ^(?!(?:\.\.\/?)+)([^_\/]+)(?:\/([^_\/]+)(?:\/([^_\/]+))?)?\/$ A full redirect appending _ to the file, in an non-obstructive hacky way (untested): RewriteEngine on RewriteRule ^(?!(?:\.\.\/?)+)([^_\/]+)(?:\/([^_\/]+)(?:\/([^_\/]+))?)?\/?$ $1.php/_?request=$2&id=$3 This has the side effect of setting $_SERVER['PATH_INFO'] as _. This solution was untested! Anything inaccurate, please leave a comment. Edit: The reasoning behind this is that we must break the matching loops. The engine validates http://example.com/property/ and succeeds, redirecting to http://example.com/property.php. If this one matches too, all the sub-requests will match and you have recursion. The idea is that it doesn't match http://example.com/property.php and continues evaluating all the other rules.
doc_23535065
function billScroller(elem){ var parentTopCoordinate = $('#bill-list').offset().top; var elementCoordinate = $(elem).parent().offset().top; var scrollPosition = ( elementCoordinate - parentTopCoordinate ) - 2; $('#bill-list').animate({ scrollTop: scrollPosition },1000); } $(document).on('click',".bill-description",function() { //close all bills $(".bill-item-list").not($(this).next(".bill-item-list")).slideUp(600); billScroller(this); //open the clicked bills $(this).next(".bill-item-list") .slideToggle(600); }); How can i fix this issue. I tried to create a fiddle but it was too much code and some of the elements are drawn using ajax responses. Update : This is the element hierarchy. <div id="bill-list"> <div id="bill-panel"> <!-- Bill --> <div class="bill"> <!-- Bill description - Holds Bill details --> <div class="bill-description"> <div class="bill-info bill-number"><span>000A</span></div> <div class="bill-info table-name"><span>TABLE 78</span></div> <div class="bill-info room-number"><span>A678</span></div> <div class="bill-info amount"><span>76.00</span></div> <div class="bill-remove-icon"></div> </div> <!-- Bill Item list --> <div class="bill-item-list"> <!-- Item : This is a sample element & will be cleared when system loads --> <div class="bill-item"> <!-- Item image --> <div class="bill-item-img"></div> <!-- Item description --> <div class="bill-item-description"> <div class="bill-item-name"> <!-- Item Name --> <p class="bill-item-name-left">Normal Cofee</p> <!-- Item Price --> <p class="bill-item-name-right">170.00</p> <div class="clear"></div> </div> <!-- Total item price --> <div class="bill-item-price"> <span>170.00</span> </div> <!-- Item Quantity --> <div class="bill-item-amount"> <span>1</span> </div> </div> <!-- Increas & Decrease item Quantity --> <div class="bill-amount-selection"> <a class="amount-increase" href="#"></a> <a class="amount-decrease" href="#"></a> </div> </div> <!-- Remove bill link --> <div class="item-drop-point"></div> </div> </div> </div> </div> Bill Panel is scrollable and Bills are generated using ajax calls. A bill can contain multiple items and toggle slide function is used to open and close item list.
doc_23535066
However now I dont get any html response, even though it works from the browser. They say that they moved to the cloudflare. How can I know the server and make my curl command work? Here is my current curl output(It is a public site so any one can try) curl -v http://f7.masaladesi.com/login.php ~ * STATE: INIT => CONNECT handle 0x800481c0; line 1034 (connection #-5000) * Added connection 0. The cache now contains 1 members * Trying 104.25.171.117... * STATE: CONNECT => WAITCONNECT handle 0x800481c0; line 1087 (connection #0) * Connected to f7.masaladesi.com (104.25.171.117) port 80 (#0) * STATE: WAITCONNECT => DO handle 0x800481c0; line 1229 (connection #0) > GET /login.php HTTP/1.1 > User-Agent: Mozilla/5.0 (Windows; U; MSIE 9.0; WIndows NT 9.0; en-US)) > Host: f7.masaladesi.com > Accept: */* > * STATE: DO => DO_DONE handle 0x800481c0; line 1314 (connection #0) * STATE: DO_DONE => WAITPERFORM handle 0x800481c0; line 1441 (connection #0) * STATE: WAITPERFORM => PERFORM handle 0x800481c0; line 1454 (connection #0) * HTTP 1.1 or later with persistent connection, pipelining supported < HTTP/1.1 301 Moved Permanently < Date: Wed, 02 Aug 2017 04:57:21 GMT < Transfer-Encoding: chunked < Connection: keep-alive < Cache-Control: max-age=3600 < Expires: Wed, 02 Aug 2017 05:57:21 GMT < Location: https://f7.masaladesi.com/login.php * Server cloudflare-nginx is not blacklisted < Server: cloudflare-nginx < CF-RAY: 387e74b4538488b4-BOM < * STATE: PERFORM => DONE handle 0x800481c0; line 1626 (connection #0) * Connection #0 to host f7.masaladesi.com left intact * Expire cleared A: CloudFlare uses various methods to try to determine if the end user is a "real" browser and not malicious; this is largely in an effort to mitigate DDoS attacks. Long story short, it is not possible to reliably script access to a CloudFlare protected site. There are various temporary workarounds involving setting curl's user agent and using a "real" browser to access the site from a given IP before using curl, but they will tend to fail over time. For a CloudFlare employee weighing in on this, look no further than here.
doc_23535067
{ "user-id": 10009, "rating": 3, "movie_id": 9823 } I need to get the each data separately.so I can store them in database. the JSON file is a form-data. I tried: def post(self, request): data = request.FILES['json_file'] # a = data.read().decode('utf-8') a = json.loads(data) x = a['user-id'] print(x) return Response(x, status=status.HTTP_201_CREATED) The above code is not working and giving me error: the JSON object must be str, not 'InMemoryUploadedFile' How can i get data from JSON file(form-data) and store it's content in database? A: data is of the type InMemoryUploadedFile, so to convert it to a string you need to read it (as bytes) and convert it to a string: def post(self, request): data = request.data.get('json_file') a = json.loads(str(data.read())) x = a['user-id'] print(x) return Response(x, status=status.HTTP_201_CREATED)
doc_23535068
I tried this $scope.channel.bind('pusher:error', function() { console.log("pusher:error"); }); and also pusher:subscription_error but it does nothing. any help will be appreciated. A: It's important to highlight the difference between connection and subscription. * *A connection is a persistent connection to Pusher over which all communication takes place. *A subscription is a request for data. In Pusher these are represented by channels. Subscriptions and associated data use the established connection and multiple subscriptions are multiplexed over a single connection. To determine if the Pusher service is reachable or not you should check the connection state. However, if you ever see this I'd also recommend contacting Pusher support since this shouldn't happen. Detecting & Querying Connection State It's possible to detect connection state by binding to events on the connection object. pusher.connection.bind('state_change', function(states) { var prevState = states.previous; var currState = states.current; }); You can additional get the state right now. var currentState = pusher.connection.state; Full documentation on this can be found here: https://pusher.com/docs/client_api_guide/client_connect#connection-states The example in the questions appears to use Angular so you'll need to get reference to the connection object from the $scope. If you're using pusher-angular then the API should be the same as the normal Pusher library. Subscription Status You can bind to two events to determine the result of a subscription: * *pusher:subscription_succeeded *pusher:subscription_error The code to use these looks as follows: var channel = pusher.subscribe('my-channel'); channel.bind('pusher:subscription_succeeded', function() { // Yipee!! }); channel.bind('pusher:subscription_error', function() { // Oh nooooos! }); Documentation on the success event can be found here: https://pusher.com/docs/client_api_guide/client_events#subscription_succeeded Docs on the error event can be found here: https://pusher.com/docs/client_api_guide/client_events#subscription_error
doc_23535069
I want my class to inherit from a base class. Do I need to have both files inherit? Or will the class inherit from the base class if either partial class In generated foo.vb: Partial Public Class Foo Inherits BaseClass In manually-created foo.vb: Partial Public Class Foo It doesn't seem to matter (according to what I see in Reflector, anyways). Can anyone explain how this works? Does the compiler simply combine the two? A: Only one of the two needs to inherit. Partial classes are just compiler tricks. Your two files are stitched back together before compiling. This means that only one base class can be specified, just like in normal classes. You can have this: partial class one : base {} partial class one {} and this: partial class one : base {} partial class one : base {} but not this partial class one : fu {} partial class two : bar {} because the last one combines into: class one : fu, bar {} which is illegal. You can mix and match interfaces, however, just like on a normal class.
doc_23535070
I have this arralist ArrayList<String> MenuHeadersAL = new ArrayList<String>(); and trying to assign like for(int i=0; i<MenuHeadersAL.size();i++){ ResideMenuItem MenuItem = new ResideMenuItem(this,R.drawable.ic_veg,MenuHeadersAL.get(i)); resideMenu.addMenuItem(MenuItem, ResideMenu.DIRECTION_LEFT); } I have 10 values in arraylist but not getting anything in reside menu. Residemenu is blank. For This I am not using any adapter. When I use itemHome = new ResideMenuItem(this, R.drawable.ic_veg, "Home"); itemNewOrder = new ResideMenuItem(this, R.drawable.ic_veg, "New Order"); and resideMenu.addMenuItem(itemHome, ResideMenu.DIRECTION_LEFT); resideMenu.addMenuItem(itemNewOrder, ResideMenu.DIRECTION_LEFT); Then I am able to see menu option but when I am assigning it dynamically then Reside menu is blank. A: Done !!! Actually I was assigning arraylist to menuitem just after calling service. So there is service thread executes quite late and menulist item line executes with null arraylist. Thanks....
doc_23535071
In my development environment, i need to prevent require to cache the files. Ok, i already searched around and found this solution Prevent RequireJS from Caching Required Scripts But when i put it in my require.config code, i lost all my references from jQuery, etc... The error i get is: Uncaught TypeError: undefined is not a function Uncaught ReferenceError: jQuery is not defined I think something is wrong with my code, but don't know what (dependencies, references...). In the main.js: requirejs.config({ "urlArgs": "bust=" + (new Date()).getTime() "baseUrl": "js/app", "paths": { "doctorWorklist": "doctor-worklist", "jquery": "//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min", "bootstrap": "../lib/bootstrap.min", "app": "app" } }); // Load the main app module to start the app requirejs(["app"]); In the app.js define( ['jquery', 'bootstrap'], function( $ ) { //my code here. }); Any suggestions ? And sorry about the bad english. :D -- Update September, 18. I got it ! For those who are beginning with require.js like me, the error related above was in main.js For my purpose, the code of main.js must be like: requirejs.config({ "urlArgs": "bust=" + Math.random(), "baseUrl": "js/app", "paths": { "doctorWorklist": "doctor-worklist", "jquery": "//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min", "dataTables": "http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min", "bootstrap": "../lib/bootstrap.min", "bootstrapDatepicker": "../lib/bootstrap-datepicker.min", "bootstrapSelect": "../lib/bootstrap-select.min", "jPlayer": "../lib/jquery.jplayer.min", "countdown": "../lib/jquery.countdown.min", "countdownBR": "../lib/jquery.countdown-pt-BR.min", "googleapi": "../lib/googlecharts-api", "onrad": "onrad" } }); // Load the main app module to start the app requirejs(["jquery"], function($, jQuery) { var jQuery = $; // This moment, jQuery is completely loaded. // Time to require external libs with jQuery dependencies requirejs( [ "dataTables", "bootstrap", "bootstrapDatepicker", "bootstrapSelect" ] , function($, jQuery) { // External libs loaded ! // Time to required my app code requirejs(["countdown", "countdownBR", "onrad"]); }); } ); Hope it be useful for someone.
doc_23535072
I'm supposed to compare two strings if they are palindrome using a stack. My idea of this program is to fgets() a string. Clear the spaces and store it in char "o" then push each char into a stack, pop them out into another set of char "r" and check if(o == r). However, when I compile I get a warning, which the program worked fine with it. Further down into my program, when I try to pop my char back out, the program crashes. I'm curious what causes that warning in my code and how to fix it. Most important I want to understand what I am doing wrong to cause my program to crash when I pop my data out of the satck. The warning: main.c:28:17: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast] dataPtr = (char*)s[c]; What I get when it crashes: Segmentation fault (core dumped) My attached Code: #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include "stacksADT.h" int main (void) { char s[50]; char o[50]; char r[50]; STACK* stack; char* dataPtr; stack = createStack(); printf("Enter the string to compare:\n"); fgets(s,50, stdin); for(int c = 0; c < strlen(s); c++){ if( s[c] != ' ' ){ dataPtr = (char*)s[c]; printf("%s", dataPtr); pushStack( stack, dataPtr ); } } for(int c = 0; c < strlen(o); c++){ printf("%s", (char*)popStack(stack)); } } // main My popStack() operation: void* popStack (STACK* stack) { // Local Definitions void* dataOutPtr; STACK_NODE* temp; // Statements if(stack->count == 0) dataOutPtr = NULL; else { temp = stack->top; dataOutPtr = stack->top->dataPtr; stack->top = stack->top->link; free(temp); (stack->count)--; } // else return dataOutPtr; } // popStack A: s[c] returns a char. You simply cast it to a pointer. Assigning to a pointer char *dataPtr is wrong, you need to pass it a reference. Use either of these two: * *dataPtr = &(s[c]) *dataPtr = s+c
doc_23535073
You don't have permission to enable Cloud Scheduler (appengine.applications.create, serviceusage.services.enable) So I asked the project owner to grant me access to the below roles: * *Cloud Scheduler admin *AppEngine Admin *Service Usage Admin However, even after this I'm still getting the same message as before. Below are the current roles that I have access to: * *App Engine Admin *BigQuery Data Viewer *BigQuery User *Cloud Scheduler Admin *Cloud SQL Admin *Editor *Service Usage Admin *Storage Admin Kindly let me know if I'm missing something here. A: You don't need to be the project Owner. You need these permission: * *appengine.applications.create *serviceusage.services.enable Predefined roles for first permission: * *roles/owner *roles/appengine.appCreator Predefined roles for second permission: * *roles/owner *roles/editor *roles/serviceusage.serviceUsageAdmin Since you already are an Editor, you only need to request App Engine Creator role for the first permission. A: For you to be able to perform the configuration of Cloud Scheduler, you need to be the Project Owner. Could you please give it a try asking your administrator to make you the Project Owner? * *Understanding roles This should fix your issue and solve your case. In case it doesn't, let me know if you are facing the same error. Please, let me know if it worked! A: If you are using target HTTP Method in your Cloud Scheduler, you can add Auth Header (Add OAuth token) with a particular or spesific service account.
doc_23535074
source https://nuget.org/api/v2 nuget Neo4jClient >= 1.0.0.664 nuget FsCheck After mono .paket/paket.exe install I get related dependencies successfully downloaded into a packages folder. The auto-generated packet.lock file looks like the following: NUGET remote: https://nuget.org/api/v2 specs: FsCheck (2.0.5) FSharp.Core (>= 3.1.2.5) FSharp.Core (4.0.0.1) Microsoft.Bcl (1.1.10) Microsoft.Bcl.Build (>= 1.0.14) Microsoft.Bcl.Build (1.0.21) Microsoft.Net.Http (2.2.29) Microsoft.Bcl (>= 1.1.10) Microsoft.Bcl.Build (>= 1.0.14) Neo4jClient (1.0.0.664) Microsoft.Net.Http Newtonsoft.Json (>= 6.0.3) Newtonsoft.Json (7.0.1) I am trying to reference such libraries within my .fs files: #if INTERACTIVE #r "./packages/FsCheck/lib/net45/FsCheck.dll" #endif open FsCheck open FsCheck statement fails with The namespace or module 'FsCheck' is not defined. What am I doing wrong? EDIT: Switching to .fsx (instead of .fs) and removing the #if part works fine. With .fs it compiles but when running the .exe I get the following exception (I understand it means the .dll isn't bundled by default, in which case I wonder what the common practice is): Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'FsCheck, Version=2.0.5.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. A: Your path is missing the version. It should be #r "./packages/FsCheck.2.0.5/lib/net45/FsCheck.dll" A: * *Do you have a paket.references file in your project? *Did you add "FsCheck" to it? *Have you set the target framework of your project to .NET 4.5? If you are using Xamarin Studio, your project target framework is probably set to .NET 4.0. You can change this in Project Options > Build > General. You can also specify the target framework in paket.dependencies. You need step 3 though. framework: net45 source https://nuget.org/api/v2 nuget Neo4jClient >= 1.0.0.664 nuget FsCheck
doc_23535075
My google sheets are "published for web" in the form of CSV. I want to use react-papaparse for in-browser CSVtoJSON parsing. My gatsby-node.js is copying from the gatsby docs so it is a little barebone. in my gatsby-node.js const papaparse = require("react-papaparse") exports.sourceNodes = ({ actions, createNodeId, createContentDigest }) => { const { createNode } = actions const myData = papaparse.readRemoteFile("published sheet links",{ download: true, header: true, delimiter: ',', dynamicTyping: true, }) const nodeContent = JSON.stringify(myData) const nodeMeta = { id: createNodeId(`my-data-${myData.key}`), parent: null, children: [], internal: { type: `MyNodeType`, mediaType: `text/html`, content: nodeContent, contentDigest: createContentDigest(myData) } } const node = Object.assign({}, myData, nodeMeta) createNode(node) } When I run, it throws XMLHttpRequest is not defined error in my google sheet links. So it seems about CORS problem? What is the workaround for this? Thank you A: I'm afraid you won't be able to use XMLHttpRequest since it will be never available in the Node server (for obvious reasons), it will be available on your browser-side, but in your use-case, you need it to be available in the Node server, at the build-time, to create your schema. You can try using some other fetching methods (fetch, axios, etc) or use some plugins like gatsby-source-google-sheets. You just need to install the plugin and: { resolve: 'gatsby-source-google-sheets', options: { spreadsheetId: 'get this from the sheet url', worksheetTitle: 'ie the name in the worksheet tab', credentials: require('./path-to-credentials-file.json') } }, This will fetch in the build-time your sheets, creating the inferred GraphQL node schema Resources: * *https://spectrum.chat/gatsby-js/general/referenceerror-xmlhttprequest-is-not-defined-on-production-build~5bc45c69-36e1-4ad4-b8d6-495b5ec242bd *Gatsby XMLHttpRequest *https://www.twilio.com/blog/2017/03/google-spreadsheets-and-javascriptnode-js.html *https://www.gatsbyjs.com/docs/debugging-html-builds/
doc_23535076
but what I am looking for is this. {"accountnumber":"A00000065","invoice":{"ids":["2c92c09a693316310169384472126a0d"], "numbers":["INV00000270"]}} I have tried using the map_concat to no luck. [![enter image description here][2]][2] https://prestodb.io/docs/current/functions/map.html [2]: https://i.stack.imgur.com/pq5iu.png UPDATE: If I do the following it works. map_concat(multimap_agg('number', invoice.invoicenumber), multimap_agg('id', invoice.id)) but if I change to map_concat(multimap_agg('number', invoice.invoicenumber), multimap_agg('id', invoice.balance)) I get this error line 1:23: Unexpected parameters (map(varchar(6),array(varchar)), map(varchar(2),array(decimal(18,6)))) for function map_concat. Expected: map_concat(map(K,V)) K, V A: It should go in a comment, but that's too long. If it doesn't work, I'll delete the answer. try this: SELECT map_concat(multimap_agg('ids', invoice.id), multimap_agg('numbers', invoice.invoicenumber)) FROM ...
doc_23535077
I have tried looking if I had made a typo but I am pretty sure I didn't and I have also made sure I had downloaded all the packages needed and looked through the tutorial multiple times. The tutorial is by https://freecodecamp.org import requests from bs4 import BeautifulSoup result = requests.get('https://en.wikipedia.org/wiki/List_of_highest-grossing_films') src = result.content soup = BeautifulSoup(src, 'lxml') results = [] for i in soup.find_all('th'): a_tag = i.find('a') results.append(a_tag.attrs['title']) print(results) A: you are getting the error because not all the items in the list soup.find_all('th') have tag a, and if you fix this, not all the items will have title , so try like this: src = result.content soup = BeautifulSoup(src, 'lxml') results = [] for i in soup.find_all('th'): if i.find('a'): a_tag = i.find('a') if a_tag.get('title'): results.append(a_tag.attrs['title']) print(results) Note:I tried not to reflector your code, and we can made it better :)
doc_23535078
I've run every command without errors, started run-job.sh without errors, but job in YARN stays forever in ACCEPTED state. I've looked at http://localhost:8088/cluster/nodes and it shows nothing - is this the problem? YARN has no nodes connected so it cannot allocate resources to complete submitted job? yarn node -list also shows Total Nodes:0 Why is that, if I'm simply following the instructions? A: YARN has no nodes connected so it cannot allocate resources to complete submitted job? Yes, the job is queued up and is awaiting resources to launch. It may be useful to look at the logs for the NodeManager to figure out why it can't connect to the ResourceManager. A: I had the same problem but I figured it out what was wrong. Maybe in your situation it was different problem, but it is worth to check it (also it may help other people). According to suggestion of Jon Bringhurst I recommended to look at Yarn Node Manager logs - for hello samza project they should be under: hello-samza/deploy/yarn/logs/yarn-*nodemanger-*.log In my case (probably in your too) I saw ERORR which said (before there was also WARN which tell me that disk space is above 90%): 1/1 local-dirs are bad: *; 1/1 log-dirs are bad: * They are bad because available disk space on the node exceeding yarn's max-disk-utilization-per-disk-percentage default value of 90.0%. Either clean up the disk, or increase the threshold in yarn-site.xml (like I did): <property> <name>yarn.nodemanager.disk-health-checker.max-disk-utilization-per-disk-percentage</name> <value>97</value> </property>
doc_23535079
A: Todd from Crashlytics here! Right now this is not possible without some sort of custom adapter on your end to go back to Swift or Objective-C. As C++ becomes more common in advanced apps I'd expect to see the team consider this :) A: Yep, I don't think there is a C-function for that but I had the problem some time ago and I used a function pointer. So here it is. In the C scope (.cpp and .h file) void yourCFunction(void (*logFunc)(const char*) = NULL); In the ObjectiveC scope: CYourCClass *yourCClass = [...]; yourCClass->yourCFunction( [](const char* t){ CLS_LOG(@"%s", t); }); To call the log function in C++: if (logFunc!=NULL) { std::string debugChr("Some message"); (*logFunc)(debugChr.c_str()); } This can be improved using macro and stuff but you have the idea.
doc_23535080
Here is the script for the row over effect without the jqtransform: function selectRowEffect(object, buttonSelect) { if (!selected) { if (document.getElementById) { selected = document.getElementById('defaultSelected'); } else { selected = document.all['defaultSelected']; } } if (selected) selected.className = 'moduleRow'; object.className = 'moduleRowSelected'; selected = object; // one button is not an array if (document.checkout_address.shipping[0]) { document.checkout_address.shipping[buttonSelect].checked=true; } else { document.checkout_address.shipping.checked=true; } } function rowOverEffect(object) { if (object.className == 'moduleRow') object.className = 'moduleRowOver'; } function rowOutEffect(object) { if (object.className == 'moduleRowOver') object.className = 'moduleRow'; } //--></script> Currently if I click on the row, it will actually select the radio button in my form but the jqtransform does not reflect that so it still looks like it is not clicked. I tried adding something like jqTransformRadio.addClass("jqTransformChecked"); My JavaScript knowledge is quite limited. Any help is greatly appreciated. A: I think you can change the your selectRowEffect() function like this: function selectRowEffect(object, buttonSelect) { if (!selected) { if (document.getElementById) { selected = document.getElementById('defaultSelected'); } else { selected = document.all['defaultSelected']; } } if (selected) selected.className = 'moduleRow'; object.className = 'moduleRowSelected'; selected = object; // Get checkbox element inside the row, then trigger the 'click' event. $('.jqTransformRadio', object).trigger('click'); } I haven't tested the code yet, but I think it will work
doc_23535081
My attempt is import numpy as np import random import pickle import bitstring import tensorflow as tf # this is for converting numbers to binary form def binary(num): f1 = bitstring.BitArray(float=num, length=32) return f1.bin def num2bin(num): return [int(x) for x in binary(num)[0:]] N=60; pos=10*np.random.rand(N) pos1=10*np.random.rand(N) pos1_test=10*np.random.rand(N) pos_test=10*np.random.rand(N) neg=-10*np.random.rand(N) neg_test=-10*np.random.rand(N) m=np.concatenate((pos,neg),axis=0) b=np.concatenate((pos*0,pos1),axis=0) m_test=np.concatenate((pos_test,neg_test),axis=0) b_test=np.concatenate((pos*0,pos1_test),axis=0) # this creates the training data. def create_label_feature(m,m_test,b,b_test,test_size=0.1): train_x=[] train_y=[] test_x=[] test_y=[] for x in m: for y in b: train_x +=[num2bin(x)+num2bin(y)] if y !=0 and abs(x)<abs(y): train_y+=[[1,0]] elif y==0 and x>0: train_y+=[[1,0]] elif y==0 and x<=0: train_y+=[[0,1]] else: train_y+=[[0,1]] for x in m_test: for y in b_test: test_x +=[num2bin(x)+num2bin(y)] if y !=0 and abs(x)<abs(y): test_y+=[[1,0]] elif y==0 and x>0: test_y+=[[1,0]] elif y==0 and x<=0: test_y+=[[0,1]] else: test_y+=[[0,1]] return train_x, train_y, test_x, test_y train_x ,train_y ,test_x, test_y=create_label_feature(m,m_test,b,b_test,test_size=0.1) This is the actual NN n_nodes_hl1 = 1500 n_nodes_hl2= 1500 n_nodes_hl3= 1500 n_classes = 2 batch_size = 144 hm_epochs = 100 x = tf.placeholder('float',shape=[None,64]) y = tf.placeholder('float') hidden_1_layer = {'f_fum':n_nodes_hl1, 'weight':tf.Variable(tf.random_normal([len(train_x[0]), n_nodes_hl1])), 'bias':tf.Variable(tf.random_normal([n_nodes_hl1]))} hidden_2_layer = {'f_fum':n_nodes_hl2, 'weight':tf.Variable(tf.random_normal([n_nodes_hl1, n_nodes_hl2])), 'bias':tf.Variable(tf.random_normal([n_nodes_hl2]))} hidden_3_layer = {'f_fum':n_nodes_hl3, 'weight':tf.Variable(tf.random_normal([n_nodes_hl2, n_nodes_hl3])), 'bias':tf.Variable(tf.random_normal([n_nodes_hl3]))} output_layer = {'f_fum':None, 'weight':tf.Variable(tf.random_normal([n_nodes_hl3, n_classes])), 'bias':tf.Variable(tf.random_normal([n_classes])),} # Nothing changes def neural_network_model(data): l1 = tf.add(tf.matmul(data,hidden_1_layer['weight']), hidden_1_layer['bias']) l1 = tf.nn.relu(l1) l2 = tf.add(tf.matmul(l1,hidden_2_layer['weight']), hidden_2_layer['bias']) l2 = tf.nn.relu(l2) l3 = tf.add(tf.matmul(l2,hidden_2_layer['weight']), hidden_2_layer['bias']) l3 = tf.nn.relu(l3) output = tf.matmul(l3,output_layer['weight']) + output_layer['bias'] return output saver = tf.train.Saver() tf_log = 'tf.log' def train_neural_network(x): prediction = neural_network_model(x) cost = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(logits=prediction,labels=y) ) optimizer = tf.train.AdamOptimizer(learning_rate=0.001).minimize(cost) with tf.Session() as sess: sess.run(tf.initialize_all_variables()) for epoch in range(hm_epochs): epoch_loss = 0 i=0 while i < len(train_x): start = i end = i+batch_size batch_x = np.array(train_x[start:end]) batch_y = np.array(train_y[start:end]) _, c = sess.run([optimizer, cost], feed_dict={x: batch_x, y: batch_y}) epoch_loss += c i+=batch_size print('Epoch', epoch+1, 'completed out of',hm_epochs,'loss:',epoch_loss) saver.save(sess, 'C:\\Users\\HP\\Documents\\Python Deep Learning Learning\\model_2.ckpt') correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct, 'float')) print('Accuracy:',accuracy.eval({x:test_x, y:test_y})) # a=num2bin(98) # a=np.reshape(a,(1,64)) for k in [1,2,3,0,15]: a=num2bin(k) a=np.concatenate((a,num2bin(10)),axis=0) a=np.reshape(a,(1,64)) a=sess.run(prediction, {x:a}) prediction_tensor = tf.nn.softmax(a) print(sess.run(prediction_tensor)) train_neural_network(x) But when I run this I get WARNING:tensorflow:From <ipython-input-43-bef948531bdc>:58: initialize_all_variables (from tensorflow.python.ops.variables) is deprecated and will be removed after 2017-03-02. Instructions for updating: Use `tf.global_variables_initializer` instead. Epoch 1 completed out of 100 loss: 1656465.87708 Epoch 2 completed out of 100 loss: 965547.536972 Epoch 3 completed out of 100 loss: 523595.430435 Epoch 4 completed out of 100 loss: 977268.598053 Epoch 5 completed out of 100 loss: 668892.447758 Epoch 6 completed out of 100 loss: 533576.244034 Epoch 7 completed out of 100 loss: 447366.692417 Epoch 8 completed out of 100 loss: 201797.375396 Epoch 9 completed out of 100 loss: 123624.894434 Epoch 10 completed out of 100 loss: 74161.0360594 Epoch 11 completed out of 100 loss: 62320.2841816 Epoch 12 completed out of 100 loss: 82650.6948113 Epoch 13 completed out of 100 loss: 97856.969979 Epoch 14 completed out of 100 loss: 86694.9150848 Epoch 15 completed out of 100 loss: 104940.329952 Epoch 16 completed out of 100 loss: 55279.0731068 Epoch 17 completed out of 100 loss: 42239.2455358 Epoch 18 completed out of 100 loss: 26236.6220574 Epoch 19 completed out of 100 loss: 15605.1042328 Epoch 20 completed out of 100 loss: 7502.51530361 Epoch 21 completed out of 100 loss: 4281.0073503 Epoch 22 completed out of 100 loss: 2421.28072715 Epoch 23 completed out of 100 loss: 1674.25452423 Epoch 24 completed out of 100 loss: 1491.07880789 Epoch 25 completed out of 100 loss: 1245.5299934 Epoch 26 completed out of 100 loss: 932.400794029 Epoch 27 completed out of 100 loss: 182.700586021 Epoch 28 completed out of 100 loss: 246.078451872 Epoch 29 completed out of 100 loss: 295.789887428 Epoch 30 completed out of 100 loss: 144.528374732 Epoch 31 completed out of 100 loss: 95.6009635925 Epoch 32 completed out of 100 loss: 88.4947395325 Epoch 33 completed out of 100 loss: 201.378837585 Epoch 34 completed out of 100 loss: 0.0 Epoch 35 completed out of 100 loss: 0.0 Epoch 36 completed out of 100 loss: 0.0 Epoch 37 completed out of 100 loss: 0.0 Epoch 38 completed out of 100 loss: 0.0 Epoch 39 completed out of 100 loss: 0.0 Epoch 40 completed out of 100 loss: 0.0 Epoch 41 completed out of 100 loss: 0.0 Epoch 42 completed out of 100 loss: 0.0 Epoch 43 completed out of 100 loss: 0.0 Epoch 44 completed out of 100 loss: 0.0 Epoch 45 completed out of 100 loss: 0.0 Epoch 46 completed out of 100 loss: 0.0 Epoch 47 completed out of 100 loss: 0.0 Epoch 48 completed out of 100 loss: 0.0 Epoch 49 completed out of 100 loss: 0.0 Epoch 50 completed out of 100 loss: 0.0 Epoch 51 completed out of 100 loss: 0.0 Epoch 52 completed out of 100 loss: 0.0 Epoch 53 completed out of 100 loss: 0.0 Epoch 54 completed out of 100 loss: 0.0 Epoch 55 completed out of 100 loss: 0.0 Epoch 56 completed out of 100 loss: 0.0 Epoch 57 completed out of 100 loss: 0.0 Epoch 58 completed out of 100 loss: 0.0 Epoch 59 completed out of 100 loss: 0.0 Epoch 60 completed out of 100 loss: 0.0 Epoch 61 completed out of 100 loss: 0.0 Epoch 62 completed out of 100 loss: 0.0 Epoch 63 completed out of 100 loss: 0.0 Epoch 64 completed out of 100 loss: 0.0 Epoch 65 completed out of 100 loss: 0.0 Epoch 66 completed out of 100 loss: 0.0 Epoch 67 completed out of 100 loss: 0.0 Epoch 68 completed out of 100 loss: 0.0 Epoch 69 completed out of 100 loss: 0.0 Epoch 70 completed out of 100 loss: 0.0 Epoch 71 completed out of 100 loss: 0.0 Epoch 72 completed out of 100 loss: 0.0 Epoch 73 completed out of 100 loss: 0.0 Epoch 74 completed out of 100 loss: 0.0 Epoch 75 completed out of 100 loss: 0.0 Epoch 76 completed out of 100 loss: 0.0 Epoch 77 completed out of 100 loss: 0.0 Epoch 78 completed out of 100 loss: 0.0 Epoch 79 completed out of 100 loss: 0.0 Epoch 80 completed out of 100 loss: 0.0 Epoch 81 completed out of 100 loss: 0.0 Epoch 82 completed out of 100 loss: 0.0 Epoch 83 completed out of 100 loss: 0.0 Epoch 84 completed out of 100 loss: 0.0 Epoch 85 completed out of 100 loss: 0.0 Epoch 86 completed out of 100 loss: 0.0 Epoch 87 completed out of 100 loss: 0.0 Epoch 88 completed out of 100 loss: 0.0 Epoch 89 completed out of 100 loss: 0.0 Epoch 90 completed out of 100 loss: 0.0 Epoch 91 completed out of 100 loss: 0.0 Epoch 92 completed out of 100 loss: 0.0 Epoch 93 completed out of 100 loss: 0.0 Epoch 94 completed out of 100 loss: 0.0 Epoch 95 completed out of 100 loss: 0.0 Epoch 96 completed out of 100 loss: 0.0 Epoch 97 completed out of 100 loss: 0.0 Epoch 98 completed out of 100 loss: 0.0 Epoch 99 completed out of 100 loss: 0.0 Epoch 100 completed out of 100 loss: 0.0 Accuracy: 0.881944 [[ 1. 0.]] [[ 1. 0.]] [[ 1. 0.]] [[ 1. 0.]] [[ 1. 0.]] At first I tried with less, layers, and training data the results were very inaccurate.So what are the tips to improve? Why does the loss stuck to 0 after 33 rd epoch. And how do I improve the acuraccy further.
doc_23535082
This my configuration : 'cache'=>array( 'class'=>'system.caching.CDbCache', 'connectionId'=>'db', ), and i want to optimise this query: $dependency = new CDbCacheDependency('SELECT MAX(id) FROM user_notification'); $userNotificationModel = UserNotification::model()->cache(9000, $dependency)->findAllByAttributes( array( 'status' => NotificationCronCommand::QUEUED ) );
doc_23535083
<img src='uploads/'"<?php echo $pic; ?>"> In the above code $pic = myCatImage.jpg But it does not work How can I do this ? A: Your quotes are off: <img src='uploads/<?php echo $pic; ?>'> This value goes inside the same quotes as the rest of the value of the src attribute.
doc_23535084
First, I created a route at web.php file: Route::view('/homepageVue', 'layouts.homepage'); Then, I created the layouts.homepage blade file: @extends('lib.master.main') @section('styles') @stop @section('scripts') <script src="{!! asset('js/homepage/homepage.js') !!}" type="text/javascript"></script> @stop @section('title') - Homepage @stop @section('content') <div id="homepage"></div> @stop Then, I created in the assets folder, the component, and the homepage.js files: assets/js/homepage/homepage.js: // ***************************** // ***** Private Variables ***** // ***************************** /** * Save this instance * @type @this; * @private */ var self = this; /** * If Module has been initiated * @type Boolean * @private */ var _isInit = false; // to avoid 'rebinds' /** * Categories Component instance */ const homepage = require('./components/homepage'); // **************************** // ***** Public functions ***** // **************************** /** * start * * Starts the module * Inits private variables and executes specific logic needed for the module * to start. * * @public */ this.start = function() { if(!_isInit) { console.log("Homepage starts.."); homepage.start(); } }; self.start(); Then, I created the assets/js/homepage/component/homepage.js file: // ***************************** // ***** Private Variables ***** // ***************************** /** * Save this instance * @type @this; * @private */ var self = this; /** * If Module has been initiated * @type Boolean * @private */ var _isInit = false; // to avoid 'rebinds' /** * Request * @type String * @private */ var _request; /** * Forms Instance */ import Homepage from './Homepage.vue'; // ***************************** // ***** Private functions ***** // ***************************** /** * * Forms * * Create Forms * */ var _homepage = function () { // Create all requested instances new Vue({ el: '#homepage', mixins: [Homepage], }); }; // **************************** // ***** Public functions ***** // **************************** /** * start * * Starts the module * Inits private variables and executes specific logic needed for the module * to start. * * @required * @param request * @type array * * @public */ self.start = function() { if(!_isInit) { // Init Forms Component _homepage(); } }; This is the component that I am trying to mount: <template> <div > <h1>hi</h1> </div> </template> <script> export default { mounted() { console.log('Component mounted.') } } </script> <style> </style> Then I added to laravel mix the script file that goes in layouts.homepage blade after compile:.js('resources/assets/js/homepage/homepage.js', 'public/js/homepage'); const mix = require('laravel-mix'); mix.js('resources/js/app.js', 'public/js') .sass('resources/sass/app.scss', 'public/css') .js('resources/assets/js/homepage/homepage.js', 'public/js/homepage'); After running npm run production the file public/js/homepage/homepage.js is created. EDIT: I will paste the part of the code that is creating errors in the console: // ***** Private Variables ***** // ***************************** var self = undefined; var _isInit = false; var _homepage = function _homepage() { // Create all requested instances new Vue({ el: '#homepage', mixins: [_Homepage_vue__WEBPACK_IMPORTED_MODULE_0__["default"]] }); }; The code above generates the following error: Uncaught TypeError: Cannot set property 'start' of undefined at Module../resources/assets/js/homepage/components/homepage.js (homepage.js:12936) at webpack_require (homepage.js:20) at Object../resources/assets/js/homepage/homepage.js (homepage.js:12974) at webpack_require (homepage.js:20) at Object.1 (homepage.js:13007) at webpack_require (homepage.js:20) at homepage.js:84 at homepage.js:87 If I manually replace the var self = undefined; to var self=this in the public/js/homepage/homepage.js file the component is mounted and everything is fixed. the problem is that I have to make this correction everytime after npm run watch. I just don´t understand why this is happening. In the files assets/js/homepage/homepage.js and assets/js/homepage/component/homepage.js the code is var self = this. I dont understand why var self becomes undefined after npm run production in the file public/js/homepage/homepage.js. Does anyobody have any idea what might be happening? Thanks in advance A: You add your javascript before the element with id homepage exists. The default index.html by a Vue app looks like this: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width,initial-scale=1.0" /> <link rel="icon" href="favicon.ico" /> <title>Example App</title> </head> <body> <noscript> <strong> We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue. </strong> </noscript> <div id="app"></div> <!-- built files will be auto injected --> </body> </html> When the scripts are injected, they are put at the end of the body tag: <!-- ... --> <div id=app></div> <script src=js/chunk-vendors.feedbeef.js></script> <script src=js/app.baadf00d.js></script> </body> </html> You should try adding your scripts last and debugging from there: @extends('lib.master.main') @section('styles') @stop @section('title') - Homepage @stop @section('content') <div id="homepage"></div> @stop @section('scripts') <script src="{!! asset('js/homepage/homepage.js') !!}" type="text/javascript"></script> @stop
doc_23535085
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: 1. You might have mismatching versions of React and the renderer (such as React DOM) 2. You might be breaking the Rules of Hooks 3. You might have more than one copy of React in the same app See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem. I also did reset to the previous commit to discard all changes but the error still remains. this is my package.json file { "name": "client", "proxy": "http://127.0.0.1:5000", "version": "0.1.0", "private": true, "dependencies": { "@material-ui/core": "^4.11.3", "@material-ui/lab": "^4.0.0-alpha.57", "@testing-library/jest-dom": "^5.11.4", "@testing-library/react": "^11.1.0", "@testing-library/user-event": "^12.1.10", "axios": "^0.21.1", "bootstrap": "^4.6.0", "mdbreact": "^5.0.1", "react": "^17.0.1", "react-bootstrap": "^1.5.1", "react-dom": "^17.0.1", "react-redux": "^7.2.2", "react-router-dom": "^5.2.0", "react-scripts": "4.0.3", "redux": "^4.0.5", "redux-thunk": "^2.3.0", "uninstall-all-modules": "^1.0.5", "web-vitals": "^1.0.1" }, "scripts": { "start": "npm run watch:css && react-scripts start", "build": "npm run build:css && react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject", "build:css": "postcss src/assets/tailwind.css -o src/assets/main.css", "watch:css": "postcss src/assets/tailwind.css -o src/assets/main.css" }, "eslintConfig": { "extends": [ "react-app", "react-app/jest" ] }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] }, "devDependencies": { "autoprefixer": "^10.2.4", "postcss": "^8.2.6", "postcss-cli": "^8.3.1", "tailwindcss": "^2.0.3" } } All packages are up to date and we're working on this particular commit None of the other answers to similar errors seem to fix my issue and the worst thing is I am not even able to figure out where the root of the error is. If other info is required pls mention it in the comments. A: This issue doesn't always have to be related to the usage of hooks or any other react errors. This time it was occurring because of a module that I was using "mdbreact". For some reason, their website is down and if your project uses it, you'll end up getting this error.
doc_23535086
A: I was able to find this article on SVN site: https://subversion.apache.org/docs/release-notes/1.10#authzperf Wildcards can be used from version 1.10 and later.
doc_23535087
./elastic-mapreduce --create ... --args -d,DT=2013-01-26 'DT' shows up satisfactorily in my HadoopJarStep.Args array, so I try to include it in the HIVE script like so: ... tblproperties( 'dynamodb.table.name' = ${DT}, ... but I quickly get this: Parse Error: line 8:28 mismatched input '$' expecting StringLiteral near '=' in specifying key/value property How should I properly include the argument in my HIVE script? A: I'm not exactly sure why your current approach isn't working, but I've been successful with: ./elastic-mapreduce --create ... --args "-hiveconf,DT=2013-01-26" and in the hive script: tblproperties( "dynamodb.table.name" = "${hiveconf:DT}", ... ) Hope this helps.
doc_23535088
So far, it reads the first word and translates it, and I would like to continue onto the next word, and then the next, until no more words exist. I would then like to print the entire original translated input. def piglatin(): pig = 'ay' original = raw_input('Enter a phrase:').split(' ') if len(original[0]) > 0 and original[0].isalpha(): word = original[0].lower() first = word[0] if first == "a" or first == "e" or first == "i" or first == "o" or first =="u": new_word = word + pig print new_word else: new_word = word[1:] + word[0:1] + pig print new_word again = raw_input('Translate again? Y/N') print again if len(again) > 0 and again.isalpha(): second_word = again.lower() if second_word == "y": return piglatin() else: print "Okay Dokey!" else: print 'Letters only please!' return piglatin() Thanks! A: You want a for loop. A good starting point would be: for word in original:
doc_23535089
mydf1: id, f1, f2 ,f3 , ..., fn x1, 34, 45 ,32 , ..., 0 x1, 24, 55 ,1 , ..., 0 x1, 67, 43 ,5 , ..., 0 x2, 20, 89 ,4 , ..., 1 x2, 24, 50 ,1 , ..., 1 x3, 14, 15 ,1 , ..., 1 x3, 44, 25 ,11 , ..., 1 .. .. .. .. ... .. mydaf2: id, v1, v2 ,v3 , ...,vm x1, 74, 4 ,32 , ..., 32 x2, 64, 5 ,10 , ..., 56 x3, 4, 3 ,50 , ..., 78 Now, I want to create a new mydf_new consisting mydf2 and one extra column 'fn' taking from mydf1. As it can be seen from mydf1, fn is a feature that contains only 1 and 0 and it is identical for every id. For example, for x1, fn always is 0, for x2, fn always is 1 and so on. I want to add those 0 and 1 in the new data frame for the corresponding id, so my desired new data frame should be like this: mydaf_new: id, v1, v2, v3 , ..., vm, fn x1, 74, 4 , 32 , ..., 32, 0 x2, 64, 5 , 10 , ..., 56, 1 x3, 4, 3 , 50 , ..., 78, 1 Any idea that I fix this problem? A: Try this: df = mydf1[['id', 'fn']] mydf_new = mydf2.merge(df, how='left', on='id')
doc_23535090
I've looked through other posts but can't seem to figure out what to do. I would assume from the error I need to start WMI on my AWS RDS Windows server, but not sure if that's correct or how to do that. Would appreciate any help. Thanks.
doc_23535091
-(IBAction)RecButtonPress:(id)sender { NSLog(@"Song name:%@",mySongname); NSMutableDictionary* recordSetting = [[NSMutableDictionary alloc] init]; [recordSetting setValue :[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey]; [recordSetting setValue:[NSNumber numberWithFloat:44000.0] forKey:AVSampleRateKey]; [recordSetting setValue:[NSNumber numberWithInt: 1] forKey:AVNumberOfChannelsKey]; [recordSetting setValue: [NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey]; [recordSetting setValue: [NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey]; [recordSetting setValue: [NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey]; NSDate* now = [NSDate date]; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"dd:MMM:YY_hh:mm:ss a"]; NSString *file= [dateFormatter stringFromDate:now]; NSString *fina=[file stringByAppendingString:mySongname]; NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *docsDir = [dirPaths objectAtIndex:0]; NSString *soundFilePath = [docsDir stringByAppendingPathComponent:@"MyRecordings"]; if (![[NSFileManager defaultManager] fileExistsAtPath:soundFilePath]) [[NSFileManager defaultManager] createDirectoryAtPath:soundFilePath withIntermediateDirectories:NO attributes:nil error:nil]; soundFilePath = [soundFilePath stringByAppendingPathComponent:fina]; recordedTmpFile = [NSURL fileURLWithPath:soundFilePath]; NSLog(@"Uf:%@",recordedTmpFile); recorder = [[ AVAudioRecorder alloc] initWithURL:recordedTmpFile settings:recordSetting error:&error]; [recorder setDelegate:self]; [recorder prepareToRecord]; [recorder record]; [recordSetting release]; [dateFormatter release]; } Now After Saving Recording When i goes to SaveRecording Class Where actually i Show all these Recording in Tableview.here my Code is - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *documentPath = [documentsDirectory stringByAppendingPathComponent:@"MyRecordings"]; directoryContent = [[NSFileManager defaultManager] directoryContentsAtPath:documentPath]; NSLog(@"file found %i",[directoryContent count]); NSLog(@"arraydata: %@", directoryContent ); [directoryContent retain]; [self.tableView reloadData]; } And After That i Assign "directoryContent" Which is my NSMutablArray To UITableview. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [directoryContent count]; } ////////////////////////////////////////////////////////////////////////////////////////////// - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; static NSInteger StateTag = 1; static NSInteger CapitalTag = 2; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; UILabel *capitalLabel = [[UILabel alloc] initWithFrame:CGRectMake(2, 2, 120, 20)]; //capitalLabel.text=@"mydata"; capitalLabel.backgroundColor=[UIColor redColor]; capitalLabel.tag = CapitalTag; [capitalLabel setFont:[UIFont systemFontOfSize:9]]; [cell.contentView addSubview:capitalLabel]; [capitalLabel release]; UILabel *stateLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 22, 310, 20)]; stateLabel.tag = StateTag; [stateLabel setFont:[UIFont systemFontOfSize:14]]; stateLabel.adjustsFontSizeToFitWidth=YES; [cell.contentView addSubview:stateLabel]; [stateLabel release]; } UILabel * stateLabel = (UILabel *) [cell.contentView viewWithTag:StateTag]; //UILabel * capitalLabel = (UILabel *) [cell.contentView viewWithTag:CapitalTag]; stateLabel.text = [directoryContent objectAtIndex:indexPath.row]; //capitalLabel.text = [datesaving objectAtIndex:indexPath.row]; return cell; } And Finaly my UITableView is Look like this Below ScreenShot My All this Brief discussion purpose is that as my Screen shot show That UITableview Cell Show my Text and Current date and Time.Now i want to Split this directoryContent Array data into Two prats.The part which Consist of Current date and time i want to Assign it capitalLabel which is redpart of Cell in UITableview And Text to stateLabel Which is Below part of Cell in UITableview.Any help will be Appriated.Thanks in Advance. A: Hi Lena you can try the following things 1) Array of Dictionary Save your Date and Song name separately in a Dictionary NSDictionary *myData = [NSDictionary dictionaryWithObjectsAndKeys:myDateObj,@"SongDate",mySongName,@"SongName", nil]; [myMutableArray addObject:myData]//myMutableArray is a NSMutableArray; Now you can use it as follows NSDictionary *dict = [directoryContent objectAtIndex:indexPath.row]; stateLabel.text = [dict objectForKey:@"SongName"]; capitalLabel.text = [dict objectForKey:@"SongDate"]; OR 2) Your can do a little trick :) NSString *fina=[file stringByAppendingFormat:@"+%@",mySongname]; NSArray *Array = [fina componentsSeparatedByString:@"+"]; capitalLabel.text = [Array objectAtIndex:0]; stateLabel.text = [Array objectAtIndex:1]; Here while appending you can use format and add any special character which you can use later to split the string. Hope this will help you in any ways :) A: First you need to append your string like this NSString *file3 = [file stringByAppendingString:@"+"]; NSString *fina= [file3 stringByAppendingString:mySongname]; after that you need to seperate it like NSArray *Array = [str componentsSeparatedByString:@"+"]; NSLog(@"myindex0str:%@",[Array objectAtIndex:0]); NSLog(@"myindex1str:%@",[Array objectAtIndex:1]); so you will get the both time and songname individually.
doc_23535092
HashMap<String, StreamSubscription<Event>> = subscriptions But when i am filling values, it show for me, that types doesn't match. Error tells that Argument of type StreamSubscription<Event> can't be assigned to parameter of type StreamSubscription<Event> Function(). When i am creating dirrectly variable like this: StreamSubscription<Event> e = subscription.eventStream.listen((event) { print(event.arguments[0]); }); It shows that type is correct. So how should i declare hashmap of HashMap<String, StreamSubscription<Event>>, if _subscriptions.putIfAbsent(uri, e); doesn't work.
doc_23535093
scipy.stats.norm.cdf(80,100,10) Are the values 100 , 10 the mean and standard deviation respectively? 80 is a continuous random variable. Reading the documentation the meaning of these values is not described : https://docs.scipy.org/doc/scipy-0.13.0/reference/generated/scipy.stats.norm.html A: Based on the docs: cdf(x, loc=0, scale=1) is the Cumulative density function. and: The location (loc) keyword specifies the mean. The scale (scale) keyword specifies the standard deviation. So mean 100 and standard deviation 80.
doc_23535094
private String label; foo(String whereto){ label = whereto; } public foo bar(String name){ return new foo(name); } } can any one explain , why they have used class name as reference to method name & what's it purpose using it ? A: The return type foo is used to return a new object of type foo out of a given object of type foo. A prominent example is BigDecimal representing an immutable value object and where the add operation returns a newly constructed BigDecimal representing the old value plus the new value. A: public class foo{ // class foo public foo bar(String name){ // method bar System.out.print(name) // you need to return instance of foo return new foo(name); } } When you call the method bar that will return an instance of foo. That's why return type of bar is foo. Further, use better Java naming while coding public class Foo{ // uppercase start for class name public foo bar(String name){ // lowercase start for method name System.out.print(name) return new FOO(name); } } For your edit: foo(String whereto){ // this is a constructor for foo class label = whereto; } It means if you want to create an instance of foo. you should do as follows foo f=new foo("a"); // constructor of foo accepting String; A: They haven't used class name as reference. Return type of bar method is of type foo.class. That means bar() method is returning object(or say reference to an object of type foo). Hope this helps. A: Class name is not exactly a reference here. It is the return type of method, as they call it in java. Also, your method will throw a compilation error because it does not return a foo as stated in the signature. It can be corrected as follows. public class foo{ public foo bar(String name){ System.out.print(name); return new foo(); } }
doc_23535095
Here is strace: chilkat/chilkat-9.5.0-x86_64-linux-gcc/lib/glibc-hwcaps/x86-64-v3/libdl.so.2", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory) A: libdl.so and libpthread.so are link editor input files, they are not used at run time. Instead, the sonames libdl.so.2 and libpthread.so.0 are used for run-time dynamic linking. Starting with glibc 2.34, explicitly linking against libdl or libpthread is no longer needed (as all functions are provided by libc directly). Therefore, libdl.so and libpthread.so have been replaced by empty static archives libdl.a and libpthread.a, so that the linker arguments -ldl and -lpthread keep working.
doc_23535096
I have the Bearer Token. But I can't seem to figure out how to add it to the Metadata Call. I tried something like this. But it did not add a header to the metadata call: var ajaxAdapter: any = breeze.config.getAdapterInstance('ajax'); ajaxAdapter.defaultSettings = { headers: { "X-Test-Header": "foo2" } } Does the fetchMetadata use a different system from the ajax adapter? How can I add a header to the Fetch Metadata call? A: Turns out I was using the Fetch API. So I had to do it that way. Here is what my setup looks like: setupFetchClient() { let httpClient = new HttpClient(); httpClient.configure(config => { config.withDefaults({ headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', } }) .withInterceptor({ request(request: Request) { let accessToken = getAccessToken(); request.headers.append('Authorization', 'Bearer ' + accessToken); return request; }, responseError(error) { return error; } }) .useStandardConfiguration(); }); // Aurelia Specific Code. Container.instance.registerInstance(HttpClient, httpClient); }
doc_23535097
javascript:alert(Object.defineProperty); I need to know however if it'll work on the iPad. Additional information about getter/setter support on the iPad is appreciated. A: I've only tested 4.3, but it looks like it is supported for JS objects, but not DOM objects... just to be different from IE8 which is the opposite. If you have access to OSX, I recommend downloading XCode --it comes with a useful iOS emulator for the various devices. Also, this link might be useful, as it contains a table of ECMAScript 5 features, even though it does not mention the DOM restriction. http://davidbcalhoun.com/2011/new-mobile-safari-stuff-in-ios5-position-fixed-overflow-scroll-new-input-type-support-web-workers-ecmascript-5
doc_23535098
when I set overlay.Location = new Point(this.Location.X, this.Location.Y + (Height - ClientSize.Height)); when I set overlay.Location = new Point(this.Location.X + 9, this.Location.Y + (Height - ClientSize.Height) - 9); Here's the code. form1 public partial class Form1 : Form { bool isOverlayGenerated = false; TestForm overlay = new TestForm(); public Form1() { InitializeComponent(); VisibleChanged += Form1_VisibleChanged; overlay.Size = ClientSize; overlay.ShowOnMeMo += () => { overlay.memoEdit1.EditValue = $"form1: ({Location.X}, {Location.Y})"; overlay.memoEdit1.EditValue += Environment.NewLine + $"form2: ({overlay.Location.X}, {overlay.Location.Y})"; }; overlay.Owner = this; } private void Form1_VisibleChanged(object sender, EventArgs e) { if (!isOverlayGenerated) { overlay.Location = new Point(this.Location.X, this.Location.Y + (Height - ClientSize.Height)); //overlay.Location = new Point(this.Location.X + 9, this.Location.Y + (Height - ClientSize.Height) - 9); isOverlayGenerated = true; overlay.Show(); } } } form2 public partial class TestForm : DevExpress.XtraEditors.XtraForm { public delegate void DoAThing(); public event DoAThing ShowOnMeMo; public TestForm() { InitializeComponent(); } private void simpleButton1_MouseClick(object sender, MouseEventArgs e) { ShowOnMeMo?.Invoke(); } } A: Thanks to @Dai 's answer, I find a way to solve this problem. int nonclientWidth = Bounds.Width - ClientSize.Width, nonclientHeight = (Bounds.Height - SystemInformation.CaptionHeight) - ClientSize.Height; overlay.Location = new Point(this.Location.X + nonclientWidth / 2, this.Location.Y + SystemInformation.CaptionHeight + nonclientHeight / 2);
doc_23535099
Specifying a value for the Completed XAML attribute does not compile as the attribute is defined inside a template so there is no specific method to wire up to. So I will need to use code behind to wire up the event manually. To this end I have looked at the application with Snoop to try to find where in the logical or visual tree the inflated template Storyboards end up. So far all I can see is a ContentControl created for each item, with its ContentTemplate set. The Content property of each ContentControl is set to its corresponding data object. The ContentTemplate property contains the Triggers collection which contain the EnterActions and ultimately the Storyboard. My question is, do all the items share a single template instance for their ContentTemplate property, or do they each get their own copy? If they share one, then where are the inflated triggers and storyboards created? I've extracted the pertinent parts of my XAML: <Style TargetType="{x:Type m:MyControl}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type m:MyControl}"> <Grid Name="ControlRoot" DataContext="{Binding RelativeSource={RelativeSource TemplatedParent}}"> <!-- ... --> <ItemsControl ItemsSource="..."> <ItemsControl.ItemTemplate> <DataTemplate DataType="{x:Type m:MyDataType}"> <Grid> <Ellipse Name="IconHighlight1" Fill="{DynamicResource GoldRadialFade}" Width="70" Height="70" StrokeThickness="0" Opacity="0"/> </Grid> <DataTemplate.Triggers> <DataTrigger Binding="{Binding Highlighted}" Value="True"> <DataTrigger.EnterActions> <BeginStoryboard HandoffBehavior="Compose"> <Storyboard Name="ConnectToMe" Duration="0:0:2.5" FillBehavior="Stop"> <DoubleAnimation To="400" Duration="0:0:1.5" Storyboard.TargetName="IconHighlight1" Storyboard.TargetProperty="Height" FillBehavior="Stop" /> </Storyboard> </BeginStoryboard> </DataTrigger.EnterActions> </DataTrigger> </DataTemplate.Triggers> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> A: In such cases, I'd normally prefer to have a bool in the DataContext of the Item that your Storyboard is applying to and say call it AnimationCompleted Now by modifying your Storyboard to <Storyboard x:Key="ConnectToMe" Duration="0:0:2.5" FillBehavior="Stop"> <DoubleAnimation To="400" Duration="0:0:1.5" Storyboard.TargetName="IconHighlight1" Storyboard.TargetProperty="Height" FillBehavior="Stop" /> <BooleanAnimationUsingKeyFrames Storyboard.TargetProperty="DataContext.AnimationCompleted" FillBehavior="HoldEnd"> <DiscreteBooleanKeyFrame Value="False" KeyTime="0:0:0" /> </BooleanAnimationUsingKeyFrames> <BooleanAnimationUsingKeyFrames Storyboard.TargetProperty="DataContext.AnimationCompleted" FillBehavior="HoldEnd"> <DiscreteBooleanKeyFrame Value="True" KeyTime="0:0:2.5" /> </BooleanAnimationUsingKeyFrames> </Storyboard> We toggle the bool AnimationCompleted to true at the end point of the animation. Hence in the property setter of AnimationCompleted check if the incoming value is True and trigger your corresponding function/method from there