id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_800
<div class="open"></div> <div class="open"></div> <div class="open"></div> <div class="open"></div> I'm looking for a way to get get a position of an element (eg. If the element is the first instance of, assign id="1" if element is the second instance of, assign id="2". I'm currently using the following jquery, but am stuck, as Im not sure where to go from here. $(document).ready(function () { var numDialogs = $('.open').length; }); Any suggestions? A: Just use: $('div.open').prop('id', function(i){ return 'openElement' + (i + 1); }); JS Fiddle demo. I've deliberately added a prefix string because while numerical ids are valid under HTML5, they remain invalid under HTML4, and are difficult to select using CSS selectors. References: * *prop(). A: Mark, you can target the element and then add an attribute like so: $('.open').attr('id', numDialogs); This will give it all 4's in this case, but I'll leave you to wrestle with the actual logic to implement the right numbers. Good luck.
doc_801
Referring to this code for example: https://github.com/benjaminmbrown/real-time-data-viz-d3-crossfilter-websocket-tutorial/blob/master/rt-data-viz/websocket_server.py Can someone guide me on how can I post message on websocket. Basically I have tornado API where if user do a curl request I would like to log that message to websocket A: You can do it by creating a registry of all active websockets and use it to send messages on a certain event. class WebsocketRegistry: def __init__(self): self._active_websockets = [] def add_listener(self, listener): self._active_websockets.append(listener) def remove_listener(self, listener): self._active_websockets.remove(listener) def send_messages(self, msg_txt): for ws in self._active_websockets: ws.write_message(msg_txt) registry = WebsocketRegistry() class WSHandler(tornado.websocket.WebSocketHandler): def open(self, *args, **kwargs): super(WSHandler, self).open(*args, **kwargs) registry.add_listener(self) def on_close(self): super(WSHandler, self).on_close() registry.remove_listener(self) P.S. Take note that if you plan to scale your app with 2+ instances, this won't work and you would have to use, for example, a message queue (RabbitMQ is good) to deliver events to the all opened websockets. But overall approach would be the same: MQ would be a registry and websockets subscribe on messages (and unsubscribe on closing) on connection.
doc_802
Using ruamel.yaml: yaml = YAML(typ="safe") yaml.version = (1, 1) yaml.default_flow_style = None yaml.dump(stuff, sys.stdout) With a python dict stuff containing: { "key": "Y" } outputs %YAML 1.1 --- {key: Y} in the output yaml. In my actual code, I'm piping this into helm, which is backward compatible with yaml 1.1, meaning that I need to have anything that might be a boolean scalar quoted. What am I missing here? E: because I am a big dummy and forgot to update everything after trying a min repro - here's the REPL output: >>> from ruamel.yaml import YAML >>> yaml = YAML() >>> yaml.version = (1,1) >>> yaml.default_flow_style = None >>> stuff = { ... "key": "T" ... } >>> import sys >>> yaml.dump(stuff, sys.stdout) %YAML 1.1 --- {key: T} >>> E again: I am shamed. T isn't a scalar boolean, I was using the wrong test subject. This is not a place of honour. A: If your Python dict really consists of a single key value pair, mapping of a string to a string, as you indicate, ruamel.yaml will not dump the output you display with or without typ='safe') import sys import ruamel.yaml data = { "key": "Y" } yaml = ruamel.yaml.YAML(typ='safe') yaml.version = (1, 1) yaml.default_flow_style = None yaml.dump(data, sys.stdout) yaml = ruamel.yaml.YAML() yaml.version = (1, 1) yaml.default_flow_style = None yaml.dump(data, sys.stdout) which gives: %YAML 1.1 --- {key: 'Y'} %YAML 1.1 --- {key: 'Y'} Not even changing the value to a boolean gets your result import sys import ruamel.yaml data = dict(key=True) yaml = ruamel.yaml.YAML(typ='safe') yaml.version = (1, 1) yaml.default_flow_style = None yaml.dump(data, sys.stdout) yaml = ruamel.yaml.YAML() yaml.version = (1, 1) yaml.default_flow_style = None yaml.dump(data, sys.stdout) which gives: %YAML 1.1 --- {key: true} %YAML 1.1 --- {key: true} Always, always, always provide a minimal program that can be cut-and-pasted to get the results that you are seeing. That is how I produce my answers ( the answers are actually comming from a multidocument YAML file processed by (ryd)[https://pypi.org/project/ryd/)), and that is how you should consider providing your questions.
doc_803
from __future__ import print_function from os.path import expanduser, join, abspath from pyspark.sql import SparkSession from pyspark.sql import Row if __name__ == "__main__": # warehouse_location points to the default location for managed databases and tables warehouse_location = abspath('spark-warehouse') spark = SparkSession \ .builder \ .appName("Python Spark SQL Hive integration example") \ .config("spark.sql.warehouse.dir", warehouse_location) \ .enableHiveSupport() \ .getOrCreate() spark.sql("CREATE TABLE IF NOT EXISTS src (key INT, value STRING) USING hive") spark.sql("LOAD DATA LOCAL INPATH 'examples/src/main/resources/kv1.txt' INTO TABLE src") spark.sql("SELECT * FROM src").show() spark.sql("SELECT COUNT(*) FROM src").show() sqlDF = spark.sql("SELECT key, value FROM src WHERE key < 10 ORDER BY key") stringsDS = sqlDF.rdd.map(lambda row: "Key: %d, Value: %s" % (row.key, row.value)) for record in stringsDS.collect(): print(record) Record = Row("key", "value") recordsDF = spark.createDataFrame([Record(i, "val_" + str(i)) for i in range(1, 101)]) recordsDF.createOrReplaceTempView("records") spark.sql("SELECT * FROM records r JOIN src s ON r.key = s.key").show() spark.stop() After run i get the error: Py4JJavaError: An error occurred while calling o28.sql.: java.lang.NoClassDefFoundError: org/apache/spark/internal/Logging$class The full error: Traceback (most recent call last): File "<ipython-input-2-c54a2a0ac76b>", line 1, in <module> runfile('C:/Users/SUBD-PodpruzhnikovIA/Desktop/test_spark_5.py', wdir='C:/Users/SUBD-PodpruzhnikovIA/Desktop') File "C:\Users\SUBD-PodpruzhnikovIA\Anaconda3\envs\py36\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile execfile(filename, namespace) File "C:\Users\SUBD-PodpruzhnikovIA\Anaconda3\envs\py36\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "C:/Users/SUBD-PodpruzhnikovIA/Desktop/test_spark_5.py", line 31, in <module> spark.sql("CREATE TABLE IF NOT EXISTS src (key INT, value STRING) USING hive") File "C:\Users\SUBD-PodpruzhnikovIA\Desktop\pyspark\sql\session.py", line 767, in sql return DataFrame(self._jsparkSession.sql(sqlQuery), self._wrapped) File "C:\Users\SUBD-PodpruzhnikovIA\Desktop\py4j\java_gateway.py", line 1257, in __call__ answer, self.gateway_client, self.target_id, self.name) File "C:\Users\SUBD-PodpruzhnikovIA\Desktop\pyspark\sql\utils.py", line 63, in deco return f(*a, **kw) File "C:\Users\SUBD-PodpruzhnikovIA\Desktop\py4j\protocol.py", line 328, in get_return_value format(target_id, ".", name), value) Py4JJavaError: An error occurred while calling o28.sql. : java.lang.NoClassDefFoundError: org/apache/spark/internal/Logging$class at org.apache.spark.sql.hive.HiveMetastoreCatalog.<init>(HiveMetastoreCatalog.scala:41) at org.apache.spark.sql.hive.HiveSessionStateBuilder.catalog$lzycompute(HiveSessionStateBuilder.scala:56) at org.apache.spark.sql.hive.HiveSessionStateBuilder.catalog(HiveSessionStateBuilder.scala:52) at org.apache.spark.sql.hive.HiveSessionStateBuilder$$anon$1.<init>(HiveSessionStateBuilder.scala:69) at org.apache.spark.sql.hive.HiveSessionStateBuilder.analyzer(HiveSessionStateBuilder.scala:69) at org.apache.spark.sql.internal.BaseSessionStateBuilder.$anonfun$build$2(BaseSessionStateBuilder.scala:293) at org.apache.spark.sql.internal.SessionState.analyzer$lzycompute(SessionState.scala:79) at org.apache.spark.sql.internal.SessionState.analyzer(SessionState.scala:79) at org.apache.spark.sql.execution.QueryExecution.analyzed$lzycompute(QueryExecution.scala:57) at org.apache.spark.sql.execution.QueryExecution.analyzed(QueryExecution.scala:55) at org.apache.spark.sql.execution.QueryExecution.assertAnalyzed(QueryExecution.scala:47) at org.apache.spark.sql.Dataset$.ofRows(Dataset.scala:79) at org.apache.spark.sql.SparkSession.sql(SparkSession.scala:642) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244) at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357) at py4j.Gateway.invoke(Gateway.java:282) at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132) at py4j.commands.CallCommand.execute(CallCommand.java:79) at py4j.GatewayConnection.run(GatewayConnection.java:238) at java.lang.Thread.run(Thread.java:748) Caused by: java.lang.ClassNotFoundException: org.apache.spark.internal.Logging$class at java.net.URLClassLoader.findClass(URLClassLoader.java:382) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) 24 more I use Spark 2.4.0, pyspark 2.4.0, java 8, python 3.6. master=local. Any ideas? I would really appreciate) UPD: if use spark 2.3.2 (local), pyspark 2.3.2, then first part of code work normal, so there is CREATE TABLE, show it and show COUNT. After that it fail with ModuleNotFoundError: No module named 'resource'. It is a old error, it fixed in older versions spark. UPD2: i add the code, which can ran on yarn for Jacek Laskowski from os.path import expanduser, join, abspath from pyspark.sql import SparkSession, SQLContext from pyspark import SparkContext, SparkConf from pyspark.sql import Row import os from operator import add from pyspark.java_gateway import launch_gateway os.environ["HADOOP_USER_NAME"] = "administrator" SparkContext._gateway=launch_gateway() SparkContext._jvm = SparkContext._gateway.jvm os.environ["PYSPARK_PYTHON"]='/opt/pypy3.6-v7.1.1-linux64/bin/ipython3' conf=SparkConf() conf.setMaster('yarn-client') conf.setAppName('PythonSparkintegrationexampleYARN') conf.set("spark.driver.memory", "16G") conf.set("spark.hadoop.yarn.resourcemanager.hostname", "hadoop-manager1.some-site.ru") conf.set("spark.hadoop.yarn.resourcemanager.address", "hadoop-manager1.some-site.ru:8032") conf.set("spark.yarn.access.hadoopFileSystems", "hdfs://hadoop-manager1.some-site.ru:8020") conf.set("spark.yarn.stagingDir", "hdfs://hadoop-manager1.some-site.ru:8020/user/administrator/stagingDir") conf.set("spark.executor.userClassPathFirst", "true") conf.set("spark.driver.userClassPathFirst", "true") conf.set("spark.eventLog.enabled", "true") conf.set("spark.eventLog.dir", "hdfs://hadoop-manager1.some-site.ru:8020/user/spark/spark2ApplicationHistory") conf.set("spark.history.fs.logDirectory", "hdfs://hadoop-manager1.some-site.ru:8020/user/spark/spark2ApplicationHistory") conf.set("spark.dynamicAllocation.enabled", "true") conf.set("spark.shuffle.service.enabled", "true") conf.set("spark.hadoop.validateOutputSpecs", "false") conf.set("spark.executor.memoryOverhead", "600") conf.set("spark.executor.memory", "4g") conf.set("spark.network.timeout", "60000") conf.set("spark.dynamicAllocation.maxExecutors", "400") conf.set("spark.yarn.appMasterEnv.HADOOP_USER_NAME", "administrator") sc=SparkContext(conf=conf) file=sc.textFile(HDFS_URI+curr_file) words = file.flatMap(lambda line: line.split(" ")) dataColl = words.countByValue() for word, count in dataColl.items(): print("{} : {} ".format(word, count )) sc.stop() if i try to use hive, i add: warehouse_location= abspath('hdfs://hadoop-manager1.some-site.ru:8020/user/hive/warehouse') ss=SparkSession(sc).builder.appName('SparkSession_Hive_reader_2')\ .config("spark.sql.warehouse.dir", warehouse_location)\ .enableHiveSupport().getOrCreate() ss.sql("CREATE TABLE IF NOT EXISTS src(key INT, value STRING) USING hive") ss.sql("LOAD DATA LOCAL INPATH 'C:/Spark/spark-2.4.0-bin-without-hadoop-scala-2.12-2/examples/src/main/resources/kv1.txt' INTO TABLE src") ss.sql("SELECT * FROM src").show() With the last add i have the following error: AnalysisException Traceback (most recent call last) <ipython-input-17-6c223a8545bf> in <module> ----> 1 ss.sql("CREATE TABLE IF NOT EXISTS src(key INT, value STRING) USING hive") 2 ss.sql("LOAD DATA LOCAL INPATH 'C:/Spark/spark-2.4.0-bin-without-hadoop-scala-2.12-2/examples/src/main/resources/kv1.txt' INTO TABLE src") 3 4 # Queries are expressed in HiveQL 5 ss.sql("SELECT * FROM src").show() ~\Anaconda3\envs\py36\lib\site-packages\pyspark\sql\session.py in sql(self, sqlQuery) 768 [Row(f1=1, f2=u'row1'), Row(f1=2, f2=u'row2'), Row(f1=3, f2=u'row3')] 769 """ --> 770 return DataFrame(self._jsparkSession.sql(sqlQuery), self._wrapped) 771 772 @since(2.0) ~\Anaconda3\envs\py36\lib\site-packages\py4j\java_gateway.py in __call__(self, *args) 1255 answer = self.gateway_client.send_command(command) 1256 return_value = get_return_value( -> 1257 answer, self.gateway_client, self.target_id, self.name) 1258 1259 for temp_arg in temp_args: ~\Anaconda3\envs\py36\lib\site-packages\pyspark\sql\utils.py in deco(*a, **kw) 67 e.java_exception.getStackTrace())) 68 if s.startswith('org.apache.spark.sql.AnalysisException: '): ---> 69 raise AnalysisException(s.split(': ', 1)[1], stackTrace) 70 if s.startswith('org.apache.spark.sql.catalyst.analysis'): 71 raise AnalysisException(s.split(': ', 1)[1], stackTrace) AnalysisException: "Hive support is required to CREATE Hive TABLE (AS SELECT);;\n'CreateTable `src`, Ignore\n" ```
doc_804
My jar includes a dependency on the Amazon AWS SDK, so I'm assuming the error is generated from that. To this point, I've found a solution as described here: Duplicate Zip Entry after Gradle Plugin v0.13.1 which describes my exact problem, but only in the context of Android Gradle. Specifically, the solution was: android.packagingOptions { pickFirst 'META-INF/LICENSE.txt' } Of course, such an option is noticeably absent in Gradle. My question: Is there a straightforward way to address this issue in the build code rather than having to manually look for and remove duplicate META-INF/LICENSE occurrences? For completeness, here's the error gradle assemble generates: Caused by: java.util.zip.ZipException: duplicate entry: META-INF/LICENSE at com.sun.javafx.tools.packager.PackagerLib.copyFromOtherJar(PackagerLib.java:1409) at com.sun.javafx.tools.packager.PackagerLib.jar(PackagerLib.java:1366) at com.sun.javafx.tools.packager.PackagerLib.packageAsJar(PackagerLib.java:288) ... 54 more And my gradle.build script: apply from: 'javafx.plugin' repositories { mavenCentral() } dependencies { compile ('com.amazonaws:aws-java-sdk:1.9.13') { exclude group: 'commons-io', module: 'commons-io' } testCompile group: 'junit', name: 'junit', version: '4.+' } jar { from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } } manifest { attributes 'Main-Class': 'com.buddyware.treefrog.Main' } } A: Based on Mark Vieira's suggestion and a little digging for live examples, I modified my build.gradle file's jar task to read as follows: jar { duplicatesStrategy(DuplicatesStrategy.EXCLUDE) from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } } manifest { attributes 'Main-Class': 'com.buddyware.treefrog.Main' } } Running 'gradle assemble' succeeded without a complaint!
doc_805
To do so, I have the following environment: cargo version cargo 1.67.0-nightly (f6e737b1e 2022-12-02) rustc --version rustc 1.67.0-nightly (01fbc5ae7 2022-12-07) export AARCH64_SYSROOT=/path/to/aarch64/root export PKG_CONFIG_SYSROOT_DIR=$AARCH64_SYSROOT export RUSTFLAGS="-C link-args=-fuse-ld=lld -C link-args=-L$AARCH64_SYSROOT/usr/lib -C link-args=-L$AARCH64_SYSROOT/lib -C link-args=-L$AARCH64_SYSROOT/usr/local/lib -C link-args=--sysroot=$AARCH64_SYSROOT" The command I run to build is the following, and I get this error on FreeBSD 13.1: cargo build -Z build-std --release --target aarch64-unknown-freebsd ld.lld: error: /usr/local/lib/libssl.so is incompatible with $AARCH64_SYSROOT/usr/lib/Scrt1.o ld.lld: error: /usr/local/lib/libcrypto.so is incompatible with $AARCH64_SYSROOT/usr/lib/Scrt1.o ld.lld: error: /usr/local/lib/libcurl.so is incompatible with $AARCH64_SYSROOT/usr/lib/Scrt1.o cc: error: linker command failed with exit code 1 (use -v to see invocation) It looks like the linker is trying to link with my host libraries even though I specify the link paths in RUSTFLAGS. I ran cargo with the --verbose flags on both machines and saw that -L native=/usr/local/lib appears on FreeBSD 13.1 but -L native=$AARCH64_SYSROOT/usr/local/lib is shown on FreeBSD 12.1 so I think this is a pretty big clue but I might be completly wrong. Why does my host libs path appear on FreeBSD13 but not on FreeBSD12 ? How can I remove this default flags when running my cargo build command ? I tried invoking rustc directly with the command shown by cargo build --verbose (removing the -L native=/usr/local/lib option) which seems to work. However this is not practical as my crate has many dependencies and building properly without using cargo would be a mess...
doc_806
void* quad(void* argis){ struct args* arg=argis; double m=(arg->l+arg->r)/2; double fm=func(m); double larea=(arg->fl+fm)*(m-arg->l)/2; double rarea = (fm+arg->fr)*(arg->r-m)/2; struct args* arg1 = (struct args*)malloc(sizeof(struct args)); arg1->l=arg->l; arg1->r=m; arg1->fl=arg->fl; arg1->fr=fm; arg1->area=larea; struct args* arg2 = (struct args*)malloc(sizeof(struct args)); arg2->l=m; arg2->r=arg->r; arg2->fl=fm; arg2->fr=arg->fl; arg2->area=rarea; if(fabs((larea+rarea)-arg->area)>error){ if(threads<=1){ void* p1=quad(arg1); void* p2=quad(arg2); larea=*((double*)p1); rarea=*((double*)p2); free(p1); free(p2); } else{ pthread_t thread1, thread2; pthread_mutex_lock(&lock1); threads-=2; pthread_mutex_unlock(&lock1); pthread_create(&thread1, NULL, &quad, (void*)arg1); pthread_create(&thread2, NULL, &quad, (void*)arg2); void* ptr1; void* ptr2; pthread_join(thread1,&ptr1); pthread_join(thread2,&ptr2); larea=*(double*)ptr1; rarea=*(double*)ptr2; } } free(arg1); free(arg2); double ret= (larea+rarea); double* poin=(double*)malloc(sizeof(double)); *poin=ret; return poin; } Now when I set the threads variable to 2 it should create two new threads that does the recursion concurrently, I think this does just that, I get a sane estimation of Pi however it's not any faster than just running on one thread (setting threads to 1), in fact it's somewhat slower. Why isn't it twice as fast? Any help sorting this out would be greatly appreciated. Thanks. A: Is this a sufficiently large problem for multithreading? Maybe the overhead of creating new threads and managing locks is greater than the cost of solving the problem with a single thread. A: Your processor may have multiple cores, but what about your floating point coprocessor? It probably does not, and will block each thread while the other thread is performing FPU computations. Also, see this article: Workloads that do not benefit much from simultaneous multithreading are those in which the majority of individual software threads use a large amount of any resource in the processor or memory. For example, workloads that are floating-point intensive are likely to gain little from simultaneous multithreading and are the ones most likely to lose performance. These workloads heavily use either the floating-point units or the memory bandwidth. Workloads with low CPI and low cache miss rates might see a some small benefit. Source
doc_807
I had, according to Pagespeed Insights (https://developers.google.com/speed/pagespeed/insights/?) a Server Response time of 1.7s. After some work, Lighthouse (embedded in Chrome) gives me a Server Response time of 200ms, my page is noticeably faster. But Pagespeed insights still gives me results in the 1.5s range. Which one should I trust? A: Google PageSpeed uses a “combo” of lab and real-world data, whereas Lighthouse uses lab data only to build its report. Since lighthouse is integrated into PSI for sake of consistency you should trust PSI over just lab data.
doc_808
EXEC USP_one EXEC USP_two EXEC USP_three I want to execute these 3 or more stored procedures. I could do this with a cursor. However is there an easier way to solve this? A: You can try this: DECLARE @SQL NVARCHAR(MAX) = ''; SELECT @SQL = @SQL + YourColumn + '; ' FROM YourTable; EXECUTE sp_executesql @SQL; Where the column YourColumn contains the SQL command. A: Declare a variable and store all the values(exec procedurename) inside the table into that variable appended with space at the end and execute the variable. Try this declare @exec_proc nvarchar(max)='' select @exec_proc += proc_name+' ' from dbo.usp_table -- print @exec_proc exec sp_executesql @exec_proc Note : This will not work if your procedure accepts parameters
doc_809
* *Use a timer to clear the expire data *Call the clean function in Add and Get So, which implementation is better? A: Do the simplest thing that could possibly work. For example, assuming your cache is a fixed sized, call clean when adding values. Adding values changes the number of cached items, but getting values does not. Also, the idea behind a cache is that getting is done more frequently than adding and you want to minimize the number of times you call clean. Using a timer means threads and complexity. Prove that the simplest implementation won't work before trying something more complicated. Unless you are writing this as a programming challenge, the best thing to do is use a mature and popular cache that someone has already written. There are many places to go wrong implementing a cache. For instance, I work in Java. If I need a simple cache I use Guava's implementation. I would not attempt to write my own cache. Lastly, even if you are writing this as a programming challenge, I suggest finding an existing LRU cache algorithm and implementing in code. When that works, you are free to tweak the code to your liking.
doc_810
if ($session->has("myVar")) { $myVar = session->get("myVar"); /* do something */ } But, I read the code of session and : /** * Returns an attribute. * * @param string $name The attribute name * @param mixed $default The default value if not found. * * @return mixed * * @api */ public function get($name, $default = null); So, if the session attribute is not find, get return "null". if ($myVar = $session->get("myVar")) { /* do something */ } Or better with false, if you have "myVar" but empty, you can't rely on "null" : if ($myVar = $session->get("myVar", false)) { /* do something */ } according to : Null vs. False vs. 0 in PHP I think the third is the best, one call to $session->get, instead of has and get in my actual code. I read about alternative comparaison with ternary operator, http://fabien.potencier.org/article/48/the-php-ternary-operator-fast-or-not, I don't use it, mostly because I.m not familiar with, but, if it's not faster, I don't need it. Can you confirm, third is the best, and if it's not, why, and how to do best ? A: That depends on what you want to achieve. First Option if ($session->has("myVar")) { $myVar = session->get("myVar"); /* do something */ } Makes sense if you want to make sure, that this var is set, and if not you actually want to set it or do anything else. It presumes that having this session variable present is a necessity Second Option $myVar = $session->get("myVar"); This one makes sense, if you are comfortable receiving the expected result or a null value as default if not set. Recommendation: $myVar = $session->get("myVar"); if (null === $myVar) { /* do something */ } Third Option $myVar = $session->get("myVar", false); This one simply allows you to override the default value if this session variable is not set Recommendation: $myVar = $session->get("myVar", false); if (!$myVar) { /* do something */ } So, in my opinion it depends what you want to do. But there is no best or worst way as you asked for, since they all differ from each other.
doc_811
A: foreach (DataGridViewRow row in myDataGrid.Rows) { if (row.Cells[myCheckboxCell.Index].Value.ToBool()) { row.Cells[myCell.index].Value // do somethin to this } } this is how i deal with my datagridviews in my project.i hope this helps,this does not need linq included in your project. however : if you are trying to do the value-get thingy right after the checkbox is checked and only for that row,you need a delegate action added to the column ,which is checkedchanged. in that case: you need this inside the EditingControlShowing event of your grid var checkbox = (CheckBox)e.Control; checkbox.CheckedChanged += (sender2, e2) => { if(checkbox.Checked) { myDatagrid.CurrentRow.Cells[myIntValue.index].Value //do something to your value } }; this means you cast the checkbox into a normal checkbox and make a delegate checked changed event for it,that way every time its checked your value is selected and your desired event would work. Edit : This is what ToBool() Does : public static bool ToBool(this bool? ex) { if (ex == null || ex == false) return false; return true; } its one of the tools that i use in my projects.
doc_812
However, this is not being loaded by angularJS. It seems my controller is being called twice. Here's the code $scope.searchTerms = JSON.parse(APIDataService.loadLocalData('changedSearchTerm')); var totalPages = JSON.parse(APIDataService.loadLocalData('oldData')); var getOldDataOn = APIDataService.getOldData($scope.searchTerms, totalPages, 1) .then(function(data) { if(data.thumbpath.length > 0) { console.log('records found'); $scope.hasResults = true; $scope.records = data.thumbpath; } else { $scope.hasResults = false; } }, function(data) { console.log('Image retrieval failed.') }); For some reason, console.log($scope.records) shows records, but Angular view is not being updated. I also tried $scope.$apply, but it's not working. Please help. Thank you in advance.
doc_813
import java.time.*; import java.time.temporal.*; class { public static void main(String[] arguments) { LocalDateTime now = LocalDateTime.now(); int Seconds = now.get(ChronoField.SECOND_OF_MINUTE); do{ \\ My Code is Here } while ( Seconds <= 00); I have it so that it should repeat when the minute changes but it won't loop unless I start it right before the minute changes. How do get the program to wait until the While becomes true so it will loop? A: You can wait for the amount of seconds to reach a full minute: LocalDateTime now = LocalDateTime.now(); int seconds = now.get(ChronoField.SECOND_OF_MINUTE); if (seconds > 0) { TimeUnit.SECONDS.sleep(60-seconds); } In fact, if you want to repeat some code every full minute, you should wait inside your loop: do { LocalDateTime now = LocalDateTime.now(); int seconds = now.get(ChronoField.SECOND_OF_MINUTE); if (seconds > 0) { TimeUnit.SECONDS.sleep(60-seconds); } // your code TimeUnit.SECONDS.sleep(1); // sleep for 1 second, so your code doesn't get executed twice per minute } while(true/*best to have some proper condition in here*/);
doc_814
Note that * *the task has to be started concurrently, since the calculations can take a while and I want to inform the user immediately that his task has been accepted - I want to keep him up to date about his task in another view. *the plaintext user password is part of the task arguments. It has to be, since the calculations involve encryption operations which rely on the password. Now I would just use celery and django_celery_results as result backend for this goal (and already started using it), when I noticed: Whoa... django_celery_results stores the plaintext password as part of the task kwargs in the database. That's not cool. Also the whole RabbitMQ messaging of the plaintext password seems a bit unsecure to me, after reading the celery security documentation. And who knows in which logs celery writes the passwords. To sum it up: celery and other task qeues not seem to be designed to handle sensible informations as arguments. I really just need to start a simple concurrent task, update its status and store its result in the database. I want to stay purely in python3 and django. Any recommendations? Edit: * *I do not want to use javascript for this. I want to use serverside form validation and start the asynchronous task there. *Applying reduction functions, hash functions or any other transformations to the user password does not solve the problem. Whatever I supply my task queue with, needs to be sufficient to perform the encryption/decryption operations and is therefore highly sensible. *I search for a solution where the plaintext password is only stored in memory
doc_815
The html is: <div id="words"> <p class="word" draggable="true">word1</p> <p class="word" draggable="true">word2</p> <p class="word" draggable="true">word3</p> </div> The js is: var dragSrcEl = null; function handleDragStart(e) { this.style.opacity = '0.4'; // this / e.target is the source node. dragSrcEl = this; e.dataTransfer.effectAllowed = 'move'; e.dataTransfer.setData('text/html', this.inneHTML); } function handleDragOver(e) { if (e.preventDefault) { e.preventDefault(); // Necessary. Allows us to drop. } e.dataTransfer.dropEffect = 'move'; return false; } function handleDragEnter(e) { // this / e.target is the current hover target. this.classList.add('over'); } function handleDragLeave(e) { this.classList.remove('over'); // this / e.target is previous target element. } function handleDrop(e) { // this / e.target is current target element. if (e.stopPropagation) { e.stopPropagation(); // stops the browser from redirecting. } if (dragSrcEl != this) { // Set the source column's HTML to the HTML of the column we dropped on. dragSrcEl.innerHTML = this.innerHTML; this.innerHTML = e.dataTransfer.getData('text/html'); //this.innerHTML = temp; } return false; } function handleDragEnd(e) { // this/e.target is the source node. [].forEach.call(words, function (word) { word.classList.remove('over'); }); } var words = document.querySelectorAll('#words .word'); [].forEach.call(words, function(word) { word.addEventListener('dragstart', handleDragStart, false); word.addEventListener('dragenter', handleDragEnter, false); word.addEventListener('dragover', handleDragOver, false); word.addEventListener('dragleave', handleDragLeave, false); word.addEventListener('drop', handleDrop, false); word.addEventListener('dragend', handleDragEnd, false); }); css is: .word{ float:left; margin-right:5px; cursor:move; } .word.over{ color: #ff0000; } However, when test the code in all browsers or jsfiddle, the target word changes fine, but the original word changes to "undefined" I'm thinking it's because dragSrcEl.innerHTML = this.innerHTML; is working but this.innerHTML = e.dataTransfer.getData('text/html'); returns undefined, and tests in jsfiddle confirmed this. So why is e.dataTransfer.getData('text/html'); return undefined? Its value should be setted at e.dataTransfer.setData('text/html', this.inneHTML); isn't it? A: Just change the replace part to this var temp = this.innerHTML; this.innerHTML = dragSrcEl.innerHTML; dragSrcEl.innerHTML = temp; Demo: http://jsfiddle.net/fWq4T/ A: Change line #5 e.dataTransfer.setData('text/html', this.inneHTML); to e.dataTransfer.setData('text/html', this.innerHTML); Hope this help
doc_816
Look at the following example: $db = new SQLite3('dogsDb.sqlite'); //create the database $db->exec("CREATE TABLE Dogs (Id INTEGER PRIMARY KEY, Breed TEXT, Name TEXT, Age INTEGER)"); $sth = $db->prepare("INSERT INTO Dogs (Breed, Name, Age) VALUES (:breed,:name,:age)"); $sth->bindValue(':breed', 'canis', SQLITE3_TEXT); $sth->bindValue(':name', 'jack', SQLITE3_TEXT); $sth->bindValue(':age', 7, SQLITE3_INTEGER); $sth->execute(); $sth->clear(); //this is supposed to clear bindings! $sth->reset(); $sth->bindValue(':breed', 'russel', SQLITE3_TEXT); $sth->bindValue(':age', 3, SQLITE3_INTEGER); $sth->execute(); Even though I would expect the second line to have a NULL value for the 'name' column, the value is 'jack' instead! So either 'clear' doesn't seem to work (although it returns true) or I haven't really understood what it's supposed to do. How can I clear the bindings between inserts in SQLite3 (or even PDO)? What's the best way to insert multiple rows where some rows might have null values for some fields? A: #include <sqlite3.h> #include <stdio.h> int main(void) { sqlite3 *db; char *err_msg = 0; sqlite3_stmt *res; sqlite3_stmt *res1; int rc = sqlite3_open("test.sqlite", &db); if (rc != SQLITE_OK) { fprintf(stderr, "Cannot open database: %s\n", sqlite3_errmsg(db)); sqlite3_close(db); return 1; } char *sql = "CREATE TABLE Dogs (Id INTEGER PRIMARY KEY, Breed TEXT, Name TEXT, Age TEXT)"; rc = sqlite3_prepare_v2(db, sql, -1, &res, 0); if (rc == SQLITE_OK) { rc = sqlite3_step(res); } sqlite3_finalize(res); char *sql1 = "INSERT INTO Dogs (Breed, Name, Age) VALUES (:breed,:name,:age);"; rc = sqlite3_prepare_v2(db, sql1, -1, &res1, 0); if (rc == SQLITE_OK) { printf("%d\n", sqlite3_bind_text(res1, 1, "breed1", 6, SQLITE_STATIC)); sqlite3_bind_text(res1, 2, "name1", 5, SQLITE_STATIC); sqlite3_bind_text(res1, 3, "age1", 4, SQLITE_STATIC); printf("%d\n", sqlite3_step(res1)); } else { fprintf(stderr, "Failed to execute statement: %s\n", sqlite3_errmsg(db)); } sqlite3_reset(res1); sqlite3_clear_bindings(res1); printf("%d\n", sqlite3_bind_text(res1, 2, "name2", 5, SQLITE_STATIC)); printf("%d\n", sqlite3_bind_text(res1, 3, "age2", 4, SQLITE_STATIC)); printf("%d\n", sqlite3_step(res1)); sqlite3_finalize(res1); sqlite3_close(db); return 0; }
doc_817
class Test extends Model { protected $fillable = [ 'subject','date', ]; public function getSubjectAttribute($value) { return ucfirst($value); } } When I call model, accessor does not work I read all documents and Q&A , but ... My Laravel version in 5.5 ----- edit In the model I have a method for fetch data public function get_specific_subject($id){ $subject = DB::table("subjects") ->where("id", "=", $id) ->first(); return $subject; } And I am calling this method in my controller by bellow code $subject = new Test(); $subject = $subject->get_specific_subject($subject_id); dd($subject); A: You have an extra letter 's' in the name of methods, Your field name is subject not subjects - tyy - public function getSubjectAttribute($value) { return ucfirst($value); } A: try this : you have written getSubjectsAttribute instead of getSubjectAttribute public function getSubjectAttribute($value) { return ucfirst($value); }
doc_818
In my AddItem.cs Add1=NameEntry.Text; Add2=CountEntry.Text; layoutListView1.newItem(Name,Count) new layoutListView1=layoutListView1; In my AddItem.xaml With this code is not passing any value to my listview. One more hint my add page is different than my Itemspage(where is my listView)… THANK YOU SO MUCH FOR ANY HELP A: Suppose the list is on MainPage, and the Entrys are on page1. Then you can try the following code: MainPage.xaml: <StackLayout Orientation="Vertical"> <Button Text="Add Item" Clicked="Button_Clicked" /> <ListView x:Name="MyListView"> <ListView.ItemTemplate> <DataTemplate> <ViewCell> <StackLayout BackgroundColor="#eee" Orientation="Vertical"> <StackLayout Orientation="Horizontal"> <Label Text="{Binding Name}" /> <Label Text="{Binding Count}"/> </StackLayout> </StackLayout> </ViewCell> </DataTemplate> </ListView.ItemTemplate> </ListView> </StackLayout> page1.xaml: <StackLayout Orientation="Vertical"> <Entry Text="new name" x:Name="NameEntry" VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand" /> <Entry Text="new count" x:Name="CountEntry" VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand" /> <Button Text="Add" Clicked="Button_Clicked" /> </StackLayout> MainPage.xamal.cs: public partial class MainPage : ContentPage { ObservableCollection<Employee> employees = new ObservableCollection<Employee>(); public MainPage() { InitializeComponent(); MyListView.ItemsSource = employees; MessagingCenter.Subscribe<Object, Employee>(this, "add_click", (sender, arg) => { employees.Add(arg); }); } async void Button_Clicked(object sender, EventArgs e) { await Navigation.PushAsync(new page1()); } } page1.xaml.cs: public partial class page1 : ContentPage { public page1 () { InitializeComponent (); } async void Button_Clicked(object sender, EventArgs e) { Employee employee = new Employee(); employee.Name = NameEntry.Text; employee.Count = CountEntry.Text; MessagingCenter.Send<Object, Employee>(this, "add_click", employee); await Navigation.PopAsync(); } You can get the demo on github.
doc_819
, so the question is - given the following svg how to make the gradient identified as Gradient1 work in such a way that it is a vertical gradient? <?xml version="1.0" encoding="utf-8"?> <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 79.4 59.5" xml:space="preserve"> <rect x="2.4" y="29.8" width="74.6" height="27.4"/> <g> <defs> <linearGradient id="Gradient1" gradientUnits="userSpaceOnUse" x1="100%" y1="0%" x2="100%" y2="100%" gradientTransform="rotate(45 50 50)"> <stop offset="0%" style="stop-color:#9AAFCC"/> <stop offset="20%" style="stop-color:#557096"/> <stop offset="35%" style="stop-color:#36557D"/> <stop offset="49%" style="stop-color:#1E3F6B"/> <stop offset="63%" style="stop-color:#0D305D"/> <stop offset="87%" style="stop-color:#032756"/> <stop offset="100%" style="stop-color:#002453"/> </linearGradient> </defs> <rect x="2.4" y="2.4" class="st0" width="74.6" height="27.4" fill="url(#Gradient1)"/> </g> </svg> I have of course tried to use a gradientTransform, what I have that works in Chrome (and presumably other browsers but not in IE) includes the following on the linearGradient element x1="-383.9706" y1="317.1023" x2="-382.9706" y2="317.1023" gradientTransform="matrix(0 -27.3826 -27.3826 0 8722.7842 -10484.3682)" however as soon as I try to do this in IE the gradient I have stops working and the rectangle just takes the first full stop color. I am open to translating the gradient into CSS if it can be made to work in the svg if that is the only cross-browser solution available. A: Your example works the same in Chrome and IE for me. <svg viewBox="0 0 79.4 59.5"> <rect x="2.4" y="29.8" width="74.6" height="27.4"/> <defs> <linearGradient id="Gradient1" gradientUnits="userSpaceOnUse" x1="100%" y1="0%" x2="100%" y2="100%" gradientTransform="rotate(45 50 50)"> <stop offset="0%" style="stop-color:#9AAFCC"/> <stop offset="20%" style="stop-color:#557096"/> <stop offset="35%" style="stop-color:#36557D"/> <stop offset="49%" style="stop-color:#1E3F6B"/> <stop offset="63%" style="stop-color:#0D305D"/> <stop offset="87%" style="stop-color:#032756"/> <stop offset="100%" style="stop-color:#002453"/> </linearGradient> </defs> <rect x="2.4" y="2.4" class="st0" width="74.6" height="27.4" fill="url(#Gradient1)"/> </svg> It's a linear gradient rotated 45 degrees as your markup requests. If you want the gradient to be vertical, remove the gradientTransform. <svg viewBox="0 0 79.4 59.5"> <rect x="2.4" y="29.8" width="74.6" height="27.4"/> <defs> <linearGradient id="Gradient1" gradientUnits="userSpaceOnUse" x1="100%" y1="0%" x2="100%" y2="100%"> <stop offset="0%" style="stop-color:#9AAFCC"/> <stop offset="20%" style="stop-color:#557096"/> <stop offset="35%" style="stop-color:#36557D"/> <stop offset="49%" style="stop-color:#1E3F6B"/> <stop offset="63%" style="stop-color:#0D305D"/> <stop offset="87%" style="stop-color:#032756"/> <stop offset="100%" style="stop-color:#002453"/> </linearGradient> </defs> <rect x="2.4" y="2.4" class="st0" width="74.6" height="27.4" fill="url(#Gradient1)"/> </svg>
doc_820
A: This is probably not the site for this question. BUT...if you are using Sharepoint on Office 365 you can sync the contents of a sharepoint library to your computer. Then any document you put in the folder gets uploaded to your sharepoint site. Sync instructions A: Sure, it is possible you can upload a whole folder into Sharepoint by creating put requests. I did write the code below to upload a directory into Sharepoint server. You must provide user authentication, check the files in folder whether you will upload or not and make an input ('y' or 'n' no case sensitive) and the full path required to upload data on Sharepoint server. Server response outputs should be 201 or 200 - OK to correctly upload files. import requests import os import sys from requests_ntlm import HttpNtlmAuth import glob path = 'C:\Python27' #CHANGE THIS it is an upload path where the files are stored files = next(os.walk(path))[2] print "File array:" print files print "\n" print 'Total number of files in', path, 'is', len(files) print "\n" print "Files listed in directory:" print "\n" i = 0 for i in range(0,len(files)): print(path+"\\."+files[i]) i += 1 print "\n" status = [] play = True while play: answer = raw_input('Do you want to continue to upload corresponding files? (Y)es or (N)o: \n').lower() while True: if answer == 'y': print 'Script will start uploading... \n' print 'Check if status codes are 200 (200 OK - The request has succeeded) ' print 'or 201 (201 CREATED - The request has been fulfilled and has resulted' print 'in one or more new resources being created). If not, try again. \n' for i in range(0, len(files)): filename = files[i] session = requests.Session() session.auth = HttpNtlmAuth('SharepointDomain\\username','password', session) #CHANGE THIS file = open(path + "\\" + filename, 'rb') bytes = bytearray(file.read()) resp = requests.put('Full directory path including hostname where the files will be uploaded' + filename, data=bytes, auth=session.auth) print "Status response for file #",i+1, "is", resp.status_code status = 'ok' break elif answer == 'n': play = False break else: answer = raw_input('Incorrect input. Press \"Y" to continue or \"N" to leave": ').lower() print 'Program will exit.'
doc_821
Possible Duplicate: Matlab 3D Matrix Plot I have a matrix in matlab that I want to plot as a 3D figure. Suppose the matrix looks like the following: A=[4 7 8; 2 3 9 ] This actually means the following data points in x,y,z plane (1,1,4) (1,2,7) (1,3,8) (2,1,2) (2,2,3) (2,3,9) I want to plot these values on a 3D graph. How can I do that? A: The function to use is surf(A) This will plot your points from x = 1:2 and y = 1:3
doc_822
root@workload-identity-test:/# ./cloud_sql_proxy -instances=project-id:europe-west4:db-instance=tcp:5432 2020/11/24 17:18:39 current FDs rlimit set to 1048576, wanted limit is 8500. Nothing to do here. 2020/11/24 17:18:40 GcloudConfig: error reading config: exit status 1; stderr was: ERROR: (gcloud.config.config-helper) There was a problem refreshing your current auth tokens: ("Failed to retrieve http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/db-proxy@project-id.iam.gserviceaccount.com/token from the Google Compute Enginemetadata service. Status: 404 Response:\nb'Unable to generate access token; IAM returned 404 Not Found: Requested entity was not found.\\n'", <google_auth_httplib2._Response object at 0x7fc5575545f8>) Please run: $ gcloud auth login to obtain new credentials. If you have already logged in with a different account: $ gcloud config set account ACCOUNT to select an already authenticated account to use. 2020/11/24 17:18:41 GcloudConfig: error reading config: exit status 1; stderr was: ERROR: (gcloud.config.config-helper) There was a problem refreshing your current auth tokens: ("Failed to retrieve http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/db-proxy@project-id.iam.gserviceaccount.com/token from the Google Compute Enginemetadata service. Status: 404 Response:\nb'Unable to generate access token; IAM returned 404 Not Found: Requested entity was not found.\\n'", <google_auth_httplib2._Response object at 0x7f06f72f45c0>) Please run: $ gcloud auth login to obtain new credentials. If you have already logged in with a different account: $ gcloud config set account ACCOUNT to select an already authenticated account to use. 2020/11/24 17:18:41 errors parsing config: Get "https://sqladmin.googleapis.com/sql/v1beta4/projects/project-id/instances/europe-west4~db-instance?alt=json&prettyPrint=false": metadata: GCE metadata "instance/service-accounts/default/token?scopes=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fsqlservice.admin" not defined Here's troubleshooting I've done so far: root@workload-identity-test:/# gcloud auth list Credentialed Accounts ACTIVE ACCOUNT * db-proxy@project-id.iam.gserviceaccount.com To set the active account, run: $ gcloud config set account `ACCOUNT` λ gcloud container clusters describe mycluster --format="value(workloadIdentityConfig.workloadPool)" project-id.svc.id.goog λ gcloud container node-pools describe mycluster-node-pool --cluster=mycluster --format="value(config.workloadMetadataConfig.mode)" GKE_METADATA λ gcloud container node-pools describe mycluster-node-pool --cluster=mycluster--format="value(config.oauthScopes)" https://www.googleapis.com/auth/monitoring;https://www.googleapis.com/auth/devstorage.read_only;https://www.googleapis.com/auth/logging.write;https://www.googleapis.com/auth/cloud-platform;https://www.googleapis.com/auth/userinfo.email;https://www.googleapis.com/auth/compute;https://www.googleapis.com/auth/sqlservice.admin λ kubectl describe serviceaccount --namespace k8s-namespace ksa-name Name: ksa-name Namespace: k8s-namespace Labels: <none> Annotations: iam.gke.io/gcp-service-account: db-proxy@project-id.iam.gserviceaccount.com Image pull secrets: <none> Mountable secrets: ksa-name-token-87n4t Tokens: ksa-name-token-87n4t Events: <none> λ gcloud iam service-accounts get-iam-policy db-proxy@project-id.iam.gserviceaccount.com bindings: - members: - serviceAccount:project-id.svc.id.goog[k8s-namespace/ksa-name] role: roles/iam.workloadIdentityUser etag: BwW02zludbY= version: 1 λ kubectl get networkpolicy --namespace k8s-namespace No resources found in k8s-namespace namespace. λ gcloud projects get-iam-policy project-id bindings: - members: - serviceAccount:db-proxy@project-id.iam.gserviceaccount.com role: roles/cloudsql.editor Expected result (I got this running on another cluster and changed configuration afterwards, can't find where my mistake is): root@workload-identity-test:~# ./cloud_sql_proxy -instances=project-id:europe-west4:db-instance-2=tcp:5432 2020/11/24 18:09:54 current FDs rlimit set to 1048576, wanted limit is 8500. Nothing to do here. 2020/11/24 18:09:56 Listening on 127.0.0.1:5432 for project-id:europe-west4:db-instance-2 2020/11/24 18:09:56 Ready for new connections What am I doing wrong? How do I troubleshoot or debug further? A: This could be due to the service account not being enabled when the Kubernetes cluster was created, or it wasn't configured properly. Try checking if the Service Account is disabled and Enable if it is. You could also try to create a new service account and change the service account in the pods. Or finally, try to provide the credentials to the gcloud command when running. A: I was able to resolve the problem by creating a service account with a different name. Just the name has changed, nothing else. If I delete the db-proxy@project-id.iam.gserviceaccount.com and then use the name again, the problem still persists. I was not able to find any other reference to said account. The problem was not encountered again after my comment on Nov 30 '20. A: Could you confirm that 'db-proxy@project-id.iam.gserviceaccount.com' is the correct account? I may be reading it wrong, but it seems that there is an error trying to refresh the auth token for that account, and the error is that the account does not exist. A: I encountered a similar error today and discovered that it was because the GSA was in a different project from the GKE cluster. It seem like the iam.workloadIdentityUser binding needs to be between accounts in the same project. So this worked: gcloud iam service-accounts create custom-metrics-adapter \ --project ${PLATFORM_PROJECT_ID} gcloud iam service-accounts add-iam-policy-binding \ "${GSA_NAME}@${PLATFORM_PROJECT_ID}.iam.gserviceaccount.com" \ --member "serviceAccount:${PLATFORM_PROJECT_ID}.svc.id.goog[${KSA_NAMESPACE}/${KSA_NAME}]" \ --role "roles/iam.workloadIdentityUser" \ --project ${PLATFORM_PROJECT_ID} with apiVersion: v1 kind: ServiceAccount metadata: name: ${KSA_NAME} namespace: ${KSA_NAMESPACE} annotations: iam.gke.io/gcp-service-account: ${GSA_NAME}${PLATFORM_PROJECT_ID}.iam.gserviceaccount.com --- apiVersion: apps/v1 kind: Deployment metadata: name: example namespace: ${KSA_NAMESPACE} spec: template: spec: serviceAccountName: ${KSA_NAME} # Deployment spec truncated for clarity Not sure if that helps you, but maybe it will help someone else who finds this by searching the error string: Failed to retrieve http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/${GSA_NAME}@${DIFFERENT_PROJECT_ID}.iam.gserviceaccount.com/token from the Google Compute Enginemetadata service. Status: 404 Response:\nb'Unable to generate access token; IAM returned 404 Not Found: Requested entity was not found.
doc_823
This is my text portion viewHolder.thrillersub_title.setText(model.getTitle()); This is my MainActivity @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_ottamooli_sub); Toolbar toolbar = findViewById(R.id.OttamooliSubtoolbar); setSupportActionBar(toolbar); getSupportActionBar().setTitle("Ottamooli"); if (getSupportActionBar()!=null){ getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); } MobileAds.initialize(this,APP_ID); AdView adView = (AdView) findViewById(R.id.adView); AdRequest adRequest = new AdRequest.Builder().build(); adView.loadAd(adRequest); database = FirebaseDatabase.getInstance(); MCC = database.getReference("Ottamooli2"); recyclerView = (RecyclerView) findViewById(R.id.recycler_OttamooliSub); recyclerView.setHasFixedSize(true); layoutManager = new LinearLayoutManager(this); recyclerView.setLayoutManager (layoutManager); if (getIntent() != null) categoryId = getIntent().getStringExtra("CategoryId"); if (!categoryId.isEmpty() && categoryId != null) { loadListThrillerSubModel(categoryId); } } private void loadListThrillerSubModel(String categoryId) { adapter = new FirebaseRecyclerAdapter<OttamoolisubModel, OttamooliSubViewHolder>(OttamoolisubModel.class, R.layout.ottamoolisub_items, OttamooliSubViewHolder.class, MCC.orderByChild("menuid").equalTo(categoryId)) { @Override protected void populateViewHolder(OttamooliSubViewHolder viewHolder, final OttamoolisubModel model, int position) { viewHolder.thrillersub_title.setText(model.getTitle()); Picasso.get().load(model.getImage()) .into(viewHolder.thrillersub_image); final OttamoolisubModel local = model; viewHolder.setItemClickListner(new ItemClickListner() { @Override public void onClick(View view, int position, boolean isLongClick) { } }); } }; recyclerView.setAdapter(adapter); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId()==android.R.id.home) finish(); return super.onOptionsItemSelected(item); } } This is my ViewHolder public TextView thrillersub_title; public ImageView thrillersub_image; private ItemClickListner itemClickListner; public void setItemClickListner(ItemClickListner itemClickListner) { this.itemClickListner = itemClickListner; } public OttamooliSubViewHolder(View itemView) { super(itemView); thrillersub_title = (TextView)itemView.findViewById(R.id.thrillerSub_name); thrillersub_image = (ImageView)itemView.findViewById(R.id.thrillerSub_image); } @Override public void onClick(View v) { itemClickListner.onClick(v,getAdapterPosition(),false); } This is my modelcalss private String title, image, menuid, cyid; public OttamoolisubModel() { } public OttamoolisubModel(String title, String image, String menuid, String cyid) { this.title = title; this.image = image; this.menuid = menuid; this.cyid = cyid; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getMenuid() { return menuid; } public void setMenuid(String menuid) { this.menuid = menuid; } public String getCyid() { return cyid; } public void setCyid(String cyid) { this.cyid = cyid; } } A: on setTitle(String title) this.title = title.replace("_b","\n"); That being said, if you have any occurrences of _b in your title outside of that, this could be problematic, and you'll need to parse it better.
doc_824
PHP Fatal error: Call to undefined function dateTime() in public_html/googleapi/calendarupdate.php on line 45. It is referring to the line: $event->setStart.dateTime($startdatetime); Here is my current PHP Code for the error: <?php header('Content-type: application/json'); require_once __DIR__ . '/google-api-php-client/src/Google/autoload.php'; $summary = $_POST["summary"]; $location = $_POST["location"]; $description = $_POST["description"]; $startdatetime = $_POST["startdatetime"]; $enddatetime = $_POST["enddatetime"]; $clientemail = $_POST["clientemail"]; $privatekey = $_POST["privatekey"]; $useremail = $_POST["useremail"]; $calendarid = $_POST["calendarid"]; $client_email = $clientemail; $private_key = file_get_contents($privatekey); $scopes = array('https://www.googleapis.com/auth/calendar'); $user_to_impersonate = $useremail; $credentials = new Google_Auth_AssertionCredentials( $client_email, $scopes, $private_key, 'notasecret', // Default P12 password 'http://oauth.net/grant_type/jwt/1.0/bearer', // Default grant type $user_to_impersonate ); $client = new Google_Client(); $client->setAssertionCredentials($credentials); if ($client->getAuth()->isAccessTokenExpired()) { $client->getAuth()->refreshTokenWithAssertion(); } $service = new Google_Service_Calendar($client); $event = $service->events->get($useremail, $calendarid); $event->setSummary($summary); $event->setLocation($location); $event->setStart.dateTime($startdatetime); $event->setStart.timeZone('America/Los_Angeles'); $event->setEnd.dateTime($enddatetime); $event->setEnd.timeZone('America/Los_Angeles'); $event->setDescription($description); $updatedEvent = $service->events->update($useremail, $event->getId(), $event); echo json_encode($updatedEvent); My PHP code is based off of Google's API Documentation found here. A: Ok, I actually managed to figure it out. I just had to change the line: $event->setStart.dateTime($startdatetime); To This: $event->start->setDateTime($startdatetime); I do the same general thing for the end datetime, except where it says start, I just put end. Just tested it and it worked perfectly. The site that helped me out can be found here.
doc_825
someone@gmail.com has retrieved data from BigQuery table bq_table_name Is there a way to get these Human readable logs instead of the complete JSON log messages? A: Unfortunately there's no way to get the templated message for audit logs provided by http://console.cloud.google.com/home/activity apart from the UI itself.
doc_826
py.test --cov-report term-missing --cov=pipelines/core/comp/plugins/abc/ --noconftest pipelines/core/comp/test/plugins/abc/test_abc_crawler_task.py -vv But getting the following error : usage: py.test [options] [file_or_dir] [file_or_dir] [...] py.test: error: unrecognized arguments: --cov-report --cov=pipelines/core/comp/plugins/abc/ pipelines/core/comp/test/plugins/abc/test_abc_v4_crawler_task.py inifile: /home/udocker/piper/pytest.ini rootdir: /home/udocker/piper A: You need to install pytest-cov with pip3 install pytest-cov
doc_827
Our problem is that we can't seem to get the info to save and load from a .txt file. We're pretty sure the file isn't being created, thus, nothing is being written to it. However we're not getting any errors thrown when it runs so we're confused at where we went wrong. If someone could take a look at it and give us some pointers, that would help immensely. Code is below: public class test { public static void main(String[] args) throws IOException { // File file = new File("enroll.txt"); used to create the file final JFrame mainMenu = new JFrame("Error"); final int WINDOW_WIDTH = 600; final int WINDOW_HEIGHT = 400; FlowLayout layout = new FlowLayout(); mainMenu.setSize(WINDOW_WIDTH, WINDOW_HEIGHT); mainMenu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainMenu.setLocationRelativeTo(null); mainMenu.setLayout(layout); Button load = new Button("Load Enrollment"); Button enroll = new Button ("New Enrollment"); mainMenu.add(load); mainMenu.add(enroll); mainMenu.setVisible(true); final JFrame loadEn = new JFrame("Load"); loadEn.setVisible(false); loadEn.setSize(WINDOW_WIDTH, WINDOW_HEIGHT); loadEn.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); loadEn.setLocationRelativeTo(null); loadEn.setLayout(layout); JLabel file = new JLabel("File:"); file.setVisible(true); final JTextField fileEnter = new JTextField(10); fileEnter.setEditable(true); fileEnter.setVisible(true); Button run = new Button("Run"); Button menu = new Button("Main Menu"); final JTextArea print = new JTextArea(500, 300); loadEn.add(file); loadEn.add(fileEnter); loadEn.add(run); loadEn.add(menu); loadEn.add(print); final JFrame newEnroll = new JFrame("New Enrollment"); newEnroll.setVisible(false); newEnroll.setSize(WINDOW_WIDTH, WINDOW_HEIGHT); newEnroll.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); newEnroll.setLocationRelativeTo(null); newEnroll.setLayout(layout); JLabel passType = new JLabel("Passport Type"); JLabel passNo = new JLabel("Passport Number"); JLabel firstName = new JLabel("First Name"); JLabel lastName = new JLabel("Last Name"); JLabel country = new JLabel("Country"); JLabel placeOB = new JLabel("Place of Birth"); JLabel visaType = new JLabel("Visa Type"); JLabel visaNo = new JLabel("Visa Number"); JLabel remarks = new JLabel("Remarks"); Button save = new Button("Save"); final JTextField _passNo = new JTextField(10); final JTextField _firstName = new JTextField(10); final JTextField _lastName = new JTextField(10); final JTextField _placeOB = new JTextField(10); final JTextField _visaNo = new JTextField(10); final JTextField _remarks = new JTextField(10); final JTextField _passType = new JTextField(10); final JTextField _country = new JTextField(10); final JTextField _visaType = new JTextField(10); newEnroll.add(passType); newEnroll.add(_passType); newEnroll.add(visaType); newEnroll.add(_visaType); newEnroll.add(passNo); newEnroll.add(_passNo); newEnroll.add(visaNo); newEnroll.add(_visaNo); newEnroll.add(firstName); newEnroll.add(_firstName); newEnroll.add(remarks); newEnroll.add(_remarks); newEnroll.add(lastName); newEnroll.add(_lastName); newEnroll.add(country); newEnroll.add(_country); newEnroll.add(placeOB); newEnroll.add(_placeOB); newEnroll.add(menu); newEnroll.add(save); load.addActionListener(new ActionListener () { @Override public void actionPerformed(ActionEvent e) { loadEn.setVisible(true); mainMenu.setVisible(false); newEnroll.setVisible(false); } }); menu.addActionListener(new ActionListener () { @Override public void actionPerformed(ActionEvent e1) { loadEn.setVisible(false); mainMenu.setVisible(true); newEnroll.setVisible(false); } }); enroll.addActionListener(new ActionListener () { @Override public void actionPerformed(ActionEvent e2) { loadEn.setVisible(false); mainMenu.setVisible(false); newEnroll.setVisible(true); } }); save.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e4) { PrintWriter fw = null ; try { fw = new PrintWriter("enroll.txt", "UTF-8"); BufferedWriter bw = new BufferedWriter(fw); bw.write(_passNo.getText()); bw.newLine(); bw.write(_firstName.getText()); bw.newLine(); bw.write(_lastName.getText()); bw.newLine(); bw.write(_placeOB.getText()); bw.newLine(); bw.write(_visaNo.getText()); bw.newLine(); bw.write(_remarks.getText()); bw.newLine(); bw.write(_passType.getText()); bw.newLine(); bw.write(_country.getText()); bw.newLine(); bw.write(_visaType.getText()); } catch (IOException e1) { e1.printStackTrace(); } finally { fw.close(); } } }); run.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e3) { FileReader fr = null; try { fr = new FileReader("enroll.txt"); } catch (FileNotFoundException e2) { e2.printStackTrace(); } try { fr = new FileReader("enroll.txt"); } catch (FileNotFoundException e1) { e1.printStackTrace(); } BufferedReader br = new BufferedReader(fr); try { print.read(br, null); } catch (IOException e1) { e1.printStackTrace(); } catch(Exception e) { System.out.println(e); } finally { try { br.close(); } catch (IOException e) { e.printStackTrace(); } try { fr.close(); } catch (IOException e) { e.printStackTrace(); } } } }); } } A: Make two changes First - writing In save.addActionListener you close your Printwriter with fw.close();. The Printerwriter is used by your BufferedWriter bw = new BufferedWriter(fw);. You have to call bw.close() instead of fw.close() Second - reading The choice of your Layout is not the best. Your JTextArea is much to large. Your file is loaded but you can't see it. If you use final JTextArea print = new JTextArea(30, 30); instead of final JTextArea print = new JTextArea(500, 500); everythings works fine. Remember: The parameters in JTextArea are rows and columns - not pixel. Hope that helps
doc_828
Supposed I stored all of my file in application/secretdirectory/file1.jpg application/secretdirectory/file2.text application/secretdirectory/file3.zip usually, I create direct link to access these files. <a href="application/secretdirectory/file3.zip" > download here </a> I want to prevent it, I want my link will be <a href="<? echo site_url() . "download/file3.zip" ?>" > download here </a> can you help me ??? A: It's probably a good idea to pass it to a controller like this: Class File extends Controller{ function download($file){ $data = file_get_contents('path/to/' . $file); // Read the file's contents $name = $file; force_download($name, $data); } } Your link would be: <?php echo anchor('file/download/' . $thefile, 'Download');?> This way they'd never know which directory it came from. A: I'm sure there is a library in CI to assist with this basically you send headers for the correct MIME type, the content length (filesize()) and then output to the browser to download echo file_get_contents() may work) If using Apache, you'll also want to deny showing directoy content. <Files .*> Order Deny,Allow Deny From All </Files>
doc_829
ex: Person: name, address, address1, cityid, stateid, countryid, pincode, .. Company: name, address, address1, cityid, stateid, countryid, pincode, .. .. Relevant viewmodels: public class customermodel{ public PersonModel basicInfo {get;set;} public string type {get;set;} public long id {get;set;} ... } public class PersonModel{ public string FirstName {get;set;} public string MiddleName {get;set;} public string LastName {get;set;} public string Email {get;set;} public long Phone {get;set;} public string address {get;set;} public string address1 {get;set;} public long cityid {get;set;} public long stateid {get;set;} public long countryid{get;set;} public long pincode {get;set;} } I created a class for address: public class AddressModel{ public string address {get;set;} public string address1 {get;set;} public long cityid {get;set;} public long stateid {get;set;} public long countryid{get;set;} public long pincode {get;set;} } (NOTE: I did not use AddressModel in personmodel so that automapper can pull in all the data) and editortemplate for the same in /Views/Shared/EditorTemplates/AddressModel.ascx <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<AddressModel>" %> <%: Html.TextBoxFor(model => model.address, new { Placeholder = "Country" })%> <%: Html.TextBoxFor(model => model.address1, new { Placeholder = "State", style="display:none;" })%> ... From my EditCustomer view, I want to call the editor template for address model. <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<CustomerModel>" %> <%: Html.TextBoxFor(model => model.id) %> <%: Html.TextBoxFor(model => model.type) %> <%: Html.EditorFor(model => (AddressModel)AutoMapper.Mapper.DynamicMap<AddressModel>(model.personModel), "AddressModel")%> ... Now I get the following error for the EditorFor line: Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions. I want to use Html.EditorForModel("AddressModel");, but that throws me an error "System.InvalidOperationException: The model item passed into the dictionary is of type 'CustomerModel', but this dictionary requires a model item of type 'AddressModel'". I dont know how to pass the automapper generated addressmodel to the editortemplate in this case. I cant use partialViews because I want the address fields to be prefixed with basicInfo in this case and I dont need any prefix in another case. This is driving me crazy for a couple of days. Please help!!! A: Found this article that helps solve this issue - http://thatextramile.be/blog/2011/01/prefixing-input-elements-of-partial-views-with-asp-net-mvc/
doc_830
def convStr2Date(given): if type(given) != str: return given pattern = r'^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}|.*)' rv = re.search(pattern, given).group(1) if rv: return datetime.strptime(rv, '%Y-%m-%d %H:%M:%S') which gives me the error ValueError: time data '2021-10-01' does not match format '%Y-%m-%d %H:%M:%S So I added an else: statement, but still getting the same error, where am I going wrong? Trying: def convStr2Date(given): if type(given) != str: return given pattern = r'^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}|.*)' rv = re.search(pattern, given).group(1) if rv: return datetime.strptime(rv, '%Y-%m-%d %H:%M:%S') else: return datetime.strptime(rv, '%Y-%m-%d') A: If you don't care about exact patterns, you could just test for a space. Your code is going to fail on other date patterns anyway. from datetime import datetime def convStr2Date(given: str) -> datetime: if not isinstance(given, str): raise ValueError(f"{given!r} is not a string") date_format = '%Y-%m-%d' if ' ' in given : date_format = '%Y-%m-%d %H:%M:%S' return datetime.strptime(given, date_format) Example for d in ['2021-10-02', '2018-10-20 01:21:23', 'not a date', 'notADate', 2, None]: try: print(convStr2Date(d)) except ValueError as e: print(e) Output 2021-10-02 00:00:00 2018-10-20 01:21:23 time data 'not a date' does not match format '%Y-%m-%d %H:%M:%S' time data 'notADate' does not match format '%Y-%m-%d' 2 is not a string None is not a string A: If you want to return None (or an Error) if nothing is matching (instead of just accepting everything) you can also do def convStr2Date(given): if type(given) != str: return given pattern = '^(\d{4}-\d{2}-\d{2})( \d{2}:\d{2}:\d{2})?$' rv = re.search(pattern, given) if rv and rv.group(2): # Tests if second group matches # (the part with the time of day) # So there is given both date and time of day return datetime.strptime(rv.group(0), '%Y-%m-%d %H:%M:%S') elif rv: # Tests if the whole regex matches. # Since the second part is optional # the regex still matches if it is missing # and because the first if tests if the # second part exists and we are in the else branch # we know only the first group matches # which is only the date (without time) return datetime.strptime(given, '%Y-%m-%d') else: # If the whole regex does not match # we know that it is not one of the two formats # and therefore cannot be parsed return None # Or raise some Error #raise NotImplementedError A: remove the |.* so that it will only match dates and then if it doesn't match it will return None so you need to ensure that is not the case before using it for things like .group(1) def convStr2Date(given: str): pattern = r'^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})' match = re.search(pattern, given) if match is not None: # only call group if the match exists return datetime.strptime(match.group(1), '%Y-%m-%d %H:%M:%S') else:raise NotImplementedError
doc_831
class IndexController extends Zend_Controller_Action { public function init(){/* Initialize action controller here */} public function indexAction(){//some code} public function addAction(){//some code} public function otherAction(){//other code} } class TestController extends Zend_Controller_Action { public function init(){/* Initialize action controller here */} public function indexAction(){//some code} public function addAction(){//some code} public function otherAction(){//other code} } When I type in address bar zf.local/ I recive content from index/index.phtml file but when I type zf.local/index/index ZF tell that url is not find. When I type zf.local/test/index everything is working fine If I type in address bar zf.local/index/add I recive a 404 ERROR but if I type zf.local/test/add everything is working fine. I've set my virtual host to AllowOverride All, and I enabled rewrite module from Apache.I stop, restart and reload apache, restart my pc.I think that is no problem with apache, or virtual host that is why I am writing this.My apache and virtual host configurations Once I tried to type zf.local/default/index/add and the code is working so I need to put a /default before /index in address bar I think that this could be solved with Zend helper to insert in my url /default before /index Official DOcumentation form Zend Framework but I don't know how to do it. Until now I've manage to get only bugs From index.html I call actions from controller with next code : <a href="<?php echo $this->url(array('controller' => 'index', 'action' => 'add')); ?>">Add</a> A: You ZF Application is incorrect created. Try first to create application from command line. After that this problem shall be solved. A: Try the following in the view file to get the correct url <a href="<?php echo $this->url(array('module' => 'default', 'controller' => 'index', 'action' => 'add')); ?>">Add</a>
doc_832
error: 'static' can only be specified inside the class definition error. In my current use-case, I am moving from a very MSVC project, where almost all the code is compiled using MSVC, and cross compiling for Android. I noticed that there is no MSVC error, least of all, a warning, about static class methods having definitions inside (outside) the class. Am I missing something? Why is there not at least a warning? EDIT To clarify, I am asking why there is no proper MSVC/MSVS warning for code such as this (taken from the link, above): class Foobar { public: static void do_something(); }; static void Foobar::do_something() {} // Error! int main() { Foobar::do_something(); } EDIT So sorry evey one! This sample doesn't work! My apologies. class Foobar { public: template<class Y> static int do_something(); }; template<class Y> static int Foobar::do_something() {return 1;} // Error! int main() { return Foobar::do_something<double>(); } Here is the output from MSVC 19.14 (success), and GCC 4.12 (failure). A: VS 2012 Update 5, VS 2013 Update 5, VS 2015 Update 3 and VS 2017 (15.9 update) all report an error for this code: error C2724: 'Foobar::do_something': 'static' should not be used on member functions defined at file scope I'm guessing the code built only with an older, non-conformant version of Visual C++. Note that if you want to clean up code using the Visual C++ compiler to make it easier to port to other platforms: * *You can use VS 2017 with the /permissive- switch. See this blog post. *There are a number of conformance switches to try as well such as /Zc:__cplusplus. See this blog post. Using /permissive- already implies /Zc:strictStrings, /Zc:rvalueCast, and /Zc:ternary and enables two-phase name look-up. * *You can also use /Wall, although it takes some effort to get all the noise down to see the useful warnings. It's still not as fussy as clang, but it's helpful. For an example of a bunch of stuff to suppress, see the top of this header. *There is also an experimental C99 preprocessor you can try, although that one is still in the early stages. See this blog post You can try it out yourself with the VS 2017 Community edition.
doc_833
import java.awt.Color; import java.awt.Dimension; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.RenderingHints; import java.awt.Stroke; import java.util.ArrayList; import java.util.List; import javax.swing.JPanel; public class Gf extends JPanel { private static final long serialVersionUID = 1L; private int padding = 0; private int labelPadding = 0; private Color pointColor = new Color(0, 10, 100); private int pointWidth = 1; private int numberYDivisions = 2; private List<Double> scores; public Gf(List<Double> scores) { this.scores = scores; } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); double xScale = ((double) getWidth() - (2 * padding) - labelPadding) / (scores.size() - 1); double yScale = ((double) getHeight() - 2 * padding - labelPadding) / 60000; List<Point> graphPoints = new ArrayList<>(); for (int i = 0; i < scores.size(); i++) { int x1 = (int) (i * xScale + padding + labelPadding); int y1 = (int) ((getMaxScore() - scores.get(i)) * yScale + padding); graphPoints.add(new Point(x1, y1)); } // draw white background g2.setColor(Color.BLACK); g2.fillRect(padding + labelPadding, padding, getWidth() - (2 * padding) - labelPadding, getHeight() - 2 * padding - labelPadding); g2.setColor(Color.BLACK); // create hatch marks and grid lines for y axis. for (int i = 0; i < numberYDivisions + 1; i++) { int x0 = padding + labelPadding; int x1 = pointWidth + padding + labelPadding; int y0 = getHeight() - ((i * (getHeight() - padding * 2 - labelPadding)) / numberYDivisions + padding + labelPadding); int y1 = y0; if (scores.size() > 0) { String yLabel = ((int) ((getMinScore() + (getMaxScore() - getMinScore()) * ((i * 1.0) / numberYDivisions)) * 100)) / 100.0 + ""; FontMetrics metrics = g2.getFontMetrics(); int labelWidth = metrics.stringWidth(yLabel); g2.drawString( yLabel, x0 - labelWidth - 5, y0 + (metrics.getHeight() / 2) - 3); } g2.drawLine(x0, y0, x1, y1); } // and for x axis for (int i = 0; i < scores.size(); i++) { if (scores.size() > 1) { int x0 = i * (getWidth() - padding * 2 - labelPadding) / (scores.size() - 1) + padding + labelPadding; int x1 = x0; int y0 = getHeight() - padding - labelPadding; int y1 = y0 - pointWidth; if ((i % ((int) ((scores.size() / 20.0)) + 1)) == 0) { String xLabel = i + ""; FontMetrics metrics = g2.getFontMetrics(); int labelWidth = metrics.stringWidth(xLabel); g2.drawString( xLabel, x0 - labelWidth / 2, y0 + metrics.getHeight() + 3); } g2.drawLine(x0, y0, x1, y1); } } // create x and y axes g2.drawLine(padding + labelPadding, getHeight() - padding - labelPadding, padding + labelPadding, padding); g2.drawLine(padding + labelPadding, getHeight() - padding - labelPadding, getWidth() - padding, getHeight() - padding - labelPadding); Stroke oldStroke = g2.getStroke(); g2.setStroke(oldStroke); g2.setColor(pointColor); for (int i = 0; i < graphPoints.size(); i++) { int x = graphPoints.get(i).x - pointWidth / 2; int y = graphPoints.get(i).y - pointWidth / 2; int ovalW = pointWidth; int ovalH = pointWidth; g2.fillOval(x, y, ovalW, ovalH); } } // @Override // public Dimension getPreferredSize() { // return new Dimension(width, heigth); // } private double getMinScore() { double minScore = -30000; return minScore; } private double getMaxScore() { double maxScore = 30000; return maxScore; } public void setScores(List<Double> scores) { this.scores = scores; invalidate(); this.repaint(); } public List<Double> getScores() { return scores; } public static void createAndShowGui() { List<Double> scores = new ArrayList<>(); short[] x = mainclass.Omega; // getting required data from main class for (int i = 0; i < x.length; i++) { scores.add((double) x[i]); } Gf mainPanel = new Gf(scores); mainPanel.setPreferredSize(new Dimension( mainclass.range, 276)); // range is calculated at main class and usually // has more than 3k width mainclass.p.add(mainPanel); // adding to jpanel at main class mainclass.f.revalidate(); mainclass.f.repaint(); } } The problem is that sometimes gets way slow specially on slower devices when scrolling the bar to check the entire diagram. So wanted to know if there is a way to save the graph as an image instead of showing at JPanel(so that it can be added to the JPanel later in some way that doesn't affect the performance).
doc_834
<img src="~/images/logo.png" /> From my understanding, the tilde is an ASP.NET MVC thing that gets rendered at runtime. However, I have some JavaScript files that are static. I need them to reference something relatively. How could I do ~/images/logo.png in JavaScript? A: ~ refers to application root folder in case your application is not hosted in a sub folder like http://example.com/mydir/myapp (in nested virtual directory) then the javascript equivalent will be /images/logo.png A: The ~ symbol as an ASP.Net feature that is resolved server-side -- Javascript does not know anything about it. The only way to do this from Javascript, is to target relative to the path where the current file is served. So if your path structure is like this: Web Application Content js test.js images logo.png Then, from your "test.js" file, you would reference "logo.png" as ../images/logo.png. (Technically, you could write a dynamic Javascript file with server tags, but that seems like an unnecessary measure just to resolve a relative path.)
doc_835
inner abstract class Base { fun Buscar(): Int { // Do something with a object called Q } } And two secondary class that I need to initialize Q with certain class inner class BFS(): Base() { constructor(): this() { Q = Cola() } } inner class DFS(): Base() { constructor(): this() { Q = Pila() } } How can I do that? --- EDIT --- Pila() and Cola() are classes from an abstract class called Secuencia: abstract class Secuencia<T> { ... } public class Pila<T> : Secuencia<T>() { ... } public class Cola<T> : Secuencia<T>() { ... } A: You just need to make Q abstract and initialise it in your class, e.g. sealed class Algo(val message: String) class Cola : Algo("cola") class Pila : Algo("pila") abstract class Base { // all concrete classes need to define a value for 'q' abstract val q: Algo fun buscar(): Int { // you can reference q here since a concrete class will have initialised it println(q.message) return 1 } } class BFS(): Base() { // since q is abstract it needs to be overridden in a concrete class override val q = Cola() } class DFS(): Base() { override val q = Pila() } fun main() { BFS().buscar() DFS().buscar() } >> cola >> pila
doc_836
I have a mysql table with a default Null field value named trigger. At the begining of each parallel process, the process selects a Null raw with: SELECT table_id from table where trigger is Null limit 1 and then immediatly, in a second request, the process do an update : UPDATE table set trigger = 1 where table_id = [#previous_select_table_id] With that process , normally, each raw will be different for each process. The issue I have, is sometimes, during the time between the two requests (select and update), two or more processes can select the same empty raw because they don't have the time to update the raw and set value. Do you have any ideas how to do a select and an update in the same query or other ideas, to be sure a raw can't be selected during the same time ? I use python. Thanks a lot ! A: The first problem is these are two independent transactions. So the first is to make them into one. START TRANSACTION SELECT table_id from table where trigger is Null limit 1 FOR UPDATE [do stuff] UPDATE table set trigger = 1 where table_id = [#previous_select_table_id] COMMIT The second aspect is this form of select of unprocessed data and remove it from consideration is a queue. Database implementing queues isn't a natural thing for them. Use a message queue like RabbitMQ or otherwise. Even if all you put on the query is a table_id. Also be careful of using reserved words like trigger for table columns.
doc_837
link to post and ended up with this config in my pom file <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>jaxws-maven-plugin</artifactId> <version>2.6</version> <executions> <execution> <goals> <goal>wsimport</goal> </goals> </execution> </executions> <configuration> <wsdlUrls> <wsdlUrl>https://tim-erp.com/ERPX_WEB/awws/ErpX.awws?wsdl</wsdlUrl> </wsdlUrls> <packageName>com.output</packageName> <sourceDestDir> ${project.build.directory}/generated-sources/ </sourceDestDir> </configuration> </plugin> but now I get this error [ERROR] Invalid wsdl:operation "kasaLogin": its a document-literal operation, message part must refer to a schema element declaration. Few moths ago I have used this link to generate initial artifactes but I've deleted the code and now I can't remember how did it worked. Now I'm looking for any solution that would work. Wsdl when imported to SOAP UI works fine. I'm using java 11 and Intellij Idea. Thanks in advance. A: Use soap ui to see what the message looks like, then create soap message exactly like what you've seen ,it works fine for me. Here's part of a demo for create a soap message MessageFactory messageFactory = MessageFactory.newInstance(); SOAPMessage soapMessage = messageFactory.createMessage(); SOAPPart soapPart = soapMessage.getSOAPPart(); SOAPEnvelope envelope = soapPart.getEnvelope(); .... after creating a soap message, you just send a http or https request with what you'v assembled.
doc_838
Thanks for any help! A: According to your answer i assume you want to scrap magento product id from a 3rd party store. The most solid way to do this, is to read it from hidden field in addtocart form.
doc_839
@Entity public class Account { private String description; private AccountPk id; public Account (String description) { this.description = description; } protected Account() { } @EmbeddedId public AccountPk getId() { return this.id; } public String getDescription() { return this.description; } public void setId(AccountPk id) { this.id = id; } public void setDescription(String description) { this.description = description; } } Then I have another supporting class public class AccountPk { private String code; private Integer number; public AccountPk() { } public String getCode() { return this.code; } public Integer getNumber() { return this.number; } public void setNumber(Integer number) { this.number = number; } public void setCode(String code) { this.code = code; } public int hashCode() { int hashCode = 0; if( code != null ) hashCode ^= code.hashCode(); if( number != null ) hashCode ^= number.hashCode(); return hashCode; } public boolean equals(Object obj) { if( !(obj instanceof AccountPk) ) return false; AccountPk target = (AccountPk)obj; return ((this.code == null) ? (target.code == null) : this.code.equals(target.code)) && ((this.number == null) ? (target.number == null) : this.number.equals(target.number)); } } What I'm having a problem is the mapper class, Account.hbm.xml which looks like <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="hello.Account" table="MESSAGES"> <id name="id" column="MESSAGE_ID"> <generator class="increment"/> </id> <property name="description" column="DESCRIPTION"/> </class> </hibernate-mapping> I am sure this xml file is the culprit but I don't know how to do it in a right way. So, I'll appreciate your help on this. A: Use <composite-id> instead of <id>, for example like this: <composite-id> <key-property name="firstId" column="FIRST_ID_COL" type="..." /> <key-property name="secondId" column="SECOND_ID_COL" type="..." /> </composite-id> By the way, you can't use a generator with a composite id. You have to generate the id yourself. (Anyway, a generator for a composite key normally doesn't make sense. Which of the key components should it generate and when?)
doc_840
Below are my .podspec and pod files. to resolve above issue, I have added "use_modular_headers!" in my pod file and did pod install successfully. when I open the app and trying to compile but I'm surprised that I have facing issues from my existing custom libraries which are successfully build before firebase integration in the app. Please check the below file for the reference. can anyone help on this issue? Thanks in advance. A: Add use_frameworks! or use_frameworks! :linkage => :static to the Podfile. Firebase 9 dropped support for CocoaPods library integrations. More details in the release notes.
doc_841
I'm checking if there are bad records to report. I'm using a sequence to keep the count. After that I'm preparing a document with this errors to be sent just it the counter is greater than zero. For the kjb father I am using this configutation to check the quantity of errors: However when I execute the process, for the ktr I'm getting this message: Set Variables 2.0 - Set variable NumberOfErrors to value 1 org.pentaho.di.core.exception.KettleStepException: Only 1 input row was expected to set the variables and at least 2 were received. at org.pentaho.di.trans.steps.setvariable.SetVariable.processRow(SetVariable.java:96) at org.pentaho.di.trans.step.RunThread.run(RunThread.java:62) at java.lang.Thread.run(Thread.java:748) 2019/02/04 18:56:36 - Set Variables 2.0 - ERROR (version 8.1.0.0-365, build 8.1.0.0-365 from 2018-04-30 09.42.24 by buildguy) : Unexpected error 2019/02/04 18:56:36 - Set Variables 2.0 - ERROR (version 8.1.0.0-365, build 8.1.0.0-365 from 2018-04-30 09.42.24 by buildguy) : org.pentaho.di.core.exception.KettleStepException: 2019/02/04 18:56:36 - Set Variables 2.0 - Only 1 input row was expected to set the variables and at least 2 were received. 2019/02/04 18:56:36 - Set Variables 2.0 - 2019/02/04 18:56:36 - Set Variables 2.0 - at org.pentaho.di.trans.steps.setvariable.SetVariable.processRow(SetVariable.java:96) 2019/02/04 18:56:36 - Set Variables 2.0 - at org.pentaho.di.trans.step.RunThread.run(RunThread.java:62) 2019/02/04 18:56:36 - Set Variables 2.0 - at java.lang.Thread.run(Thread.java:748) And the variable with the errors is equal to zero even when I know that there are some bad records. How can I configure the set variable step in the proper way in order to set the value of this variable? Regards. A: The error that you are seeing is telling you that Set Variables step only accepts streams containing a single row. In case your stream contains many rows this step will throw an error. To solve your issue you could try aggregating the rows using Group By step so that you can aggregate all your rows into a single one which is containing the count field. After that your Set Variables step will receive only 1 input row and the variable will be successfully set in the parent job. Here is an example:
doc_842
class first { unique_ptr<second> p2; public: first() : p2(this) {} }; class second { first* p1; public: second(first* arg) : p1(arg) {} }; This all works fine and dandy, but what I really want is to use a shared_ptr as a part of second because second objects may also be created independently of first. They will just be passed a pointer to a first on construction, but they won't know if it's gone. I can't just make second::p1 a shared_ptr because I wouldn't know how to pass in this from first::first(). Is there an idiom that can help me handle this? A: It is possible with the caveat that you can then only create instances on the heap. Using std::shared_from_this would be a nice solution but it can only be called once a std::shared_ptr to the object exists which is not possible until the constructor has finished, even when using std::make_shared and a std::bad_weak_ptr exception is thrown. Instead we ensure that the only way to create an instance of this class is through a static function which does the necessary setup. #include <cassert> #include <memory> class second; class first { struct Unconstructable {}; std::unique_ptr<second> p2; public: first(Unconstructable) : p2() {} static std::shared_ptr<first> create() { Unconstructable u; auto f = std::make_shared<first>(u); f->p2 = std::make_unique<second>(f); return f; } }; class second { std::shared_ptr<first> p1; public: second(std::shared_ptr<first> arg) : p1(arg) {} }; int main() { auto f = first::create(); } Edit: The use of Unconstructable isn't really necessary but is required for the use of std::make_unique. If I were to simple make the constructor private then std::make_unique would fail to compile even if I made it a friend function since the implementation uses internal helper functions. Having a private struct as a constructor argument is a way to bypass this while still preventing construction from happening outside of the class itself. A: Copying from my comments as OP indicated this is an answer he is OK with. Unfortunately, there is no safe way of doing so - for the simple matter of constructor not having a slightest idea how an object was allocated. What if it was not allocated dynamically at all? enable_shared_from_this, as indicated in another comment, is not a solution either - it just allows to get a shared_ptr from a weak_ptr hidden inside the class. However, this is only safe as long as there is at least one shared_ptr already created and holding the lock - and again, this is not something which can be ensured from the constructor.
doc_843
There is a problem with this Windows Installer package. A DLL required for this install to complete could not be run. Any clue? Code snippet: <?xml version="1.0" encoding="UTF-8"?> <Wix xmlns="http://schemas.microsoft.com/wix/2006/wi" xmlns:util="http://schemas.microsoft.com/wix/UtilExtension"> <Product Id="*" Name="SetupProject1" Language="1033" Version="1.0.0.0" Manufacturer="GoGo" UpgradeCode="9bfe9221-2d7d-46ee-b483-88f00e14b4b3"> <Package InstallerVersion="200" Compressed="yes" InstallScope="perMachine" /> <MajorUpgrade DowngradeErrorMessage="A newer version of [ProductName] is already installed." /> <MediaTemplate /> <Feature Id="ProductFeature" Title="SetupProject1" Level="1"> <ComponentGroupRef Id="ProductComponents"/> </Feature> <!--<Binary Id="WixCA" SourceFile="WixCA.dll" />--> <Property Id="QtExecDeferredExample" Value="InstallManager.exe"/> <CustomAction Id="QtExecDeferredExample" BinaryKey="WixCA" DllEntry="WixQuietExec" Execute="immediate" Return="check" Impersonate="no"/> <InstallExecuteSequence> <Custom Action="QtExecDeferredExample" Before="InstallFinalize">NOT Installed</Custom> </InstallExecuteSequence> </Product> <Fragment> <Directory Id="TARGETDIR" Name="SourceDir"> <Directory Id="ProgramFilesFolder"> <Directory Id="INSTALLFOLDER" Name="SetupProject1" > <Component Id='MainExecutable'> <File Id='InstallManagerEXE' Name='InstallManager.exe' DiskId='1' Source='InstallManager.exe' KeyPath='yes'/> </Component> </Directory> </Directory> </Directory> </Fragment> <Fragment> <ComponentGroup Id="ProductComponents" Directory="INSTALLFOLDER"> <ComponentRef Id='MainExecutable' /> </ComponentGroup> </Fragment> </Wix> A: Your question has two answers. First answer: Generic DLL When you set your custom action, there is an attribute DllEntry="WixQuietExec". You need to include the DLL in the package with this code: <Binary Id="WixCA" SourceFile="WixQuietExec.dll" /> This tag should be created inside the Product. So your code would be like this: ... <Binary Id="WixCA" SourceFile="WixQuietExec.dll" /> <CustomAction Id="QtExecDeferredExample" BinaryKey="WixCA" DllEntry="WixQuietExec" Execute="deferred" Return="check" Impersonate="no" /> ... Don't forget to match the CustomAction[BinaryKey] and Binary[Id]. Second answer: WixUtilExtension Particularly for a standard custom action like QtExec, you need only to include a reference to the extension. * *In Solution Explorer, expand the References in your project *Right-click over it and select Add Reference *Browse for the folder where the WiX Toolset is installed. Then select bin folder. In my case, the full path is C:\Program Files (x86)\WiX Toolset v3.8\bin *Select WixUtilExtension.dll and press Add and then OK Change the Wix tag adding xmlns:util="http://schemas.microsoft.com/wix/UtilExtension". For example, your tag will be: <Wix xmlns="http://schemas.microsoft.com/wix/2006/wi" xmlns:util="http://schemas.microsoft.com/wix/UtilExtension"> A: Try change DllEntry from WixQuietExec to CAQuietExec and property use QtExecCmdLine please reference to https://www.firegiant.com/wix/tutorial/standard-libraries/silence-please/ A: I confronted the same issue (error 1157) when I switched from using CAQuietExec extension to WixQuietExec. I used Wix Toolset 3.9 when error occured. I solved this problem installing Wix Toolset 3.10.1 (it is last stable version now) and WixQuietExec extension works as expected. A: For any one facing this issue when developing the custom action using C#, I suggest to ensure that * *The BinaryKey is referring to the generated *.CA.dll and not the actual dll file. *Ensure that the method being called is decorated with the [CustomAction] attribute.
doc_844
Then I started reading about OCR. So I installed tesseract OCR and tried it on some images. It doesn't even detect something close to the code. I figured after reading some questions on stackoverflow, that the images need some preprocessing like skewing the image to a horizontal one, which can been done by openCV for example. Now my questions are: * *What kind of preprocessing or other methods should be used in a case like the above image? *Secondly, can I rely on the output? Will it always work in cases like the above image? I hope someone can help me! A: I have decided to capture the whole card instead of the code only. By capturing the whole card it is possible to transform it to a plain perspective and then I could easily get the "code" region. Also I learned a lot of things. Especially regarding speed. This function is slow on high resolution images. It can take up to 10 seconds with a size of 3264 x 1836. What I did to speed things up, is re-sizing the input matrix by a factor of 1 / 4. Which makes it 4^2 times faster and gave me a minimal lose of precision. The next step is scaling the quadrangle which we found back to the normal size. So that we can transform the quadrangle to a plain perspective using the original source. The code I created for detecting the largest area is heavily based on code I found on stackoverflow. Unfortunately they didn't work as expected for me, so I combined more code snippets and modified a lot. This is what I got: private static double angle(Point p1, Point p2, Point p0 ) { double dx1 = p1.x - p0.x; double dy1 = p1.y - p0.y; double dx2 = p2.x - p0.x; double dy2 = p2.y - p0.y; return (dx1 * dx2 + dy1 * dy2) / Math.sqrt((dx1 * dx1 + dy1 * dy1) * (dx2 * dx2 + dy2 * dy2) + 1e-10); } private static MatOfPoint find(Mat src) throws Exception { Mat blurred = src.clone(); Imgproc.medianBlur(src, blurred, 9); Mat gray0 = new Mat(blurred.size(), CvType.CV_8U), gray = new Mat(); List<MatOfPoint> contours = new ArrayList<>(); List<Mat> blurredChannel = new ArrayList<>(); blurredChannel.add(blurred); List<Mat> gray0Channel = new ArrayList<>(); gray0Channel.add(gray0); MatOfPoint2f approxCurve; double maxArea = 0; int maxId = -1; for (int c = 0; c < 3; c++) { int ch[] = {c, 0}; Core.mixChannels(blurredChannel, gray0Channel, new MatOfInt(ch)); int thresholdLevel = 1; for (int t = 0; t < thresholdLevel; t++) { if (t == 0) { Imgproc.Canny(gray0, gray, 10, 20, 3, true); // true ? Imgproc.dilate(gray, gray, new Mat(), new Point(-1, -1), 1); // 1 ? } else { Imgproc.adaptiveThreshold(gray0, gray, thresholdLevel, Imgproc.ADAPTIVE_THRESH_GAUSSIAN_C, Imgproc.THRESH_BINARY, (src.width() + src.height()) / 200, t); } Imgproc.findContours(gray, contours, new Mat(), Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE); for (MatOfPoint contour : contours) { MatOfPoint2f temp = new MatOfPoint2f(contour.toArray()); double area = Imgproc.contourArea(contour); approxCurve = new MatOfPoint2f(); Imgproc.approxPolyDP(temp, approxCurve, Imgproc.arcLength(temp, true) * 0.02, true); if (approxCurve.total() == 4 && area >= maxArea) { double maxCosine = 0; List<Point> curves = approxCurve.toList(); for (int j = 2; j < 5; j++) { double cosine = Math.abs(angle(curves.get(j % 4), curves.get(j - 2), curves.get(j - 1))); maxCosine = Math.max(maxCosine, cosine); } if (maxCosine < 0.3) { maxArea = area; maxId = contours.indexOf(contour); //contours.set(maxId, getHull(contour)); } } } } } if (maxId >= 0) { return contours.get(maxId); //Imgproc.drawContours(src, contours, maxId, new Scalar(255, 0, 0, .8), 8); } return null; } You can call it like so: MathOfPoint contour = find(src); See this answer for quadrangle detection from a contour and transforming it to a plain perspective: Java OpenCV deskewing a contour
doc_845
int main() { int x = 5; int x = 6; } My guess is that this would fail in the semantic analysis phase, but I'm not that certain (is it possible that it would fail in the lexical analysis phase as a duplicate token for (int x) would be generated?) Appreciate your help. A: You're right, this program is both lexically and syntactically correct but not semanticaly, assuming that the language you describe here is standard C or C++. C/C++ does not allow redefinition of variables - that's semantics. If your language allowed variable redefinitions, it would be a semantically correct program.
doc_846
a,b,c x,y,z where a is a char *, b contains a float and c contains a double. For an example, the input file can look like this: apple,$12.34,test130.8 x,y,z I want to use fscanf() to read a, b, c and assign each one of them to a corresponding variable. "apple" will be assigned to A of the same data type; "12.34"(not "$12.34") will be assigned to B with a float data type; so on. My attempt was as follows: fp = the file pointer char A[50]; float B; double C; fscanf(fp, "%[^,],%[^,],%[^,]\n", A, B, C); But I realized that %[^,]can only specify type char *; ergo, I'm not allowed to assign type char * to a float or double variable. Is there a way to parse %[^,] to make it only specifies type float? if I only use this: fscanf(fp, "%s,%f,%lf\n", A, B, C); It will be thrown off by the "$" in "12.34", and it will give me 0.000000. A: Using sscanf() (instead of fscanf()) for ease of testing: #include <stdio.h> #include <stdlib.h> int main() { char *s = "apple,$12.34,test130.8\npear,$23.45,abc"; for(int offset = 0, n;; offset += n) { char *symbol; float price; char *note; if(sscanf(s + offset, " %m[^,],$%f,%m[^\n]%n", &symbol, &price, &note, &n) != 3) { break; } printf("symbol: %s, price: %f, note: %s\n", symbol, price, note); free(note); free(symbol); } } and the matching output (note how it demonstrate the evils of using floating points for money): symbol: apple, price: 12.340000, note: test130.8 symbol: pear, price: 23.450001, note: abc I used %m to have scanf() allocate the strings. If I knew the maximum size of the strings I would reuse a fixed size strings instead of dynamically allocating and freeing those. When using fscanf() instead of break you could use feof() to see if we are done, or if the input is invalid. If it's invalid you may want to resync to the next \n with fsccnf(..., "%c", ch). For the above s[offset] == '\0' will tell if you are the end but see below. You may find it's much easier to get a line with fgets(), then use sscanf() similar to above to extract each item. If fails you can report the line and just read the next one. fgets() will return NULL if you have no more data and it leads to cleaner code when you separate I/O and parsing. A: There's already an answer from @AllanWind (using dynamic allocation for strings that my old library doesn't do.) Here's an alternative solution (that is much the same.) First, the input file used for testing: apple,$12.34,test130.8 banana,$20.67,testing201.45 Then the code using fscanf() with a complicated format string: int main( void ) { FILE *fp = fopen( "test.txt", "r" ); if( fp == NULL) { fprintf( stderr, "fopen() failed\n" ); return -1; } char txt[50], word[12]; double dval1, dval2; while( fscanf( fp, " %49[^,],%*c%lf,%11[^0123456789]%lf", txt, &dval1, word, &dval2 ) == 4 ) printf( "'%s' / %.2lf / '%s' / %.2lf\n", txt, dval1, word, dval2 ); fclose( fp ); return 0; } Finally, the output 'apple' / 12.34 / 'test' / 130.80 'banana' / 20.67 / 'testing' / 201.45
doc_847
array = [colors objectAtIndex:indexPath.row]; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"]; cell.selectionStyle = UITableViewCellSelectionStyleNone; UIView *colorBox = [[UIView alloc] initWithFrame:CGRectMake(10,10,20,20)]; [colorBox setTag:1]; [cell.contentView addSubview:colorBox]; } UIView *box = [cell viewWithTag:1]; box.backgroundColor = [self colorForBox:array.color]; return cell; and then getting the colors - (UIColor *)colorForTransport:(NSString*)Line { if([Line isEqualToString:@"Brown"]) return [UIColor colorWithRed:0.682 green:0.38 blue:0.094 alpha:1]; else if([Line isEqualToString:@"Red"]) return [UIColor colorWithRed:0.894 green:0.122 blue:0.122 alpha:1]; else return DefaultBackgroundColor; } Any help would be much appreciated Thanks! A: You might try altering the selectedBackgroundView subview of the tablecellview to get the colour change you are looking for. See http://developer.apple.com/library/ios/documentation/uikit/reference/UITableViewCell_Class/Reference/Reference.html#//apple_ref/occ/instp/UITableViewCell/selectedBackgroundView for more info on that property A: if you're using a plain-style table, then you'll need to alloc-init a new UIView having your desired background colour and then assign it to selectedBackgroundView. Or something like, cell.selectionStyle = UITableViewCellSelectionStyleGray; A: You can create new subclass which inherits from UIView. Then override setBackgroundColor to do nothing. And add your own method which will set background color. In that way system will not be able to override your background color and you can set any color using your new method :) -(void) setBackgroundColor:(UIColor *)backgroundColor { //do nothing } //System do not know this method :) -(void) mySetBackgroundColor:(UIColor *)backgroundColor { [super setBackgroundColor:backgroundColor]; } A: UITableViewCell changes the backgroundColor of all subviews on selection for some reason. This might help: DVColorLockView
doc_848
I need to authenticate to an API which needs OAuth encryption. I'm in the right direction but I am sure something is wrong with my signature base string. Since the HMACSHA1 Hash is based on a Key and BaseString, I get a wrong oauth_signature. OAuth Signing Process So far I have been able to collect all the required pieces of data, which includes: * *Consumer Key *Consumer Secret *Acces Token *Acces Secret *Sha1Hased Value (Based on Key and Message, where Message is the signature Base string) *Signature Base String The Problem I get a HTTP(401 Bad Request) returned because of a invalid signature. note: I'm pretty sure it is how I build my Signature Base String. For info about the API Docs I used, please check bottom page. The Code GetOAuthToken (Doing the actual request) public static string GetAuthorizationToken() { string TimeInSecondsSince1970 = ((int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString(); string Nonce = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(TimeInSecondsSince1970 + TimeInSecondsSince1970 + TimeInSecondsSince1970)); HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(GetAppleApiUrl.GetUrl(AppleApiUrl.SESSION_TOKEN)); httpWebRequest.Method = "GET"; string consumer_secret = Uri.EscapeDataString(Settings.SettingsManager.consumer_secret); string token_secret = Uri.EscapeDataString(Settings.SettingsManager.access_secret); string signature_base_string = GetSignatureBaseString(TimeInSecondsSince1970, Nonce); string SHA1HASH = GetSha1Hash(consumer_secret + "&" + token_secret, signature_base_string); string Header = "OAuth realm=" + '"' + "ADM" + '"' + "," + "oauth_consumer_key=" + '"' + Settings.SettingsManager.consumer_key + '"' + "," + "oauth_token=" + '"' + Settings.SettingsManager.access_token + '"' + "," + "oauth_signature_method=" + '"' + "HMAC-SHA1" + '"' + "," + "oauth_signature= " + '"' + SHA1HASH + '"' + "," + "oauth_timestamp=" + '"' + TimeInSecondsSince1970 + '"' + "," + "oauth_nonce=" + '"' + Nonce + '"' + "," + "oauth_version=" + '"' + "1.0" + '"' + ","; httpWebRequest.Headers.Add(HttpRequestHeader.Authorization, Header); var Result = httpWebRequest.GetResponse(); return Result.ToString(); } GetSha1Hash public static string GetSha1Hash(string key, string message) { var encoding = new System.Text.ASCIIEncoding(); byte[] keyBytes = encoding.GetBytes(key); byte[] messageBytes = encoding.GetBytes(message); string Sha1Result = string.Empty; using (HMACSHA1 SHA1 = new HMACSHA1(keyBytes)) { var Hashed = SHA1.ComputeHash(messageBytes); Sha1Result = Convert.ToBase64String(Hashed); } return Sha1Result; } GetSignatureBaseString public static string GetSignatureBaseString(string TimeStamp, string Nonce) { //1.Convert the HTTP Method to uppercase and set the output string equal to this value. string Signature_Base_String = "Get"; Signature_Base_String = Signature_Base_String.ToUpper(); //2.Append the ‘&’ character to the output string. Signature_Base_String = Signature_Base_String + "&"; //3.Percent encode the URL and append it to the output string. string PercentEncodedURL = Uri.EscapeDataString(GetAppleApiUrl.GetUrl(AppleApiUrl.SESSION_TOKEN)); Signature_Base_String = Signature_Base_String + PercentEncodedURL; //4.Append the ‘&’ character to the output string. Signature_Base_String = Signature_Base_String + "&"; //5.append parameter string to the output string. Signature_Base_String = Signature_Base_String + Uri.EscapeDataString("oauth_consumer_key=" + Settings.SettingsManager.consumer_key); Signature_Base_String = Signature_Base_String + Uri.EscapeDataString("&oauth_token=" + Settings.SettingsManager.access_token); Signature_Base_String = Signature_Base_String + Uri.EscapeDataString("&oauth_signature_method=" +"HMAC-SHA1"); Signature_Base_String = Signature_Base_String + Uri.EscapeDataString("&oauth_timestamp=" + TimeStamp); Signature_Base_String = Signature_Base_String + Uri.EscapeDataString("&oauth_nonce=" + Nonce); Signature_Base_String = Signature_Base_String + Uri.EscapeDataString("&oauth_version=" + "1.0"); return Signature_Base_String; } Result (Fiddler) API Doc A: It looks like you should sort parameters alphabetically in Header string and within GetSignatureBaseString method as described in this comment and Twitter OAuth documentation
doc_849
how do i avoid showing the white body background before my div background loads? any suggestions? HTML <body class="hold-transition skin-blue sidebar-mini sidebar-collapse"> <div class="wrapper" ng-style="{'background': backgroundImg}" > <div class="content-wrapper"> <section class="content"> <div ng-view></div> </section> </div> </body> my route $routeProvider.when('/about',{ templateUrl:'partials/about.php', controller: 'pageController' }); My controller app.controller("pageController",function($scope, $rootScope){ $scope.title = "About Us"; $rootScope.backgroundImg="url('http://abounde.com/uploads/images/abt-min.jpg')"; //abt bg $scope.$on('$viewContentLoaded', function() { console.log("about page loaded"); }); }); A: On this particular page, you could have a div that wraps the entire document. Give this div a class with css ie .document-wrapper-invisible in your css give .display-none class a display property of none .dislay-none { display: none; } When your view content loaded function runs, remove this class. You can simply set a variable to be true and use ng-class to conditionally remove the class. ie <div ng-class="{display-none: !documentLoaded}"> // your page content </div> in your controller $rootScope.$on('$viewContentLoaded', function() { console.log("about page loaded"); $scope.documentLoaded = true; }); Something along these lines should work (I've only ever used rootScope for the viewContentLoaded event, if $scope works on it's own then great) A: From what I understand, the pb is that when you route to another page then you launch a new request to download your background with your url(...). Because this request can take time then you have your white screen. So a solution could be to "preload" all background images when you open your app. So before displaying anything on your app you can display a "loading..." div. In background download all your backgrounds. Once this is done, when changing route then simply change the css class of your wrapper div to the css class containing the correct background image.
doc_850
As stipulated in this article, we need to provide a custom test adapter path pointing to xunit.runner.visualstudio.testadapter.dll. But this package is restored by NuGet to a global packages folder, namely C:\Users\{user}\.dnx\packages? How am I to reference this folder in the build step? We are using VS 2015 and DNX projects. EDIT: I even tried pointing to the package path DLL directly: C:\Users\buildagent\.dnx\packages\xunit.runner.visualstudio\2.1.0-beta4-build1109\build\_common It still did not seem to use the adapter: Executing C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\CommonExtensions\Microsoft\TestWindow\vstest.console.exe "C:\a\8ac4a4f6\Root\artifacts\bin\MyProject.UnitTest\release\dnx451\TransitApi.UnitTest.dll" /TestAdapterPath:C:\Users\buildguest\.dnx\packages\xunit.runner.visualstudio\2.1.0-beta4-build1109\build\_common /UseVsixExtensions:true /logger:trx Microsoft (R) Test Execution Command Line Tool Version 14.0.23107.0 Copyright (c) Microsoft Corporation. All rights reserved. Starting test execution, please wait... Warning: No test is available in C:\a\8ac4a4f6\Root\artifacts\bin\MyProject.UnitTest\release\dnx451\TransitApi.UnitTest.dll. Make sure that installed test discoverers & executors, platform & framework version settings are appropriate and try again. No results found to publish. The project.json, if relevant: "dependencies": { "xunit": "2.1.0-beta4-build3109", "xunit.runner.dnx": "2.1.0-beta4-build134", "xunit.runner.visualstudio": "2.1.0-beta4-build1109" }, "commands": { "test": "xunit.runner.dnx" }, "frameworks": { "dnx451": { } } A: Make a global.json file and put the following into it: { "packages": "packages" } That will force your dnu restore to put the packages into .\packages\, which will hopefully solve the problem. Just specify the test adapter path as $(Build.SourcesDirectory)\packages\ -- you may have to specify the full assembly name, I'm not sure off the top of my head. Update: I took the sample "HelloMvc" application and got it to build with xUnit tests without a global.json. Here's my build definition: { "build": [ { "enabled": true, "continueOnError": false, "alwaysRun": false, "displayName": "Restore packages", "task": { "id": "d9bafed4-0b18-4f58-968d-86655b4d2ce9", "versionSpec": "*" }, "inputs": { "filename": "$(DNXPath)\\dnu.cmd", "arguments": "restore", "workingFolder": "", "failOnStandardError": "false" } }, { "enabled": true, "continueOnError": false, "alwaysRun": false, "displayName": "Run tests", "task": { "id": "d9bafed4-0b18-4f58-968d-86655b4d2ce9", "versionSpec": "*" }, "inputs": { "filename": "$(DNXPath)\\dnx.exe", "arguments": "test", "workingFolder": "", "failOnStandardError": "false" } }, { "enabled": true, "continueOnError": false, "alwaysRun": false, "displayName": "Build NuGet package", "task": { "id": "d9bafed4-0b18-4f58-968d-86655b4d2ce9", "versionSpec": "*" }, "inputs": { "filename": "$(DNXPath)\\dnu.cmd", "arguments": "publish", "workingFolder": "", "failOnStandardError": "false" } }, { "enabled": true, "continueOnError": false, "alwaysRun": false, "displayName": "Publish Artifact: drop", "task": { "id": "1d341bb0-2106-458c-8422-d00bcea6512a", "versionSpec": "*" }, "inputs": { "CopyRoot": "", "Contents": "**\\output\\*", "ArtifactName": "drop", "ArtifactType": "FilePath", "TargetPath": "\\\\ic-tfs-fs-01\\TFSBuilds\\$(Build.DefinitionName)\\$(Build.BuildNumber)" } } ], "options": [ { "enabled": false, "definition": { "id": "7c555368-ca64-4199-add6-9ebaf0b0137d" }, "inputs": { "multipliers": "[]", "parallel": "false", "continueOnError": "true" } } ], "variables": { "BuildConfiguration": { "value": "debug", "allowOverride": true }, "BuildPlatform": { "value": "any cpu", "allowOverride": true }, "DNXPath": { "value": "C:\\Users\\tfs-build\\.dnx\\runtimes\\dnx-clr-win-x86.1.0.0-beta7-12335\\bin\\" } }, "retentionRules": [ { "branches": [ "+refs/heads/*" ], "daysToKeep": 10, "deleteBuildRecord": true } ], "_links": { "self": { "href": "http://ic-tfs-at-01:8080/tfs/InCycleEventsCollection/b3284707-3d86-4bc7-b321-b22aee80daca/_apis/build/Definitions/22" }, "web": { "href": "http://ic-tfs-at-01:8080/tfs/_permalink/_build/index?collectionId=0ea6f8c1-f923-47f0-b59a-af6d452d8f7f&projectId=b3284707-3d86-4bc7-b321-b22aee80daca&definitionId=22" } }, "buildNumberFormat": "$(date:yyyyMMdd)$(rev:.r)", "createdDate": "2015-08-12T15:34:17.887Z", "jobAuthorizationScope": 1, "jobTimeoutInMinutes": 60, "repository": { "id": "ee7584f9-ba25-4535-9b5e-5038ec6a39c7", "type": "TfsGit", "name": "AspNet5", "url": "http://ic-tfs-at-01:8080/tfs/InCycleEventsCollection/BTE2015/_git/AspNet5", "defaultBranch": "refs/heads/master", "clean": "false", "checkoutSubmodules": true }, "quality": 1, "authoredBy": { "id": "7f2b1ec7-224f-41de-b679-17e6ef28ce35", "displayName": "ICTFS-Admin", "uniqueName": "AZURE\\ICTFS-Admin", "url": "http://ic-tfs-at-01:8080/tfs/InCycleEventsCollection/_apis/Identities/7f2b1ec7-224f-41de-b679-17e6ef28ce35", "imageUrl": "http://ic-tfs-at-01:8080/tfs/InCycleEventsCollection/_api/_common/identityImage?id=7f2b1ec7-224f-41de-b679-17e6ef28ce35" }, "queue": { "pool": null, "id": 1, "name": "default" }, "uri": "vstfs:///Build/Definition/22", "type": 2, "revision": 6, "id": 22, "name": "ASP .NET 5 app", "url": "http://ic-tfs-at-01:8080/tfs/InCycleEventsCollection/b3284707-3d86-4bc7-b321-b22aee80daca/_apis/build/Definitions/22", "project": { "id": "b3284707-3d86-4bc7-b321-b22aee80daca", "name": "BTE2015", "url": "http://ic-tfs-at-01:8080/tfs/InCycleEventsCollection/_apis/projects/b3284707-3d86-4bc7-b321-b22aee80daca", "state": "wellFormed", "revision": 383343 I suspect that the problem is that you're trying to use the Visual Studio test adapter. A: I had a similar issue finding the correct path with the NUnit test adapter, here's the path I used in the Test step that ended up working for me, may work for you as well: "$(Build.SourcesDirectory)[your path to the packages folder]\packages\NUnit3TestAdapter.3.8.0\build\netcoreapp1.0" The test adapter dll is in the netcoreapp1.0 folder. Also, KEEP the quotes around the path.
doc_851
* *Reinstalled the Apple WorldWide developer... cert to both system and login, and made sure it is always trusted *Deleted all developer certs from keychain *created a new product and selected automatically manage signing I have dragged a few more Xcode projects (frameworks) such as Alamofire, FileKit, etc., I have embedded the frameworks. Everything works fine until I try archiving and validating and get this error. I have the necessary profiles installed i think. Ideas A: Seems that I had to download a distribution profile manually from my developer account. Xcode didnt do it automatically.
doc_852
The code below shows the ParserTask and getDirections URL. private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String, String>>>> { // Parsing the data in non-ui thread @Override protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) { JSONObject jObject; List<List<HashMap<String, String>>> routes = null; try { jObject = new JSONObject(jsonData[0]); DirectionsJSONParser parser = new DirectionsJSONParser(); routes = parser.parse(jObject); Log.d("routes", routes.toString()); Log.d("jObject", jObject.toString()); } catch (Exception e) { e.printStackTrace(); } return routes; } @Override protected void onPostExecute(List<List<HashMap<String, String>>> result) { ArrayList<LatLng> points = new ArrayList<LatLng>();; PolylineOptions lineOptions = new PolylineOptions();; lineOptions.width(2); lineOptions.color(Color.RED); MarkerOptions markerOptions = new MarkerOptions(); // Traversing through all the routes for(int i=0;i<result.size();i++){ // Fetching i-th route List<HashMap<String, String>> path = result.get(i); for (int j = 0; j < path.size(); j++) { HashMap<String, String> point = path.get(j); double lat = Double.parseDouble(point.get("lat")); double lng = Double.parseDouble(point.get("lng")); LatLng position = new LatLng(lat, lng); points.add(position); } lineOptions.addAll(points); lineOptions.width(12); lineOptions.color(Color.RED); lineOptions.geodesic(true); } // Drawing polyline in the Google Map for the i-th route mMap.addPolyline(lineOptions); } } private String getDirectionsUrl(LatLng origin_start, LatLng dest, LatLng waypoint_xx) { String origin = "origin=" + origin_start.latitude + "," + origin_start.longitude; //String waypointss = "waypoints=optimize:true|" + waypoint_xx.latitude + "," + waypoint_xx.longitude ; String destination = "destination=" + dest.latitude + "," + dest.longitude; // Waypoints String waypoints = ""; for(int i=2;i<markerPoints.size();i++){ LatLng point = (LatLng) markerPoints.get(i); if(i==2) waypoints = "waypoints="; waypoints += point.latitude + "," + point.longitude + "|"; } String sensor = "sensor=false"; String alternative = "alternatives=false"; String params = origin + "&" + destination + "&" + alternative + "&" + sensor + "&" + waypoints ; String output = "json"; String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + params; return url; } This code is the Directions JSON Parser public class DirectionsJSONParser { /** Receives a JSONObject and returns a list of lists containing latitude and longitude */ public List<List<HashMap<String,String>>> parse(JSONObject jObject){ List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String,String>>>() ; JSONArray jRoutes = null; JSONArray jLegs = null; JSONArray jSteps = null; try { jRoutes = jObject.getJSONArray("routes"); /** Traversing all routes */ for(int i=0;i<jRoutes.length();i++){ jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs"); List path = new ArrayList<HashMap<String, String>>(); /** Traversing all legs */ for(int j=0;j<jLegs.length();j++){ jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps"); /** Traversing all steps */ for(int k=0;k<jSteps.length();k++){ String polyline = ""; polyline = (String)((JSONObject)((JSONObject)jSteps.get(k)).get("polyline")).get("points"); List list = decodePoly(polyline); /** Traversing all points */ for(int l=0;l <list.size();l++){ HashMap<String, String> hm = new HashMap<String, String>(); hm.put("lat", Double.toString(((LatLng)list.get(l)).latitude) ); hm.put("lng", Double.toString(((LatLng)list.get(l)).longitude) ); path.add(hm); } } routes.add(path); } } } catch (JSONException e) { e.printStackTrace(); }catch (Exception e){ } return routes; } /** * Method to decode polyline points * Courtesy : http://jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java * */ private List decodePoly(String encoded) { List poly = new ArrayList(); int index = 0, len = encoded.length(); int lat = 0, lng = 0; while (index < len) { int b, shift = 0, result = 0; do { b = encoded.charAt(index++) - 63; result |= (b & 0x1f) << shift; shift += 5; } while (b >= 0x20); int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); lat += dlat; shift = 0; result = 0; do { b = encoded.charAt(index++) - 63; result |= (b & 0x1f) << shift; shift += 5; } while (b >= 0x20); int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); lng += dlng; LatLng p = new LatLng((((double) lat / 1E5)), (((double) lng / 1E5))); poly.add(p); } return poly; } } This is the Download Task private class DownloadTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... url) { String data = ""; try { data = downloadUrl(url[0]); } catch (Exception e) { Log.d("Background Task", e.toString()); } Log.d("parserTask data", data.toString()); return data; } @Override protected void onPostExecute(String result) { super.onPostExecute(result); ParserTask parserTask = new ParserTask(); Log.d("parserTask result", result.toString()); parserTask.execute(result); } } And finally the onMapReady method public void onMapReady(GoogleMap googleMap) { mMap = googleMap; UiSettings uiSettings = googleMap.getUiSettings(); //uiSettings.setCompassEnabled(false); uiSettings.setZoomControlsEnabled(true); //------------- // mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); //Initialize Google Play Services if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { //Location Permission already granted buildGoogleApiClient(); mMap.setMyLocationEnabled(true); } else { //Request Location Permission checkLocationPermission(); } } else { buildGoogleApiClient(); mMap.setMyLocationEnabled(true); } //------------- DatabaseReference myRef = FirebaseDatabase.getInstance().getReference().child("location"); myRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { NotificationCompat.Builder builder = new NotificationCompat.Builder(MapsActivity.this) .setSmallIcon(R.drawable.applogo) .setContentTitle("Trip Request") .setContentText("Click to accept trip!"); manager = (NotificationManager) MapsActivity.this.getSystemService( MapsActivity.this.NOTIFICATION_SERVICE ); manager.notify(0, builder.build()); // sendNotification(); startLatFB = (Double) dataSnapshot.child("startLat").getValue(); startLonFB = (Double) dataSnapshot.child("startLon").getValue(); endLatFB = (Double) dataSnapshot.child("endLat").getValue(); endLonFB = (Double) dataSnapshot.child("endLon").getValue(); Log.d("startLat", startLatFB.toString()); Log.d("startLon", startLonFB.toString()); Log.d("endLat", endLatFB.toString()); Log.d("endLon", endLonFB.toString()); if (markerPoints.size() > 1) { markerPoints.clear(); mMap.clear(); } double startLat = startLatFB; //SLIIT double startLon = startLonFB; double wayPointLat = 6.9040322; //FAB - Malabe double wayPointLon = 79.948803; double wayPointLatTwo = 6.053519; //FAB - Malabe double wayPointLonTwo = 80.220977; double endLat = endLatFB; //MAS double endLon = endLonFB; LatLng start_latLng = new LatLng(startLat, startLon); LatLng waypoint_latLng = new LatLng(wayPointLat, wayPointLon); LatLng end_latLng = new LatLng(endLat, endLon); // LatLng start_latLng = new LatLng(startLatFB, startLonFB); // LatLng waypoint_latLng = new LatLng(wayPointLat, wayPointLon); // LatLng end_latLng = new LatLng(endLatFB, endLonFB); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(start_latLng, 11)); mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(start_latLng,11f)); // start_latLng = startLatFB; // Adding new item to the ArrayList markerPoints.add(start_latLng); markerPoints.add(end_latLng); markerPoints.add(waypoint_latLng); // Creating MarkerOptions MarkerOptions options = new MarkerOptions(); MarkerOptions optionsTwo = new MarkerOptions(); MarkerOptions optionsThree = new MarkerOptions(); BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.drawable.startlocation); BitmapDescriptor icon2 = BitmapDescriptorFactory.fromResource(R.drawable.endlocation); // Setting the position of the marker options.position(start_latLng); optionsTwo.position(end_latLng); optionsThree.position(waypoint_latLng); if (markerPoints.size() == 1) { options.icon(icon); } else if (markerPoints.size() == 2) { options.icon(icon2); } // Add new marker to the Google Map Android API V2 mMap.addMarker(options); mMap.addMarker(optionsTwo); mMap.addMarker(optionsThree); // Checks, whether start and end locations are captured if (markerPoints.size() >= 3) { LatLng origin = (LatLng) markerPoints.get(0); LatLng dest = (LatLng) markerPoints.get(1); LatLng waypointss = (LatLng) markerPoints.get(2); Log.d("origin url", origin.toString()); Log.d("dest url", origin.toString()); Log.d("waypoint url", origin.toString()); // Getting URL to the Google Directions API String url = getDirectionsUrl(origin, dest, waypointss); DownloadTask downloadTask = new DownloadTask(); // Start downloading json data from Google Directions API downloadTask.execute(url); Log.d("DownloadTask url", url); } } @Override public void onCancelled(DatabaseError databaseError) { } }); } A: Try initializing new Arraylist of Points each time while traversing. Here is a sample: @Override protected void onPostExecute(List<List<HashMap<String, String>>> result) { ArrayList<LatLng> points = null; PolylineOptions lineOptions = null; // Traversing through all the routes for(int i=0;i<result.size();i++){ points = new ArrayList<LatLng>(); //initialize here lineOptions = new PolylineOptions(); // Fetching i-th route List<HashMap<String, String>> path = result.get(i); for (int j = 0; j < path.size(); j++) { HashMap<String, String> point = path.get(j); double lat = Double.parseDouble(point.get("lat")); double lng = Double.parseDouble(point.get("lng")); LatLng position = new LatLng(lat, lng); points.add(position); } lineOptions.addAll(points); lineOptions.width(12); lineOptions.color(Color.RED); } // Drawing polyline in the Google Map for the i-th route mMap.addPolyline(lineOptions); } } For detail implementation Go through This Link
doc_853
This is my javascript variable looks like ['08/25','08/26','08/27','08/28','08/29','08/30','08/31','09/01','09/02','09/03','09/04','09/05','09/06','09/07','09/08','09/09','09/10','09/11','09/12','09/13','09/14','09/15','09/16','09/17','09/18','09/19','09/20','09/21','09/22','09/23','09/24','09/25','09/26','09/27','09/28','09/29','09/30','10/01','10/02','10/03','10/04','10/05','10/06','10/07','10/08','10/09','10/10','10/11','10/12','10/13','10/14','10/15','10/16','10/17','10/18','10/19','10/20','10/21','10/22','10/23','10/24','10/25','10/26','10/27','10/28','10/29','10/30','10/31','11/01','11/02','11/03','11/04','11/05','11/06','11/07','11/08','11/09','11/10','11/11','11/12','11/13','11/14','11/15','11/16','11/17','11/18','11/19','11/20','11/21','11/22'] And this is my Javascript, function changeGraph(rate, currency, site_id, room_code, keyword_mst){ var graph_categories = getPeriod(new Date()); $('#hotelByGraph').highcharts( { title: { text: 'Plan Detail', x: -20 //center }, xAxis: { categories: graph_categories }, } } function getPeriod(date){ var periodReturn = '['; var tmp = 1; for(var i = 0 ; i < 90 ; i++){ if(i !== 0) date.setDate(date.getDate()+tmp); else date.setDate(date.getDate()); if(i != 89) periodReturn += "'"+toDoubleDigits(date.getMonth()+1)+"/"+toDoubleDigits(date.getDate())+"',"; else periodReturn += "'"+toDoubleDigits(date.getMonth()+1)+"/"+toDoubleDigits(date.getDate())+"']"; } return periodReturn; } Could you help point out where did I go wrong?
doc_854
* *I have MERN Stack Application running (where frontend reactJS is running inside NodeJS backend server) *The whole application is then wrapped inside Docker Container *Then Deployed in AWS ECS EC2 (using single Service & Task) behind a single Application Load Balancer. *Created a Hosted Zone in AWS Route 53 to Point my domain name to Load Balancer *Now the application is successfully running when I visit my domain name. Problem Araised Here * *The website is "Not Secure"!! — I want to install SSL Certificate *I went to AWS Certificate Manager *Successfully got a certificate by adding CNAME in the AWS Hosted Zone Records *Configured Security Group, Load balancer Listeners to HTTPS *Added that Certificate to Load Balancer listener Actual Problem * *I got the certificate, connected to load balancer, *I can see my certificate in the address bar - "Certificate is Valid" *And still, it shows my the Site is "Not Secure" - Below image is for your reference. Error in the Console (Edited) Mixed Content: The page at 'https://example.com/' was loaded over HTTPS, but requested an insecure resource 'http://my-alb-XXXXXXX.us-xxxx-X.elb.amazonaws.com/api/goals'. This request has been blocked; the content must be served over HTTPS. My Assumption of What Went Wrong * *Since AWS ALB has its own DNS Name, which is "Not Secure" *Connecting my new secured domain name TO an unsecured AWS ALB DNS name would be the problem. Appreciate Your Response Thank you, ARUN
doc_855
list_names = ['annie','betty', 'charlie','debie', 'elf', 'frank', 'goe', 'hayri'] list_ages = [19,23,44,31,55,65,15,40] The ages are corresponding to each name in the list and the target is to create a key:value pair that contains values only older than 30. Thank you for any help. A: Try this list_names = ['annie','betty', 'charlie','debie', 'elf', 'frank', 'goe', 'hayri'] list_ages = [19,23,44,31,55,65,15,40] {name: age for name, age in zip(list_names,list_ages) if age>30} A: Try taking example from this code: list_names = name((k, v) for k, v in list_names.items() if v > 30)
doc_856
But i want to do this while the data is binding... is there a way to do that? also how do i enable/disable a row cell? dgvLayout.AutoGenerateColumns = false; dgvLayout.DataSource = list; in cell click but it does not work if ((dgvLayout.Rows[e.RowIndex].Cells["colControlText"].Value.ToString()) == "-Invalid-") { if (e.ColumnIndex == 2 || e.ColumnIndex == 5) { return; } else if (e.ColumnIndex == 1) { return; } } A: you can write you code on RowsAdded event of datagrid A: you can use this solution for enabling and disabling cell To "disable" a cell, it must be read-only and grayed out somehow. This function enables/disables a DataGridViewCell: /// <summary> /// Toggles the "enabled" status of a cell in a DataGridView. There is no native /// support for disabling a cell, hence the need for this method. The disabled state /// means that the cell is read-only and grayed out. /// </summary> /// <param name="dc">Cell to enable/disable</param> /// <param name="enabled">Whether the cell is enabled or disabled</param> private void enableCell(DataGridViewCell dc, bool enabled) { //toggle read-only state dc.ReadOnly = !enabled; if (enabled) { //restore cell style to the default value dc.Style.BackColor = dc.OwningColumn.DefaultCellStyle.BackColor; dc.Style.ForeColor = dc.OwningColumn.DefaultCellStyle.ForeColor; } else { //gray out the cell dc.Style.BackColor = Color.LightGray; dc.Style.ForeColor = Color.DarkGray; } }
doc_857
$players[$vidIdPlaceholderRef] = new YT.Player('player_' + $vidIdPlaceholderRef, { height: '550', width: '840', videoId: $vidId }); is what I have in place. I have also tried: $players[$vidIdPlaceholderRef] = new YT.Player('player_' + $vidIdPlaceholderRef, { height: '550', width: '840', videoId: $vidId + '?rel=0', rel : 0 }); with no luck. Does any one know of an option which can be added (tried rel : 0 with no luck ) A: You get related videos in two places: at the end of the video with the grid, and at the bottom of the video while paused. I've figured out a way to remove them at the end and make the ones at the bottom at least tolerable for most businesses. 1. Remove related videos at the end of a video IFrame Player API: Events To avoid showing related videos at the end of a video, I just stopped the video so it returned to showing the thumbnail and play button: var player = new YT.Player('player', { height: '390', width: '640', events: { 'onStateChange': function(event){ switch(event.data){ // Stop the video on ending so recommended videos don't pop up case 0: // ended player.stopVideo(); break; case -1: // unstarted case 1: // playing case 2: // paused case 3: // buffering case 5: // video cued default: break; } } } }); You could also replace player.stopVideo(); with any other code you want to run. 2. Making related videos at the bottom of a video only show your videos IFrame Player API: YouTube Embedded Players and Player Parameters rel=0 no longer avoids showing any related videos; now, it will still show related videos, but at least they'll only be from your channel. This changed sometime around September 25, 2018 (documentation). By setting playerVars in YT.Player, we can at least have related videos only show our channel's videos. The documentation isn't clear that you have to have playerVars set up as an object, but you can set it up like so: var player = new YT.Player('player', { ... playerVars:{ rel: 0 modestbranding: 1, // If you're trying to remove branding I figure this is helpful to mention as well; removes the YouTube logo from the bottom controls of the player // color: 'white', // Can't have this and modestbranding active simultaneously (just a note in case you run into this) }, ... }); 2A. Potential way to remove related videos from bottom I may look more into it if I have the time, but here's where an answer may lie: We can easily access the iframe object but we can't do anything with it: IFrame Player API: Accessing and modifying DOM nodes. It appears that because we'd be editing an iframe from YouTube there are security concerns (regardless of what we'd actually be doing). Ideally I could just remove the "More videos" text with player.getIframe().contentWindow.document.querySelector('.ytp-pause-overlay.ytp-scroll-min').remove(), but when I run player.getIframe().contentWindow.document I get an error SecurityError: Permission denied to access property "document" on cross-origin object. But playerVars also has an origin value that may let us access the iframe's object anyway: var player = new YT.Player('player', { ... playerVars:{ origin: 'https://mywebsite.com' }, ... }); It's not working with localhost, but that may be a Chromium and Firefox thing. Perhaps this is a legitimate option on a live site; I'll update this post when/if I try that to let you know if I succeed. A: The accepted solution was not working for me. What does work is: 1) Putting the iframe in html that includes the rel parameter <iframe id="youtube-video" width="560" height="315" src="https://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1&rel=0&modestbranding=1" frameborder="0" enablejsapi="1" allowfullscreen></iframe> 2) Using the javascript API to attach to that existing player var tag = document.createElement('script'); tag.src = "https://www.youtube.com/iframe_api"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); var player; function onYouTubeIframeAPIReady() { player = new YT.Player('youtube-video', { events: { 'onReady': onPlayerReady, 'onStateChange': onPlayerStateChange } }); } function onPlayerReady(event) { console.log("ready"); } function onPlayerStateChange(event) { console.log("state changed"); } demo fiddle: http://jsfiddle.net/bf7zQ/195/ A: The behavior of the rel player parameter has changed. From documentation, The behavior for the rel parameter is changing on or after September 25, 2018. The effect of the change is that you will not be able to disable related videos. However, you will have the option of specifying that the related videos shown in the player should be from the same channel as the video that was just played So, it's no longer possible to disable related videos. Instead playerVars: {rel:0} will change the behavior of the player and shows suggestion from specified channel. A: "rel" is a player parameter, as specified here: https://developers.google.com/youtube/player_parameters#rel To add player parameters to iframe players, you need to specify the playerVars property of the second constructor argument (at the time of writing this is documented here, and on the IFrame API documentation page) e.g. new YT.Player('playerid', { height: '550', width: '840', videoID: 'video_id', playerVars: {rel: 0, showinfo: 0, ecver: 2} }); A: If you're using SWFObject, you simply need to do something like this: function loadVideo() { var params = { allowScriptAccess: "always" } , atts = { id: "myvideo" } ; //NOTE THE END OF THE BELOW LINE vvvvvv swfobject.embedSWF("https://www.youtube.com/v/[video id here]?enablejsapi=1&playerapiid=myvideo&version=3&rel=0" , "videoplaceholderid" , "768", "432", "8", null, null, params, atts); } Just add rel=0 to the end of your url. A: No need to code through the API,now its easily can be done by You tube embed button -> Show more -> tickout the option 'Show suggested videos when the video finishes' A: Here is a Quick solution: setInterval(function(){ if($('iframe').length > 0){ $('iframe').each(function(){ if($(this).hasClass('gotYou')){ //do nothing }else{ var getMySrc = $(this).attr('src'); var newSrc = getMySrc.split('?'); console.log(newSrc); var freshURL = newSrc[0]+'?rel=0&'+newSrc[1]; console.log(freshURL); $(this).addClass('gotYou'); $(this).attr('src', freshURL ); } }); } }, 1); What it does it, it looks for the iframe in your document. If it finds iframe, it grabs the src of the iframe, finds the ? mark and then replaces ? by ?rel=0& . Here the goal is to out rel=0 A: new YT.Player('playerid', { height: '550', width: '840', videoID: 'video_id', playerVars: {rel: 0}, });
doc_858
I have a template class that starts like this in my .h: template <class DOC_POLICY, class PRINT_POLICY, class UNDO_POLICY> class CP_EXPORT CP_Application : public CP_Application_Imp Now I need to initialize so in my .cpp so I do: CPLAT::CP_DocumentPolicy_None * d = new CPLAT::CP_DocumentPolicy_None(); CPLAT::CP_PrintPolicy_None * p = new CPLAT::CP_PrintPolicy_None(); CPLAT::CP_UndoPolicy_None * u = new CPLAT::CP_UndoPolicy_None(); CPLAT::CP_Application::Init(d, p, u); I get an error on CPLAT::CP_Application::Init(d, p, u); that states: error: 'template class CPLAT::CP_Application' used without template parameters How does one pass template parameters? A: I believe it should work CPLAT::CP_Application<CPLAT::CP_DocumentPolicy_None,CPLAT::CP_PrintPolicy_None,CPLAT::CP_UndoPolicy_None>::Init(d,p,u); A: * *You have a class template, not a "template class". It's a template from which classes can be generated. (There's also function templates. Those are templates from which functions are generated.) *It takes type parameters. d, p, and u are (pointers to) objects, not types. Types are, for example, CPLAT::CP_DocumentPolicy_None, CPLAT::CP_PrintPolicy_None, and CPLAT::CP_UndoPolicy_None. So you should be able to do CP_Application< CPLAT::CP_DocumentPolicy_None , CPLAT::CP_PrintPolicy_None , CPLAT::CP_UndoPolicy_None > app; *When you have function templates, where template parameters are also function parameters (they appear as types in the function's argument list), you can omit them in the list of actual template arguments when instantiating the template: template< typename T > void f(T obj) {...} ... f(42); // same as f<int>(42), because 42 is of type int This is automatic function argument deduction. *Instead of having to call an Init member function, have the constructor initialize the object.
doc_859
export LC_CTYPE=en_US.UTF-8 export LC_ALL=en_US.UTF-8 everytime i create a new database for the django app. Is it possible to avoid this? What should i do to avoid this? Need some guidance on this.. A: Go to the bash_profile file in your home directory and add the two statements in it...
doc_860
A: I've found decision for my child parameter go-blank problem. In the Report Parameters dialog just print to the 'non-queried' field default value in quotes. For example, in case of olap data source: print ="[Calendar].[Quarter].&[All]" instead of: [Calendar].[Quarter].&[All] After this Quarter child cascading parameter will not lose it's default value 'All' when user chooses another Year. Nuts! A: There is nothing you can do by keeping the default value to "All". That is for only the first time the report is rendered. Once you change the parent parameter, the child value is refreshed and then it starts looking towards "Available values" set. So, whatever values are coming from the dataset which is the source of Available Values, will be considered to populate the child parameter then. So only way you can still have an "All" still, is to modify the dataset. We could probably help you further if you could share the MDX queries for the parameters, or even you could give it as shot.
doc_861
So I have no idea what I'm doing wrong, all other 'solutions' on this website haven't been working for me, so could you please tell me what I'm doing wrong, or rather what I'm not doing. import Foundation import UIKit enum gameType { case easy case medium case hard case player2 case impossible } func pauseGame() { // HERE IS WHERE I GET THE ERRORS... IN THIS FUNCTION self.isPaused = true currentGameType = gameType.pauseGame self.physicsWorld.speed = 0 self.speed = 0.0 } class MenuVC : UIViewController { @IBAction func Player2(_ sender: Any) { moveToGame(game: .player2) } @IBAction func Easy(_ sender: Any) { moveToGame(game: .easy) } @IBAction func Medium(_ sender: Any) { moveToGame(game: .medium) } @IBAction func Hard(_ sender: Any) { moveToGame(game: .hard) } @IBAction func Impossible(_ sender: AnyObject) { moveToGame(game: .impossible) } func moveToGame(game : gameType) { let gameVC = self.storyboard?.instantiateViewController(withIdentifier: "gameVC") as! GameViewController currentGameType = game self.navigationController?.pushViewController(gameVC, animated: true) } } A: At the top of your file, gameType is an enumeration. That means that there are a finite set of cases that it can have (the game type can either be easy, medium, hard, etc.) In your code, you're attempting to use a case called pauseGame, but if you look at the definition of gameType there's no case with that name. So you either need to a) add a pauseGame case to gameType (does it make sense for pauseGame to be a "kind" of game?) or not set the gameType inside your pauseGame function. My instinct is that you don't actually want to change the type of the game when the user pauses it, so you can probably just get rid of that line. Also, a note on style -- it's good to start the names of types with capital letters to distinguish them from functions and local variables (so GameType instead of gameType.)
doc_862
"A state mutation was detected between dispatches" please let me know, where I am doing it wrong. classInfo[ { Id:"", students:[] }] function sampleReducer(state = initialState.classInfo, action) { switch (action.type) { case types.ADD_CLASSROOMS: return [...state, ...action.data]; case types.REMOVE_CLASSROOMS: return state.filter((class) => class.id !== action.data); case types.ADD_STUDENT_DETAILS: const stateObj = state.map((class, i) => { if (class.id === action.data.id) { return { ...class, students: { ...action.data.students, }, }; } return { ...class, }; }); return stateObj; default: return state; } } A: You are spreading object for students. It's an array. So use square brackets and spread the students array - students: [...action.data.students] ... case types.ADD_STUDENT_DETAILS: const stateObj = state.map((class, i) => { if (class.id === action.data.id) { return { ...class, students: [ //<----use square brackets(as its an array) ...action.data.students ], }; } return class; }); return stateObj; ... A: You are doing great, do not to mutate the state simply means, do not alter the prevState just update the state. The main error is that, you are trying to change state of student as previously it was array type and while you are updating it you made it as object type just a typo. please use [ ] instead of { } const state = { id: 1, students: [ {first: 1}, {second: 2}, {third: 3} ] } const action = { data: { students: [ {fourth: 4} ] } } const updatedStudents = { ...action.data.students } console.log(state); console.log(updatedStudents); So, in your case-> case types.ADD_STUDENT_DETAILS: const stateObj = state.map((class, i) => { if (class.id === action.data.id) { return { ...class, students: [ ...action.data.students, ], }; } return { ...class, }; }); return stateObj;
doc_863
The code is as below: from mongokit import * connection = Connection() @connection.register class Test(Document): structure = {'title': unicode, 'body': unicode} On the python shell: test = connection.testdb.testcol.Test() test['foo'] = u'bar' test['title'] = u'my title' test['body'] = u'my body' test.save() This gives me a StructureError: unknown fields ['foo'] in Test I have an application where, while I have a core of fields that are always present, I can't predict what new fields will be necessary beforehand. Basically, in this case, it's up to the client to insert what fields it find necessary. I'll just receive whatever he sends, do my thing, and store them in mongodb. But there is still a core of fields that are common to all documents, so it would be nice to type and validate them. Is there a way to solve this with mongokit? A: According to the MongoKit structure documentation you can have optional fields if you use the Schemaless Structure feature. As of version 0.7, MongoKit allows you to save partially structured documents. So if you set up your class like this, it should work: from mongokit import * class Test(Document): use_schemaless = True structure = {'title': unicode, 'body': unicode} required_fields = [ 'title', 'body' ] That will require title and body but should allow any other fields to be present. According to the docs: MongoKit will raise an exception only if required fields are missing
doc_864
My MKMapViewDelegate's - (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated selector is never called while i pan the map (but is called while zooming) in iPhone 5.0 simulator. It works as it should (or at least i suppose it should) on 4.3 simulator and 4.3 device. I don't have access to 5.0 device at the moment. Situation: I have a MKMapView instance (created in Interface Builder) - i double checked it in viewWillLoad - (void)viewDidLoad { assert(self.myMapView); [self.stopMapView setDelegate:self]; } I further define some of the MKMapViewDelegate's selectors, but the ones that concern me are: - (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated { RKLogDebug(@"Will Change map longSpan: %lf", mapView.region.span.longitudeDelta); } - (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated { RKLogDebug(@"Did Change map longSpan: %lf", mapView.region.span.longitudeDelta); } What's going on here? The delegate is not somehow informed about the 'panning' in the MKMapView while on iPhone 5.0 Simulator. I already tried to reset simulator content but to no avail. I wonder whether is it just some simulator bug or iOS5's intended behavior? (I'm on 10.7.2 & Xcode 4.2). A: I added the two methods to my project. Tested iPhone 5.0 simulator: zooming / panning -> methods get called I'm on 10.7.2 & Xcode 4.2 too. So I can confirm it's not intented behavior as you thought it could be. Hope it helps.
doc_865
<SwaggerUI url={SPEC_FILE} responseInterceptor={(response: Response) => { //console.log("response ", response); if (response.url === REQUEST_URL && response.status === 200) { setData(response.data); } }} /> However when using the above in React with TypeScript, I get the following error at responseInterceptor: No overload matches this call. Overload 1 of 2, '(props: Readonly<SwaggerUIProps>): SwaggerUI', gave the following error. Type '(response: Response) => void' is not assignable to type '(res: Response) => Response | Promise<Response>'. Types of parameters 'response' and 'res' are incompatible. Type 'Response' is missing the following properties from type 'Response': headers, ok, redirected, status, and 12 more. Overload 2 of 2, '(props: SwaggerUIProps, context?: any): SwaggerUI', gave the following error. Type '(response: Response) => void' is not assignable to type '(res: Response) => Response | Promise<Response>'.ts(2769) index.d.ts(27, 5): The expected type comes from property 'responseInterceptor' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<SwaggerUI> & Readonly<SwaggerUIProps> & Readonly<...>' index.d.ts(27, 5): The expected type comes from property 'responseInterceptor' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<SwaggerUI> & Readonly<SwaggerUIProps> & Readonly<...>' Anyone has ideas how to use Swagger UI's responseInterceptor in TypeScript? A: Nice folks at typescript group helped me, so i thought to share the answer here, i just needed to return the response. <SwaggerUI url="https://api.mna.dev.spsapps.net/swagger/?format=openapi" responseInterceptor={response => { if (response.status === 200) { console.log(response.data); } return response; // this is what i needed to do. }} />
doc_866
The solution provided to the question didn't really work for my case. My use case is different in the way that there is an extra active input field above the hidden username field. Google Smart Lock will grab the value from the active input field instead of my hidden username input field This is Chromium Design document talking about Google Smart Lock will use a display: none username but it doesn't mention my use case. div { margin: 3px; } #email { display: none; } <form> <div> <label>Verification Code</label> <input type='text' /> </div> <div> <input type='email' autocomplete='username' id='email' /> </div> <div> <label>Password</label> <input type='password' autocomplete='new-password' /> </div> <input type="submit" value="Verify"> </form> A: short answer, put hidden email input first and then use css to reverse the order: .flex-container { display: flex flex-direction: row; } Check out this article that explains how to make it work on Chrome, Firefox and Safari for 3 different cases: normal login, username first login and reset password page with verification input first.
doc_867
But, when I am decoding the buffers on the client side they are seems to be overlapping, Meaning that the new chunk of data is being played few milliseconds before the previous one ended, causing the audio to lag. is there any way to make the client wait until the current buffer is finished before starting the new one? Server: var BinaryServer = require('binaryjs').BinaryServer; var fs = require('fs'); var server = BinaryServer({port: 9000}); server.on('connection', function(client){ var file = fs.createReadStream(__dirname + '/Song.mp3', { 'flags': 'r', 'bufferSize': 4 * 1024 }); }); client.send(file); }); Client: var client = new BinaryClient('ws://localhost:9000'); window.AudioContext = window.AudioContext || window.webkitAudioContext; var context = new AudioContext(); client.on('stream', function (stream, meta) { var parts = []; var last = 0; stream.on('data', function (data) { var source = context.createBufferSource(); context.decodeAudioData(data, function (buf) { source.buffer = buf; source.connect(context.destination); source.loop = false; source.start(last); last += buf.duration; source.onended = function() { console.log('Your audio has finished playing'); }; }, function (e) { "Error with decoding audio data" + e.err }); parts.push(data); }); stream.on('end', function () { console.log(parts); }); }); A: Not sure about this, but instead of initializing last to 0, you might want to initialize it to context.currentTime.
doc_868
[2018-07-10 15:04:11] USER INPUT "hello" [2018-07-10 15:04:12] SYSTEM RESPONSE: "Hello! How are you doing today" [2018-07-10 15:04:42] USER INPUT "I am doing good thank you" [2018-07-10 15:04:42] SYSTEM RESPONSE: "Good to know" in a way that I just have the data from double quotes in a list ["hello","Hello! How are you doing today","I am doing good thank you","Good to know"] I am trying to use corpus_raw = "" for log_filename in log_filenames: print("Reading '{0}'...".format(log_filename)) with codecs.open(log_filename, "rb", encoding='utf-8', errors='ignore') as log_file: corpus_raw += log_file.read() corpus_raw= re.findall(r'\[(.*?)\]\s+', corpus_raw) print("Corpus is now {0} characters long".format(len(corpus_raw))) print() but I am not able to get any results with that. Any suggestions will help! Thanks A: You can use .*?: import re contents = [re.findall('"(.*?)"', i.strip('\n'))[0] for i in open('filename.txt')] Output: ['hello', 'Hello! How are you doing today', 'I am doing good thank you', 'Good to know'] A: You can simply split corpus_raw by " and get every other item within the list: corpus_raw = "" for log_filename in log_filenames: print("Reading '{0}'...".format(log_filename)) with codecs.open(log_filename, "rb", encoding='utf-8', errors='ignore') as log_file: corpus_raw += log_file.read() print("Corpus is now {0} characters long".format(len(corpus_raw))) print() corpus_raw = corpus_raw.split('"')[1::2] corpus_raw would become (given your sample input): ['hello', 'Hello! How are you doing today', 'I am doing good thank you', 'Good to know'] A: Use cut: $ cut -d'"' -f2 < so.txt hello Hello! How are you doing today I am doing good thank you Good to know
doc_869
The instructions that came with the project (libssl) say to run "VCVARS32.BAT" and then "nmake". When I run VCVARS32.BAT, the following error message is emitted: \Common was unexpected at this time A similar issue was discussed in SO (#8756828) but that one applied to modifying VCVARS32 which I am not doing. An answer to that also mentioned quote marks within the PATH, but I checked and that is not so. I am running from a base CMD.EXE prompt on a Dell Win10-64 machine. Any idea why this is happening? A: I found a fix. The problem was quotes ("") in the PATH as suggested in answer to SO #8756828. Strangely, there were NO quotes in ControlPanel->System->Advanced->EnvironmentVariables->SystemVariables->PATH or in the Registry, however "echo %PATH%" did show quotes. By trial and error, I discovered that the offending component in my PATH was C:\Program Files (x86)\Common Files\Oracle\Java\javapath When I removed that, all was good. At first, I suspected that the embedded spaces were the culprit, but then I noticed other PATH components with embedded spaces that caused no problems. So, I still don't understand what was going on but at least I have a working fix.
doc_870
my App.js looks like this class App extends Component { render() { return ( <BrowserRouter> <Switch> <MyCustomLayout> <Route path="/mypath" component={myComponent} /> </MyCustomLayout> </Switch> </BrowserRouter> ) } Here is the code for myComponent import React, { Component } from 'react'; import './index.css'; import { getList } from './apiService.js'; class myComponent extends Component { constructor(props) { super(props); this.state = { myList: [], }; } componentDidMount() { // get list ajax call getList().then(response => { this.setState({ myList: response.data }) }); } handleClick = () => { this.props.history.push('/home'); } renderMyList() { /* Code for rendering list of items from myList state */ } render() { return ( <div> <h1>Hello World</h1> <button onClick={this.handleClick}>Click me</button> {this.renderMyList()} </div> ) } } export default myComponent Here is the code for my test import React from 'react'; import myComponent from './myComponent'; import renderer from 'react-test-renderer'; import { shallow, mount } from 'enzyme'; import sinon from 'sinon'; test('Initial state of myList should be empty array ', () => { const component = shallow(<myComponent/>); expect(component.state().myList).toEqual([]); }); test('Make sure the componentDidMount being called after mount', () => { sinon.spy(myComponent.prototype, 'componentDidMount'); const component = mount(<myComponent/>); expect(myComponent.prototype.componentDidMount.calledOnce).toEqual(true); }); What does the error ? A: Had this issue here the other day - the reason you're getting this error is because you're trying to mount a <Route /> or a <Link /> or a component wrapped with withRouter() when there's no <Router /> surrounding the code. These components are expecting a certain context to be there (which <Router /> provides), so in order to test these components, you have to mount the component inside a <MemoryRouter />. Here's a function that does this for you: const mountWithRouter = Component => mount( <MemoryRouter> {Component} </MemoryRouter> ); And here's how you use it: test('Make sure the componentDidMount being called after mount', () => { sinon.spy(myComponent.prototype, 'componentDidMount'); const component = mountWithRouter(<myComponent/>); expect(myComponent.prototype.componentDidMount.calledOnce).toEqual(true); }); That being said, I ended up trying to remove most of my mounted test code when migrating to react-router@^4.0.0 - it's a lot of hassle. The major downside of this is that your const component in this test no longer is a myComponent, but a MemoryRouter. That means you can't dig into its state etc quite as easily. Edit: An example of what I did when I did need to check the state of a component that I "had" to mount was that I shallow-rendered it instead, and then ran the life cycle methods I needed manually, like this: test('populates state on componentDidMount', () => { const wrapper = shallow(<MyComponent />); wrapper.instance().componentDidMount(); expect(wrapper.state()).toBe({ some: 'state' }); }); This way, I don't have to deal with the router issue at all (since no mount), and I still get to test what I need to test.
doc_871
A: A C-Style array is just a "naked" array - that is, an array that's not wrapped in a class, like this: char[] array = {'a', 'b', 'c', '\0'}; Or a pointer if you use it as an array: Thing* t = new Thing[size]; t[someindex].dosomething(); And a "C++ style array" (the unofficial but popular term) is just what you mention - a wrapper class like std::vector (or std::array). That's just a wrapper class (that's really a C-style array underneath) that provides handy capabilities like bounds checking and size information.
doc_872
FooType : (Type, Type) FooType = (Int, Int) fst FooType -- Int : Type I would like to use somehow this feature in Scala so that I can reuse type members over different methods: class Foo { type FooType = (Int, Int) def foo : FooType = { ... } def bar : Int = { ... } // Here I would like to reuse the first type of FooType (Int) } What is the recommended way to accomplish this in Scala? A: I think the closest you can get is using a type member: trait TupleType[T] { type Member = T } implicit def toTuple[T](a: (T, T)) = new TupleType[T] {} type FooType = TupleType[Int] def foo: FooType = (1, 2) def bar: FooType#Member = 1 Otherwise you could just use a type alias for your tuple member type: type A = Int type FooType = (A, A) def foo: FooType = (1, 2) def bar: A = 1 A: It is more or less possible if you create the necessary infrastructure yourself. In scala type level functions aren't really first class. They are implemented at the library level with implicits. scala> :paste // Entering paste mode (ctrl-D to finish) sealed trait Deconstruct[T <: (_,_)] { type fst type snd def fst(t: T): fst def snd(t: T): snd } object Deconstruct { implicit def mkDeconstruct[A,B] = new Deconstruct[(A,B)] { type fst = A type snd = B def fst(t: (A,B)): A = t._1 def snd(t: (A,B)): B = t._2 } } // Exiting paste mode, now interpreting. defined trait Deconstruct defined module Deconstruct scala> type FooType = (Int,Int) defined type alias FooType scala> def foo: FooType = (1,2) foo: (Int, Int) scala> def bar(implicit d: Deconstruct[FooType]) = d.fst(foo) bar: (implicit d: Deconstruct[(Int, Int)])d.fst scala> bar res0: Int = 1
doc_873
Possible Duplicate: Building Dynamic LINQ Queries based on Combobox Value I am using LINQ within C# to connect to a DBML relationship. Currently, all of my queries have been static (from x in table select x.item), however now I have built a pseudo adhoc report system for my client. The client can pick some items from a box and filter. When the user submit the filtered data, I am storing everything in a custom object. The object holds the table name, table item name, constraint (>, <, +, contains, etc), and the text to filter on. I gather all of these attributes into an object and I need to be able to query off of it. For example, my filtered object could come back as the following: tblCars, strCarType, =, "Ford" My application has a central table that needs to join to each one of the tables that comes in after the filtration, and then query on that data to get the results. What is the best approach to dynamically build the LINQ query with the joins?
doc_874
However, I want the Form to receive the event after it has been to the focused control. As a test I have placed a TextBox on a Form. Upon typing in the TextBox it should perform it's default behavior, upon pressing certain key commands. Ctrl-S, F1, etc, I want those to bubble through the TextBox up to the Form to be handled at a higher level. These commands are those that the TextBox doesn't do by default. I do need the events to go through the TextBox first though. The application this functionality is needed in is more complex than this simple example. For example, when the TextBox is the focused control it should perform the default Copy & Paste using Ctrl-C and Ctrl-V. However, when various other controls are focused these commands need to end up at the top-most Form-level to be processed there. Edit: It seems that input events go from Form to Focused Control and not the other way around like I was expecting. If it went from Focus to Form I probably wouldn't be having the problem I have. Edit2: Having read (briefly) though this article: http://www.codeproject.com/KB/WPF/BeginWPF3.aspx I am now assuming that the sort of 'bubbling' that I was expecting to just 'be there' is only available in WPF, and not standard C#. I think I'm going to have to re-think the way in which the users interact with my app as opposed to writing swathes of ugly code. Big points to anyone who can reply on doing WPF-style bubbling in C# without ugly code. A: You may still use KeyPreview property but check which control is focused, if it is a textbox then do nothing, else if it is another control - say RichTextBox - then handle the pressed keys. To get the currently focused control, you may need to access Win32 API. Example: Created a new Windows forms application, add a text box and a richtext box in the form, set the KeyPreview property of the form to true, add an event handler for the KeyDown event of the form, the textbox, and the richtextbox. Also the following using statement: using System.Runtime.InteropServices;//for DllImport then replace the code of the form by the following code: public partial class Form1 : Form { // Import GetFocus() from user32.dll [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Winapi)] internal static extern IntPtr GetFocus(); protected Control GetFocusControl() { Control focusControl = null; IntPtr focusHandle = GetFocus(); if (focusHandle != IntPtr.Zero) // returns null if handle is not to a .NET control focusControl = Control.FromHandle(focusHandle); return focusControl; } public Form1() { InitializeComponent(); } private void Form1_KeyDown(object sender, KeyEventArgs e) { Control focusedControl = GetFocusControl(); if (focusedControl != null && !(focusedControl is TextBox) && e.Control && e.KeyCode == Keys.C)//not a textbox and Copy { MessageBox.Show("@Form"); e.Handled = true; } } private void richTextBox1_KeyDown(object sender, KeyEventArgs e) { if(e.Control && e.KeyCode == Keys.C) MessageBox.Show("@Control"); } private void textBox1_KeyDown(object sender, KeyEventArgs e) { if (e.Control && e.KeyCode == Keys.C) MessageBox.Show("@Control"); } } A: Check out the link given below. http://www.vbdotnetforums.com/windows-forms/30257-solved-ctrl-s-combobox.html Hope this helps. Regards, Raja A: You have to implement it manually unfortunately - implement the KeyDown event handler in your form, check for the global key combinations and set KeyPressEventArgs.Handled = true for them. For reference: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keydown.aspx A: You can implement an event handler for the textbox's KeyPress and/or KeyUp/KeyDown events. In your event handler of the KeyPress event, if you set the Handled property on the event args to true, then the event will not be passed on to the textbox. If you don't set it to true, it will be. (Edited to clarify the second paragraph).
doc_875
This is my userDirectory page, only added a subheader and a data table which I got from Vuetify <template> <div class="userDirectory"> <v-subheader class="d-flex justify-space-between align-center"> <h3>User Directory</h3> </v-subheader> <v-row> <v-card> <template> <v-data-table :headers="headers" :items="users" :items-per-page="5" class="elevation-1"></v-data-table> </template> </v-card> </v-row> </div> </template> <script> import axios from 'axios' export default { data: () => ({ headers: [ { text: 'User ID', align: 'start', sortable: false, value: 'u.id', }, { text: 'Created At', value: 'created_at' }, { text: 'Email', value: 'email' }, { text: 'Is Premium', value: 'is_premium' }, { text: 'Goal', value: 'goal' }, { text: 'Fitness Level', value: 'fitness_level' }, { text: 'Profile Completed', value: 'profile_completed' }, { text: 'Accepted Health Warning', value: 'accepted_health_warning' }, { text: 'Role', value: 'roles_list' }, ], users: [], }), methods: { async loadUsers() { axios.get('https://somehost/api/admin/getUserList', { headers: {Authorization : 'Bearer ' + 'token' }}) .then(res=> console.log(res)) .catch(err=> console.log(err)) } }, } </script> <style scoped> </style> and this is the API file. I can get the data by making a GET request in Thunder Client, with a bearer token but the same token doesn't work in Vue. const { response } = require("express"); const pool = require("../../config/database"); async function listUsers() { let sqlquery = `select u.id, created_at, email, is_premium, goal, fitness_level, profile_completed, accepted_health_warning, group_concat(r.name) as roles_list from users u left join user_role ur on ur.user_id = u.id left join role r on r.id = ur.role_id group by u.id;` return new Promise((resolve, reject) => { pool.query(sqlquery, (error, results) => { if (error) { return reject(error) } return resolve(results) }) }) } module.exports.listUsers = listUsers; A: Do you, at any point, call the loadUsers function? <script> export default { // ... data created() { this.loadUsers(); }, methods: { loadUsers() { axios.get('https://somehost/api/admin/getUserList', { headers: {Authorization : 'Bearer ' + 'token' }}) .then(res=> { // assign the result to the users array this.users = res; }) .catch(err=> console.log(err)) } }, } </script> A: Like Matt say, you need to call your function, if you don't nothing happend. created() { this.loadUsers(); }, But indeed (if you call it now) the cors failed the request and you don't get any responses. It's normal. The server api where you do the request block the access and you got the cors error, i see in your file you require express, so i'm pretty sur you use express(nodejs). You can try to install the node-cors package with the command: npm install cors Docs ir: https://expressjs.com/en/resources/middleware/cors.html In your app.js you do that: const app = express() const cors = require('cors'); app.use(cors({ origin: 'https://mywebsite.com' })) The origin is to authorize your vuejs app, so if your Vue app is running on localhost:3000 or online on mondomaine.com you do this: origin: 'http://mondomaine.com' This solution works for online domain. In case you'r in localhost, you have to setup a proxy on vue.js, it's not difficult. In your case you have to replace the url when you get: axios.get('/api/admin/getUserList', ... // let what you have before To understand, the call GET is now on localhost:1000/api/admin/getUserList, this call is on the same domain and doesn't work, but you don't have cors problem. Now you have to setup a proxy, it's pretty easy! devServer: { proxy: { '^/api/*': { target: 'https://somehost/' } } }, Your call localhost:1000/api/admin/getUserList will trigger the proxy ^/api/* and redirect this call to https://somehost/api/admin/getUserList Don't forget to restart you vue server after every update in vue.config.js.
doc_876
var customDiv = $('<div />', { class: 'myCustDiv'}); customDiv.append( $('<textarea />', { class: 'mycustTextarea' }) ); How do I add text above the textarea? See below expected output: A: You can add <label> element, for example: var customDiv = $('<div />', { class: 'myCustDiv'}); customDiv.append( $('<label>Add Your Number</label>' ); customDiv.append( $('<textarea />', { class: 'mycustTextarea' }) ); To add class names you can use HTML attributes instead of passing object: customDiv.append( $('<label class="myTextareaLabel">Add Your Number</label>' ); A: Try this: var customDiv = $('<div />', { class: 'myCustDiv', html: 'Add Your number'}); customDiv.append( $('<textarea />', { class: 'mycustTextarea' }) ); DEMO A: Try this fiddle var customDiv = $("<div class='myCustDiv'></div>"), textArea = $(customDiv).append(("<textarea class='mycustTextarea'>")), blockText = $("<p>Block of Text</p>"); $('#printArea').append(textArea); $(customDiv).prepend(blockText)
doc_877
When the user right clicks on the label of the tab a costume contextMenu should appear.But i don't want to add .setContextMenu(...) for each tab instead to use something like this: tabPane.setOnMouseClicked(m -> { if (m.getButton() == MouseButton.SECONDARY) { Node pick = m.getPickResult().getIntersectedNode(); for (Tab tab : getTabs()) { if (pick.toString().contains(tab.getText())) { contextMenu.show(tab, m.getScreenX(), m.getScreenY()); break; } } } }); but i can't figure it out how to use pickResult for this. Why .i am doing this is cause the tabs may be hundrends and i don't want to spend so much memory for adding a new ContextMenu for each tab so i use only one with defferent tab every time.
doc_878
For example: * *Turn radius: 4° *Original angle = 0° *Input angle = 180.01° *Output angle = -4° or 356° (actual output should be within [0, 360) of course) or * *Turn radius: 4° *Original angle = 0° *Input angle = 179.99° *Output angle = 4° or * *Turn radius: 4° *Original angle = 45° *Input angle = 46° *Output angle = 46° I am not sure exactly how to properly wrap the angle, so I'm a bit stuck here. A: First, find the difference between the original angle and the input angle. (Just subtract.) Then, "normalize" this difference to between -180 degrees and 180 degrees. normalized_difference = (((( raw_difference % 360) + 540) % 360) - 180) Then, if the "normalized" difference is outside the desired range, change it to be within range. Then add the (possibly changed) normalized difference to the original angle to get the output angle. If you wish to normalize the output angle to between 0 degrees and 359.99... degrees, you can do it thus: normalized_angle = (((raw_angle % 360) + 360) % 360) A: Based on @robert-lozyniak's answer, this is what I ended up with: fn clamp_angle_update(angle: u8, target: u8, limit: u8) -> u8 { let mut difference = target as isize - angle as isize; // normalize the difference difference += 256 + 256 / 2; difference %= 256; difference -= 256 / 2; let limit = limit as isize; difference = if difference > limit { limit } else if difference < -limit { -limit } else { difference }; // add the difference to the original angle let mut angle = angle as isize + difference; // normalize the angle angle %= 256; angle += 256; angle %= 256; angle as u8 }
doc_879
var request = require('request'); var fs = require('fs'); var http = require('http'); var _HttpContent = ""; var pageindex = 1; var itemindex = 1; var ServerPort = 1880; function ParsePages() { request('https://url/', function (error, response, body) { console.log('error:', error); console.log('statusCode:', response && response.statusCode); var lines = body.split('\n'); lines.forEach(function (line) { //console.log(line); if (line.indexOf("__listing_ItemsStoreState") > 0) { var start = line.indexOf("__listing_ItemsStoreState") + "__listing_ItemsStoreState = ".length; var stop = line.indexOf("};"); var result = line.substring(start, stop + 1); obj = JSON.parse(result); for (var i = 0; i < obj.itemsGroups[0].items.length; i++) { _HttpContent = _HttpContent + itemindex + ") " + obj.itemsGroups[0].items[i].title.text + "<br>\n"; itemindex++; } pageindex++; console.log("PageIndex: " + pageindex); if (pageindex <= 4) { ParsePages(); } else { res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); res.write(_HttpContent, 'utf8'); res.end(); _HttpContent = ""; } } }); }); } function onRequest(req, res) { ParsePages(); } const _HttpServer = http.createServer(onRequest).listen(ServerPort, (err) => { if (err) { return console.log('something bad happened', err) } console.log(`server is listening on locallhost:${ServerPort}`); }); Hello .. I note that I'm just learning nodejs and I have a problem with the code below, i.e. I want the server to return the response to the client after the parse web page.
doc_880
https://github.com/spabsa/Chapman-Automotive-Skills-Assessment
doc_881
Is there any way to detect whether the client is connected from WCF service in which the client has the url http://localhost:8080 alone without class name and function name where the WCF service is listening to 8080 port at localhost? A: Based upon your request to explain how to send an empty string message to a WCF service I have developed a VS2017 solution and uploaded onto the GITHUB for you. The solution contain 3 projects, 2 on the WCF Service side (Class library and Console Application) and 1 for client. WCF Service Side First we define a ServiceContract that will have single OperationalContract to receive the string message and returns a boolean: [ServiceContract] public interface IClientConnectionService { [OperationContract] bool Connect(string message); } Next, we have a class that implements this ServiceContract public class ClientConnectionService : IClientConnectionService { public bool Connect(string message) { /* * As per your comment on http://stackoverflow.com/questions/43366101/how-to-check-wcf-service-is-connected-with-client?noredirect=1#comment74005120_43366101 * the message should be empty, however you can pass string. * Once you are done with processing you can return true or false depending upon how you want to carry out * this operation. */ return true; } } Next, we have the WCF service host manager (a console based application just to host this WCF service) class Program { static void Main(string[] args) { using (ServiceHost host = new ServiceHost(typeof(ClientConnectionService))) { host.Open(); Console.WriteLine($"{host.Description.Name} is up and listening on the URI given below. Press <enter> to exit."); PrintServiceInfo(host.Description); Console.ReadLine(); } } private static void PrintServiceInfo(ServiceDescription desc) { foreach (ServiceEndpoint nextEndpoint in desc.Endpoints) { Console.WriteLine(nextEndpoint.Address); } } } Its responsibility is to just keep the WCF service listening for incomming requests on a net.tcp port defined in the config file: <system.serviceModel> <services> <service name="StackOverflow.Wcf.Services.ClientConnectionService"> <endpoint address="net.tcp://localhost:9988/ClientConnectionService/" binding="netTcpBinding" contract="StackOverflow.Wcf.Services.Contracts.IClientConnectionService" ></endpoint> </service> </services> </system.serviceModel> Once this is completed we have a running WCF service. Now lets turn our attention to the client that will consume this service. WCF Client Side This is just a console application that has a reference of WCF Service and it creates the proxy class to call the method on the service. public class ClientConnectionServiceProxy : ClientBase<IClientConnectionService> { public bool Connect(string message) { return base.Channel.Connect(message); } } Notice that we have used IClientConnectionService interface / contract from the service side. ClientBase<T> is a WCF Framework class. Here is the program class that calls the WCF servie using above defined proxy class. class Program { static void Main(string[] args) { using (ClientConnectionServiceProxy proxy = new ClientConnectionServiceProxy()) { bool isCallSuccessful = proxy.Connect(string.Empty); } } } and here is the client configuration: <system.serviceModel> <client> <endpoint address="net.tcp://localhost:9988/ClientConnectionService/" binding="netTcpBinding" contract="StackOverflow.Wcf.Services.Contracts.IClientConnectionService" ></endpoint> </client> </system.serviceModel> How to run: Once you have downloaded the source code from GITHUB, open the StackOverflow.Wcf.sln file in VS2017 (thats what I have used to develop this - not sure if you can open it in the VS2015) and hit F5. You can put break points to step through the code and edit it as you wish. Hope this makes it clear - leave any questions in the comments below.
doc_882
[WebMethod()] public static string login(string userName, string password) { if (usernName == "test" && password == "test") { return "validated"; } return "error"; } I'm trying to connect to it with the following Objective C code: NSString *post = [NSString stringWithFormat:@"userName="test"&password="test"]; NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]]; NSString *serverURLString = @"http://myURL.aspx/login"; NSURL *serverURL = [NSURL URLWithString:serverURLString]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:serverURL]; [request setHTTPMethod:@"POST"]; [request addValue:postLength forHTTPHeaderField:@"Content-Length"]; [request setHTTPBody:postData]; NSHTTPURLResponse *urlResponse = nil; NSError *error = nil; NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error]; NSLog(@"response data = %@", responseData); I got lost in ignorant newbie land and thought the last line would print out either "validated" or "error" in my Objective C console but it returns an integer (which I'm sure is obvious to those of you who have done this before =)). Can anyone tell me how I would get to see the webMethod return value in my Objective C log? -EDIT- I've just noticed that I get an HTTP response status code of 200, regardless of whether I use the correct userName/password combination or not, which I'm guessing could also mean the issue lies elsewhere? A: You can create an NSString using the NSData returned in the response. E.g.: NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
doc_883
My first goal is to colorize the first half of the width. My code is acting weird and the problem is... I do not know why! loopVertical = function (data, canvas){ for (var x = 0; x < canvas.width*2; x+=4) { for (var y = 0; y < canvas.height; y++) { data[x+y*canvas.width*4] = 255; } } return data; } The result: red stripes on my image. And that's not what I want. After I will need to divide the image in smaller images if I have a vertical line of transparent pixels, but this is not the topic of the question :) A: I don't really know about html5 canvas and the image data, but according to this tutorial, my guess is that your outer loop is wrong. Apparently, you also need to take care of operator precedence when calculating the index of your data. Maybe something like : loopVertical = function (data, canvas){ // first half of the width for (var x = 0; x < canvas.width / 2; x++) { for (var y = 0; y < canvas.height; y++) { data[(x+y*canvas.width)*4] = 255; } } return data; }
doc_884
Example Array Received: [[user1, , ], [user2, user3, ], [user4, user5, user6]] As you can see, I have a potential of up to three users per row (inner array). However, some of those cells are empty resulting in empty values in the array. I am then feeding each inner array into .addEditors() which throws an error due to the empty user. I know I can run through each array and delete the empties and then push that new array into .addEditors() but it would be ugly, and very inefficient. I don't have enough experience to know how to develop a more elegant way. Could someone help me understand the how and the why to solve this issue in as efficient a manner as possible? Thanks. Note: Though it seems like the .filter(Boolean) solution might work, I can only get it to work for a single array, not for an array within an array. var myFilterArray = myArray.filter(Boolean); arr.forEach(function(x){ return x.filter(Boolean); }); I cannot get it to return the modified array if greater than one deep. A: I know I can run through each array and delete the empties... thats pretty much your only options. There are methods that make your code look cleaner but behind the scenes something is going to have to loop through the array. Here is an example using Array.map() and Array.filter() let data = [["bob", , ], ["jake", "john", ""], ["joe", "henry", "morgan"]]; let newData = data.map(x => { return x.filter(j => j) }) console.log(newData); Using ES5 syntax var data = [["bob", , ], ["jake", "john", ""], ["joe", "henry", "morgan"]]; var newData = data.map(function(x) { return x.filter(function(j) {if (j) return j}) }) console.log(newData); A: If You have following type of array then we can rid of empty data using filter method. var data=[["user1", , ], ["user2", "user3", ], ["user4", "user5", "user6"]]; data.filter(a => a.filter( b => b.length>0)); A: Just out of curiosity I ran these four functions 10 times each on 3 columns and 1000 rows of data. Partially, I was interested in learning more about these array methods because I've just began to use them. So I'm not expert at them for sure. The code: function removeFalsies1() { var start=new Date(); var ss=SpreadsheetApp.getActive(); var sh=ss.getActiveSheet(); var rg=sh.getDataRange(); var vA=rg.getValues(); var vU=[]; var cnt=0; for(var i=1;i<vA.length;i++){ for(var j=0;j<vA[i].length;j++) { cnt++; if(vA[i][j]) { vU.push(vA[i][j]); } } } var end=new Date(); return Utilities.formatString('1,%s',seconds_(start,end)); } function removeFalsies2() { var start=new Date(); var ss=SpreadsheetApp.getActive(); var sh=ss.getActiveSheet(); var rg=sh.getDataRange(); var vA=rg.getValues(); var cnt=0; var vU=[]; vA.forEach(function(r,i,A){ if(i>0) { for(var n=0;n<A[i].length;n++){ var rA=[]; cnt++; if(A[i][n] && i>0){ vU.push(A[i][n]); } } } return rA; }); var end=new Date(); return Utilities.formatString('2,%s',seconds_(start,end)); } function removeFalsies3() { var start=new Date(); var ss=SpreadsheetApp.getActive(); var sh=ss.getActiveSheet(); var rg=sh.getDataRange(); var vA=rg.getValues(); var cnt=0; var vU=[]; vA.forEach(function(r,i,A){if(i>0){r.forEach(function(rix,ix,r){if(rix){vU.push(rix);}cnt++;})}}); var end=new Date(); return Utilities.formatString('3,%s',seconds_(start,end)); } function removeFalsies4() { var start=new Date(); var ss=SpreadsheetApp.getActive(); var sh=ss.getActiveSheet(); var rg=sh.getDataRange(); var vA=rg.getValues(); var cnt=0; var vU=[]; vA.map(function(r,i) {if(i>0){return r.filter(function(rix){if(rix){vU.push(rix);}cnt++;})}}); var end=new Date(); return Utilities.formatString('4,%s',seconds_(start,end)); } The Data: The single digit numbers refer the last digit in the function names.
doc_885
* *select a small recordset from a table of subscribers (150k records); *update those rows to indicate that an email is in the process of being sent; *send email to the subscribers in the recordset; *update the rows again to indicate that the email has been sent. The wrinkle is that the table is simultaneously being accessed by multiple clients to distribute the email workload, which is why there is the intermediate update (to indicate in-process) is used -- to keep the different clients from selecting the same rows, which results in multiple emails being sent to the same subscriber. I've applied some randomizing logic to reduce the likelihood of two clients working with the same data, but it still happens occasionally. So now I am looking at using SELECT ... FOR UPDATE in order to lock the relevant rows (so another client won't select them). My question: is it better to write the UPDATE statement based on the IDs of the SELECT...FOR UPDATE statement, or to create a loop to update each row individually? Here's what I've got so far: DELIMITER $$ CREATE DEFINER=`mydef`@`%` PROCEDURE `sp_SubscribersToSend`(v_limit INTEGER) BEGIN START TRANSACTION; SELECT _ID, email, date_entered, DATE_FORMAT(date_entered, '%b %e, %Y') AS 'date_entered_formatted' FROM _subscribers WHERE send_state = 'Send' AND status = 'Confirmed' LIMIT v_limit FOR UPDATE; [[UPDATE _subscribers SET send_state = 'Sending' WHERE _ID IN (...?)]] [[OR]] [[Loop through the resultset and update each row?]] COMMIT; END Seems like a single UPDATE is going to be more efficient; what is the best way to turn the _ID column of the resultset into a comma-delimited list for the IN() clause? (I've been doing this client-side before this) -- or is there a better way altogether? A: Instead of trying to create a comma-delimited list, just do an UPDATE with the same criteria as the SELECT START TRANSACTION; UPDATE _subscribers SET send_state = 'Sending' WHERE send_state = 'Send' AND status = 'Confirmed' ORDER BY <something> LIMIT v_limit; SELECT _ID, email, date_entered, DATE_FORMAT(date_entered, '%b %e, %Y') AS 'date_entered_formatted' FROM _subscribers WHERE send_state = 'Send' AND status = 'Confirmed' ORDER BY <something> LIMIT v_limit; COMMIT; The ORDER BY clause is necessary to ensure that both queries process the same rows; if you use LIMIT without ORDER BY, they could select a different subset of rows. A: Thanks to Barmar, I took a different tack in the stored procedure: SET @IDs := null; UPDATE _subscribers SET send_state = 'Sending' WHERE send_state = 'Send' AND status = 'Confirmed' AND (SELECT @IDs := CONCAT_WS(',', _ID, @IDs) ) LIMIT v_limit; SELECT CONVERT(@IDs USING utf8); As Barmar suggested, it does an UPDATE but also concatenates the IDs of the rows being updated into a variable. Just SELECT that variable, and it gives you a comma-delimited list that can be passed into a PREPARE statement. (I had to use CONVERT because SELECTing the variable was returning a binary/blob value). So...this does not use SELECT...FOR UPDATE as I was originally intending, but it does ensure that the different clients won't be working with the same rows.
doc_886
string currentPassword; string getUserName; string getPassword; getUserName = Convert.ToString(Session["UserName"]); getPassword = Convert.ToString(Session["Password"]); currentUser = Convert.ToString(txtUserNameLogIn.Text); currentPassword = Convert.ToString(txtPasswordLogin.Text); if ((currentUser == getUserName ) && (currentPassword == getPassword)) { currentUser = Convert.ToString(Session["CurrentUser"]); currentPassword = Convert.ToString(Session["CurrentPassword"]); Response.Redirect("Home.aspx"); } else { lblResult.Text = "Invalid Password"; } I have 3 pages. First one for registration, that saves UserName and Password so a Session and then I have login page that should take the UserName and Password sessions and compare them to the current user input on this page. So far I'm not getting any responses. Edit: The username and password that I put in on previous page gets stored in a Session Variable called "UserName", the person gets re-directed to login page and I simply want to compare what user types in with the Session Variable from previous page and if it's correct, store that information in new Session Variable and re-direct user to home page. A: You can do several things here working under the assumption this is a test project and you know Session is not the correct place to store plaintext credentials. Take a look at SimpleMembership for a cleaner approach. That out of the way I created two extension classes. The first takes care of string security, and the second takes care of Session. You can take this a step further and create constants for the keys or even a SessionUser object. In terms of comparison I just combined both username+password so the logic is short. public static class StringExtensions { public static string Encrypt(this string plainText) { // Replace with your encryption impl return plainText; } public static string Decrypt(this string hiddenText) { // Replace with your decryption impl return hiddenText; } } public static class SessionExtensions { public static void Set<T>(this HttpSessionState sessionState, string key, T value) { sessionState[key] = value; } public static T Get<T>(this HttpSessionState sessionState, string key) where T : class { return (T)sessionState[key]; } } public partial class _Default : Page { protected void Page_Load(object sender, EventArgs e) { Session.Set("UserName", "something"); Session.Set("Password", "something".Encrypt()); var username = Session.Get<string>("UserName"); var password = Session.Get<string>("Password").Decrypt(); var savedUser = $"{username}{password}"; var currentUser = $"somethingsomething"; if (currentUser.Equals(savedUser, StringComparison.InvariantCultureIgnoreCase)) { } else { } } }
doc_887
public void GetConfig() { AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", @"C:\dev\VS\ProofOfConcept\ProofOfConcept\TestApp.config"); var a = ConfigurationManager.AppSettings; } A: This post might help: In the solution posted here there is a method ResetConfigurationMechanism() that you should call after you call CurrentDomain.SetData(...);. private static void ResetConfigMechanism() { typeof(ConfigurationManager) .GetField("s_initState", BindingFlags.NonPublic | BindingFlags.Static) .SetValue(null, 0); typeof(ConfigurationManager) .GetField("s_configSystem", BindingFlags.NonPublic | BindingFlags.Static) .SetValue(null, null); typeof(ConfigurationManager) .Assembly.GetTypes() .Where(x => x.FullName == "System.Configuration.ClientConfigPaths") .First() .GetField("s_current", BindingFlags.NonPublic | BindingFlags.Static) .SetValue(null, null); }
doc_888
My question is very similar to this one, I need to know how to change BlueZ to display the actual device name, i.e. reading it from the build.prop, as opposed to displaying "BlueZ" I found the main.conf in external/bluetooth/bluez/src/main.conf (Might be slightly off) and it contains a line regarding the device name, with the variable set to "BlueZ". I tried changing it to both %d and %h, neither of which made any change. I'm going to try setting it to the device name manually, but I'd prefer that this fix be usable across several devices. Any ideas? # Default adaper name # %h - substituted for hostname # %d - substituted for adapter id Name = "Bluez" I've tried substituting the above two variables, but neither seem to have any effect. A: What about from an outside app? You could just make an Android build and, at the last state, run an app to change the Android device name? You can use IBluetooth.aidl -> setName to change the Bluetooth name. Tutorials can be found here, which further references this. In short, in src you make a package android.bluetooth, Inside it you copy paste IBluetooth.aidl and IBluetoothCallback.aidl (you can find them in the previous link). In your code, import the package: import android.bluetooth.IBluetooth; Then implement this method to get the Bluetooth object: @SuppressWarnings("rawtypes") private IBluetooth getIBluetooth() { IBluetooth ibt = null; try { Class c2 = Class.forName("android.os.ServiceManager"); Method m2 = c2.getDeclaredMethod("getService", String.class); IBinder b = (IBinder) m2.invoke(null, "bluetooth"); Class c3 = Class.forName("android.bluetooth.IBluetooth"); Class[] s2 = c3.getDeclaredClasses(); Class c = s2[0]; Method m = c.getDeclaredMethod("asInterface", IBinder.class); m.setAccessible(true); ibt = (IBluetooth) m.invoke(null, b); } catch (Exception e) { Log.e("flowlab", "Erroraco!!! " + e.getMessage()); } return ibt; } Then instance this object: IBluetooth ib =getIBluetooth(); and probably use ib.setName("something");
doc_889
For this, I wonder if it is possible to compile the Linux kernel along with the Busybox incorporated in the build process so that it is included in initramfs and loaded in RAM in the boot process. I have been looking for info about this but I don't think I found the answer. A: Another option is the Yocto project, which uses bitbake and the OpenEmbedded metadata. It is well-documented and very flexible, but has a fairly steep learning curve. A: You can use Buildroot, that's a buildsystem that downloads the linux kernel, manages rootfs, integrates BusyBox, and much much more. From my opinion it's the easiest way to get an embedded Linux/BusyBox system. Here's their homepage: http://buildroot.uclibc.org/
doc_890
Thanks in advance A: dnsjava does not use InetAdress.getByName() or InetAddress.getAllByName(). Just use it like this: System.setProperty("dns.server", "<resolver you want to use>"); InetAddress addr = Address.getByName("<name>");
doc_891
Does Local Memory refer to the memory allocated to a certain program? And does the Global memory refer the the Main memory? I am reading about Uniform Memory Access time and Non Uniform Memory Access time. They say a multiprocessor computer has a Uniform Memory Access time if the time it takes to access memory data locally is the same as the amount of time it takes to access data globally. I thought by "locally" they are referring to a cache, but in the preceding statements they clarify that a local memory is not a cache.
doc_892
Here have a look on a problem that I am facing https://ibb.co/VvtRx1H. I just want to display the paragraph that is enclosed in a red border on entire mobile screen My CSS code: *{ margin:0; padding:0; box-sizing: border-box; } h1{ text-transform: uppercase; margin:50px 0; text-align: center; } .parent{ width:100%; height:50vh; display: flex; justify-content: space-around; align-self: center; } .daughter{ width:50%; text-align: center; padding:0; } .daughter img{ width:450px; } .son{ width:50%; padding:0 5%; box-sizing: border-box; line-height: 1.7; text-align: justify; } @media (max-width:768px){ h1{ color:red; } .parent{ display: block; } .daughter{ width:100%; } .son{ width:100%; } } @media (max-width:468px){ .daughter img{ padding:10%; box-sizing: border-box; } } @media (max-width:410px){ .daughter img{ padding:10%; box-sizing: border-box; } .son{ border:1px solid red; } } my HTML code: <body> <h1>My WEBSITE</h1> <br> <div class="parent"> <br> <div class="son"> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Tempore minima doloremque aliquid ad voluptates iste dicta officiis repellat nesciunt a.</p> <br> </div> <div class="daughter"> <img src="images/11.jpg" alt="image"> </div> </div> A: Edits needed to fix the problem: Line 55, Css code. @media (max-width:410px){ .daughter img{ padding:10%; box-sizing: border-box; } .son{ border:1px solid red; height: 85vh; width: 100%; } .son p{ height: 95%; text-align: center; } } A: Apply meta tag in your head section <meta content="width=device-width, initial-scale=1" name="viewport" /> Replace Style *{ margin:0; padding:0; box-sizing: border-box; } h1{ text-transform: uppercase; margin:50px 0; text-align: center; } .parent{ width:100%; height:50vh; display: flex; justify-content: space-around; align-self: center; } .daughter{ width:50%; text-align: center; padding:0; } .daughter img{ width:450px; } .son{ width:50%; padding:0 5%; box-sizing: border-box; line-height: 1.7; text-align: justify; } @media screen and (max-width: 768px) { h1{ color:red; } .parent{ display: block; } .daughter{ width:100% !important; } .son{ width:100%; } .parent{display: inline;} } @media (max-width:468px){ .daughter img{ padding:10%; box-sizing: border-box; } } @media (max-width:410px){ .daughter img{ padding:10%; box-sizing: border-box; } .son{ border:1px solid red; } } and html <h1>My WEBSITE</h1> <br> <div class="parent"> <br> <div class="son"> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Tempore minima doloremque aliquid ad voluptates iste dicta officiis repellat nesciunt a.</p> <br> </div> <div class="daughter"> <img src="images/11.jpg" alt="image"> </div> </div>
doc_893
How to use JPA Criteria API in JOIN CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder(); CriteriaQuery<Company> criteria = criteriaBuilder.createQuery( Company.class ); Root<Company> companyRoot = criteria.from( Company.class ); Join<Company,Product> products = companyRoot.join("dentist"); Join<Company, City> cityJoin = companyRoot.join("address.city");//Company->Address->City-city criteria.where(criteriaBuilder.equal(products.get("category"), "dentist"),      criteriaBuilder.equal(cityJoin.get("city"),"Leeds")); A company has an address, inside the address there is City-pojo and Country-Pojo. How can I use it in JOIN? I tried to reference it with address.city but I got the error message: The attribute [address.city] from the managed type [EntityTypeImpl@1692700229:Company [ javaType: class com.test.domain.Company descriptor: RelationalDescriptor(com.test.domain.Company --> [DatabaseTable(COMPANY)]), mappings: 16]] is not present. A: If you use canonical Metamodel, you'll avoid this kind of errors. In your code you have misused the "dentist" keyword, that's probably the cause of your error, because "dentist" is not a field in Company entity. However, looking at how you defined your class in the other question, the way to define that join using Metamodel is this: SetJoin<Company,Product> products = companyRoot.join(Company_.products); As you can see, Metamodel avoids the use of strings, and so avoids a lot of runtime errors. If anyway you don't use Metamodel, try this: SetJoin<Company,Product> products = companyRoot.join("products"); If you now want to add a predicate, i.e. something after the where, you'll write something like: Predicate predicate = criteriaBuilder.equal(products.get(Product_.category), "dentist"); criteria.where(predicate); If you want to add a join for the City entity: Join<Company, City> city = companyRoot.join(Company_.city); predicate = criteriaBuilder.and(predicate, criteriaBuilder.equal(city.get(City_.cityName), "Leeds"); criteria.where(predicate); (supposing that the field cityName is the correct field name for your city). A: Agree with @perissf. I can't comment but the symbol "Company_" is the metadata class file which contains all the attribute name of the model class. I strongly suggest to use metadata classes, you can autogenerate metadata classes using the maven processor plugin using org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor as processor in your configuration. This example pom plugin xml should work it out : <plugin> <groupId>org.bsc.maven</groupId> <artifactId>maven-processor-plugin</artifactId> <executions> <execution> <goals> <goal>process</goal> </goals> <phase>generate-sources</phase> <configuration> <processors> <processor>org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor</processor> </processors> </configuration> </execution> </executions> <dependencies> <dependency> <groupId>org.hibernate.orm</groupId> <artifactId>hibernate-jpamodelgen</artifactId> <version>${version.hibernate-jpamodelgen}</version> </dependency> </dependencies> </plugin>
doc_894
For example: Instead of SELECT "ApplicationId" FROM "dbo"."Applications"; I want SELECT ApplicationId FROM dbo.Applications; Will Entity Framework be able to correctly map properties and entities to the database fields and tables correctly? EDIT: Rather than try to eliminate the quotation marks, I should have indicated that my goal is to interface with an Oracle DB. Oracle will require using quotation marks around identifiers that contain lowercase letters. So, I should probably change my request to indicate that I need all uppercase identifiers. I came up with part of a solution in the OnModelCreating method of the DbContext, but it won't handle Foreign Key identifiers: protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Properties() .Configure(c => c.HasColumnName(c.ClrPropertyInfo.Name.ToUpperInvariant())); modelBuilder.Types() .Configure(c => c.ToTable(c.ClrType.Name.ToUpperInvariant())); } A: You can put the foreign key properties in your class, and then map their database column. Like this How to configure DbContext to work with Oracle ODP.Net and EF CodeFirst? Or, if you don't want to put the foreign key property in the classes, you should use the fluent API to map the foreign key using uppercase letters. Like this example: modelBuilder.Entity<Course>() .HasRequired(c => c.Department) .WithMany(t => t.Courses) .Map(m => m.MapKey("CHANGEDDEPARTMENTID"));
doc_895
Collecting avro-python3==1.9.2.1 Downloading https://artifactory/avro-python3-1.9.2.1.tar.gz (37 kB) WARNING: Requested avro-python3==1.9.2.1 from https://artifactory/avro-python3-1.9.2.1.tar.gz#sha256=ca1e77a3da5ac98e8833588f71fb2e170b38e34787ee0e04920de0e9470b7d32 (from -r requirements.txt (line 4)), but installing version file-.avro-VERSION.txt ERROR: Requested avro-python3==1.9.2.1 from https://artifactory/avro-python3-1.9.2.1.tar.gz#sha256=ca1e77a3da5ac98e8833588f71fb2e170b38e34787ee0e04920de0e9470b7d32 (from -r requirements.txt (line 4)) has different version in metadata: 'file-.avro-VERSION.txt' My requirements.txt looks like avro-python3==1.9.2.1 Is there a way to avoid this error? What needs to be fixed in order to resolve it? Is there a way I can specify in requirement.txt ? to not use artifactory for this package? A: I downloaded avro-python3-1.9.2.1.tar.gz from PyPI. And its setup.cfg file looks like: [metadata] name = avro-python3 version = file: avro/VERSION.txt description = Avro is a serialization and RPC framework. ... Note the version line and the file: notation. This notation was added in setuptools 39.2.0: * *doc *changelog *code change So, make sure that your setuptools version is at least 39.2.0 and it would probably work better (maybe upgrading pip could help as well).
doc_896
from bulbs.neo4jserver import Graph, Config, NEO4J_URI config = Config(NEO4J_URI) g = Graph(config) def get_or_create_node(text, crsqid): v = g.vertices.index.lookup(crsqid=crsqid) if v==None: v = g.vertices.create(crsqid=crsqid) print text + " - node created" v.text = text v.save() return v I then loop over each line in the text file, count = 1 with open('titles-sorted.txt') as f: for line in f: get_or_create_node(line, count) count += 1 This is terribly slow. This gives me 5000 nodes in 10 minutes. Can this be improved? Thanks A: I don't see any transaction code in there, establishing one, or signaling transaction success. You should look into that -- if you're doing one transaction for every single node creation, that's going to be slow. You should probably create one transaction, insert thousands of nodes, then commit the whole batch. I'm not familiar with bulbs, so I can't tell you how to do that with this python framework, but here is a place to start: this page suggests you can use a coding style like this, with some python/neo bindings: with db.transaction: foo() also, if you're trying to load mass amounts of data and you need performance, you should check this page for information on bulk importing. It's unlikely that doing it in your own script is going to be the most performant. You might instead consider using your script to generate cypher queries, which get piped to the neo4j-shell. Finally a thing to consider is indexes. Looks like you're indexing on crsqid - if you get rid of that index, creates may go faster. I don't know how your IDs are distributed, but it might be better to break records up into batches to test if they exist, rather than using the get_or_create() pattern. A: Batch loading 500k nodes individually via REST is not ideal. Use Michael's batch loader or the Gremlin shell -- see Marko's movie recommendation blog post for an example of how to do this from the Gremlin shell.
doc_897
Output: id title content tags However my code outputs the columns in this order: Output : content id tags title How do I get it back in the order that all the csv files have it as here is my code below: import glob import os import pandas as pd pd.set_option("display.max_rows", 999) pd.set_option('max_colwidth',100) import numpy as np from IPython.display import display %matplotlib inline file_path = 'data/' all_files = glob.glob(os.path.join(file_path, "*.csv")) merging_csv_files = (pd.read_csv(f) for f in all_files) stack_exchange_data = pd.concat(merging_csv_files, ignore_index=True) print ("Data loaded succesfully!") print ("Stack Exchane Data has {} rows with {} columns each.".format(*stack_exchange_data.shape)) A: The general way for selecting a DataFrame with columns in a specific order is to simply create a list of the order you desire and then pass that list to the bracket operator of the DataFrame like this: my_col_order = ['id', 'title', 'content', 'tags'] df[my_col_order] Also you might want to check that all the DataFrames indeed have the same column order. I don't believe Pandas will sort the column names in concat unless there is at least one DataFrame that has a different column ordering. You might want to print out all the column names from all the DataFrames you are concatenating.
doc_898
<outer> <inner /> </outer> I need to use Mavens Jaxb plugin, any will do, as long as it will generate xml from xsd. The schema states that outer element must occur once, and inner element has minoccurs 0. The inner element has also attribute, which is also minoccurs 0. Element having more than just a value makes it as a class. I'm receiving the example xml, and after doing unmarshalling, it saves the inner element as "empty instance" and not null. When I'm doing marshalling again, I get validation errors because the inner element is not ignored though it's "null" in sense. What I need is a way to make these elements with just /> ending and nothing else to be read as null, so they wont be marshalled or validated, just ignored, dropped, unless they are specified to occur. So the XML would be marshalled to be simply: <outer /> I read that there are some ways to achieve this with modifying the xml classes ( Create Null Object Unmarshalling Empty Element with JAXB and JAXB empty element unmarshalling), but since my xml classes are generated with maven jaxb plugin, the modifications are ofcourse overwritten every time the classes are generated. Is there any way to achieve this with jaxb maven plugins or is there some other way to apply the changes on top of generated codes so that they are easily managed? Other suggestions are welcomed as well. The received xml cannot be modified and the result must be the way I described. IF there is something that can be added to schema to get this behavior that is acceptable as well.
doc_899
my CSS: .card-columns { @include media-breakpoint-only(xl) { column-count: 5; } @include media-breakpoint-only(lg) { column-count: 4; } @include media-breakpoint-only(md) { column-count: 3; } @include media-breakpoint-only(sm) { column-count: 2; } } <div class="card-columns"> <% @products.each do |product| %> <div class="card"> <%= image_pack_tag product.image, class: "card-img-top" %> <div class="card-body"> <h5 class="card-title"><%= product.name %></h5> <p class="card-text"><%= sanitize(product.description) %></p> <p class="card-text"><small class="price"><%= sprintf("$%0.02f", product.price) %></small></p> <%= button_to 'Add to Cart', line_items_path(product_id: product), class: "btn btn-primary btn-sm" %> </div> </div> <% end %> </div> Image here: