id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23538400
|
A: My gut tells me this may be a permissions problem. Have you ensured the security context under which your IIS app domain is running as write permissions to the folder in which you are storing the files? In 'debug' mode, your user account may already have permissions, but not so with the IIS security context. You may be getting access denied errors that you are somehow swallowing in your code. Just a hunch. Post more details for better diagnosis.
| |
doc_23538401
|
+---+---+-------+
| A | B | |
+---+---+ C |
| D | E | |
+---+---+-------+
But my current layout shows something like this: (- = empty space)
+---+---+-------+
| A | B | |
+---+---+ C |
| - | - | |
+---+---+-------+
| D | E |
+---+---+
Link: http://www.bootply.com/3m75xi0G2M
Can this be done in "pure" BS3? Supposedly, this can be done w/ Masonry, but since the site is already built w/ BS3, I'd rather stay away from additional frameworks.
(In this particular case, the larger column is on the right side. But some will be in the middle or even left - the real grid is done using a modified 10-grid bootstrap.)
A: Make a wrapper for ABDE, make that wrapper col-6 and make C col-6.
This will float your 4 divs next to C.
it will look something like this:
<div class="wrapper col-6">
<div class="A"></div>
<div class="B"></div>
<div class="D"></div>
<div class="E"></div>
</div>
<div class="C col-6"></div>
Add your responsive columns as needed
A: Simply create two separate columns. A floating left with the four boxes and another to the right with a single box. See the solution in this link http://codepen.io/anon/pen/NqOxaW
<div class="container">
<div class="left">
<div class="col-md-4 noBox" id="div1">A</div>
<div class="col-md-4 noBox" id="div2">B</div>
<div class="col-md-4 noBox" id="div4">D</div>
<div class="col-md-4 noBox" id="div5">E</div>
</div>
<div class="right">
<div class="col-md-4 noBox" id="div3">C</div>
</div>
</div>
<style>
#div1 {background-color: red;}
#div2 {background-color: green;}
#div3 {background-color: blue;}
#div4 {background-color: yellow;}
#div5 {background-color: pink;}
#div6 {background-color: cyan;}
.container {
width: 400px;
display: table;
}
.container .left {
width: 200px;
float: left;
}
.container .left > div {
width: 100px;
height: 100px;
float: left;
}
.container .right {
width: 100px;
float: right;
}
.container .right > div {
width: 200px;
height: 200px;
float: right;
}
body {
background-color: black;
}
.noBox {
line-height: 100px;
color: white;
font-weight: bold;
text-align: center;
}
#div3 {line-height: 200px;}
</style>
A: I tackled the same problem (different layout) using the core Bootstrap 3 CSS so it is still responsive. The example above isn't responsive.
See Codeply here where I placed this code:
<div class="container-fluid">
<div class="row">
<div class="col-md-12" id="BigBox">
<div class="col-md-6" id=LeftBigBox><p>Left box copy</p></div>
<div class="col-md-6">
<div class="row">
<div class="col-md-6" id="TopBox"><p>Top right box copy</p></div>
</div>
<div class="row">
<div class="col-md-6" id="BottomBox"><p>Bottom right box copy</p></div>
</div>
</div>
</div>
</div>
</div>
| |
doc_23538402
|
@Mock
MyBaseClass myBaseClass; // It is failing here
Now I am not sure why my class is fail to mock but intrestingly i found something in stack trace. That is "Caught an exception while trying to initialize Bootstrap Services Initializer". Can anyone explain what is this and How to fix the problem in my class so I can load this.
Here is my stack Trace.
> log4j:WARN No appenders could be found for logger (com.java.wss.test.frmwrk.geek.bootstrap.BootstrapServicesInitializer).
log4j:WARN Please initialize the log4j system properly.
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 3.626 sec <<< FAILURE!
testmyMethod(com.java.test.testmyMethod) Time elapsed: 2.101 sec <<< ERROR!
java.lang.ExceptionInInitializerError
at sun.reflect.GeneratedSerializationConstructorAccessor6.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.objenesis.instantiator.sun.SunReflectionFactoryInstantiator.newInstance(SunReflectionFactoryInstantiator.java:48)
at org.objenesis.ObjenesisBase.newInstance(ObjenesisBase.java:73)
at org.mockito.internal.creation.instance.ObjenesisInstantiator.newInstance(ObjenesisInstantiator.java:18)
at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMock(SubclassByteBuddyMockMaker.java:47)
at org.powermock.api.mockito.mockmaker.PowerMockMaker.createMock(PowerMockMaker.java:50)
at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.createMethodInvocationControl(DefaultMockCreator.java:116)
at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.createMock(DefaultMockCreator.java:69)
at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.mock(DefaultMockCreator.java:46)
at org.powermock.api.mockito.PowerMockito.mock(PowerMockito.java:192)
at org.powermock.api.extension.listener.AnnotationEnabler.standardInject(AnnotationEnabler.java:107)
at org.powermock.api.extension.listener.AnnotationEnabler.beforeTestMethod(AnnotationEnabler.java:55)
at org.powermock.tests.utils.impl.PowerMockTestNotifierImpl.notifyBeforeTestMethod(PowerMockTestNotifierImpl.java:82)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:308)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:131)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.access$100(PowerMockJUnit47RunnerDelegateImpl.java:59)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner$TestExecutorStatement.evaluate(PowerMockJUnit47RunnerDelegateImpl.java:147)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.evaluateStatement(PowerMockJUnit47RunnerDelegateImpl.java:107)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:298)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:87)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:50)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:218)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:160)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:134)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:136)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:121)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:57)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
Caused by: com.java.frmwrk.geek.exception.ParameterizedRuntimeException: Caught an exception while trying to initialize Bootstrap Services Initializer as :
at com.java.frmwrk.geek.bootstrap.BootstrapServicesInitializer.init(BootstrapServicesInitializer.java:280)
at com.java.frmwrk.flex.java.service.myActionScript.<clinit>(myActionScript.java:99)
... 44 more
Caused by: java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Properties.java:434)
at java.util.Properties.load0(Properties.java:353)
at java.util.Properties.load(Properties.java:341)
at com.java.frmwrk.geek.bootstrap.BootstrapProperties.init(BootstrapProperties.java:101)
at com.java.frmwrk.geek.bootstrap.BootstrapServicesInitializer.init(BootstrapServicesInitializer.java:229)
... 45 more
| |
doc_23538403
|
CustomerID Date
001 02/15/2022
001 03/01/2022
002 01/19/2022
002 02/11/2022
002 03/30/2022
...
I would want to end up with
CustomerID Date Flag
001 02/15/2022 N
001 03/01/2022 N
002 01/19/2022 N
002 02/11/2022 N
002 03/30/2022 Y
...
The only way I can think of doing this is by referencing the previous row. Here's the pseudo-code to illustrate what I mean.
IF (CUSTOMERID = PRIOR.CUSTOMERID) AND (DATE - PRIOR.DATE >= 30) THEN FLAG = 'Yes'
However, after looking around some, I'm unsure how to accomplish this in SAS, either in a data step or proc sql. I assume there's some way of saving the value of a previous row, but I'm not familiar with that.
A: That is what the LAG() function is for. The LAG() function returns the value saved from the last time you called it. So if you call it for every observation then the result is the value from the previous observation. Just make sure not to skip running the LAG() function on some observation or else the returned value will NOT be the previous observation's value.
data want;
set have;
by customerid date;
if not first.customerid and (date-30 )> lag(date) then flag='YES';
else flag='NO';
run;
Results
Customer
Obs ID Date flag
1 001 2022-02-15 NO
2 001 2022-03-01 NO
3 002 2022-01-19 NO
4 002 2022-02-11 NO
5 002 2022-03-30 YES
| |
doc_23538404
|
I am trying to understand variable-byte encoding. I have read the Wikipedia article (http://en.wikipedia.org/wiki/Variable-width_encoding) as well as a book chapter from an Information Retrieval textbook. I think I understand how to encode a decimal integer. For example, if I wanted to provide variable-byte encoding for the integer 60, I would have the following result:
1 0 1 1 1 1 0 0
(please let me know if the above is incorrect). If I understand the scheme, then I'm not completely sure how the information is compressed. Is it because usually we would use 32 bits to represent an integer, so that representing 60 would result in 1 1 1 1 0 0 preceded by 26 zeros, thus wasting that space as opposed to representing it with just 8 bits instead?
Thank you in advance for the clarifications.
A: The way you do it is by reserving one of the bits to mean "I'm not done with the value." Usually, that's the most significant bit.
When you read a byte, you process the lower 7 bits. If the most significant bit is 1, then you know there's one more byte to read, and you repeat the process, adding the next 7 bits to the current 7 bits.
The MIDI format uses that exact encoding to represent lengths of MIDI events, in the following manner:
*
*ExpectedValue = 0
*byte=ReadFromFile
*ExpectedValue = ExpectedValue + (byte AND 0x7f)
*if byte > 127 then
*
*ExpectedValue = ExpectedValue SHL 7
*Goto 2
*Done
For example, the value 0x80 would be represented using the bytes 0x81 0x00. You can try running the algorithm on those two bytes, and you see you'll get the right value.
UTF-8 works similarly, but it uses a slightly more complex scheme to tell you how many bytes you should be expecting. This allows for some error correction, since you can easily tell if the bytes you're getting match the length claimed. Wikipedia describes their structure quite well.
A: You hit the nail on the head.
There are many encoding schemes, such as gamma and delta, which are special cases of elias coding. These are bit-level codes, as opposed to the byte-level code you used, and are useful when you have a strong skew towards small numbers (which can often be achieved by encoding deltas instead of absolute values).
Bit-level encoding schemes are much more difficult to implement than byte-level schemes and the additional CPU burden may outweigh the time saved by having less data to read, though most modern CPUs have "highest-bit" and "lowest-bit" instructions that dramatically improve the performance of bit-level codecs. As CPU speeds continue to outpace RAM speeds, bit-level schemes will become more attractive, though the simplicity of byte-level codecs is a big factor too.
A: Yes, you are right, you save space by encoding using one byte instead of 4.
Generally, you will save memory if the values you are encoding are much smaller than the maximum value that would have fit in your original fixed-width encoding.
| |
doc_23538405
|
SELECT * FROM Catalogue WHERE Catalogue.ID IN (
SELECT ID_catalogue FROM Categories WHERE Categories.Product_type='xxx'
)
Error Code : 1064
You have an error in
your SQL syntax near 'SELECT
ID_catalogue FROM Categories WHERE
Categories.Product_type='xxx' ) ' at
line 2
Ok, that's because I am using a very old MySQL version.
What I am trying to get is
SELECT * FROM Catalogue WHERE Product_type='xxx' OR Catalogue.ID IN (
SELECT ID_catalogue FROM Categories WHERE Categories.Product_type='xxx'
)
Is there any equivalent for that?
Thank you for all your comments.
A: If you're using mysql version <= 4.0 - then it is the reason, since subqueries were added in 4.1
SELECT c.*,
g.ID_catalogue
FROM Catalogue c
LEFT JOIN Categories g ON g.ID_catalogue = c.ID
AND g.Product_type='xxx'
HAVING ID_catalogue IS NOT NULL
OR Product_type = 'xxx'
You should add composite index ID_catalogue + Product_type for table Categories AND index Product_type for table Catalogue to have this query performed fast
A: There is nothing wrong with your query. It is the version of MySQL that is more than likely your problem.
| |
doc_23538406
|
filtered = FILTER data by ($0 is not null) AND ($1 is not null) AND ($2 is not null)
Is there any cleaner way to do this, without having to write out 3 boolean expressions?
A: If all of the fields are of numeric types, you could simply do something like
filtered = FILTER data BY $0*$1*$2 is not null;
In Pig, if any terms in an arithmetic expression are null, the result is null.
You could also write a UDF to take an arbitrary number of arguments and return null (or 0, or false, whatever you find most convenient) if any of the arguments are null.
filtered = FILTER data BY NUMBER_OF_NULLS($0, $1, $2) == 0;
where NUMBER_OF_NULLS is defined elsewhere, e.g.
public class NUMBER_OF_NULLS extends EvalFunc {
public Integer exec(Tuple input) {
if (input == null) { return 0; }
int c = 0;
for (int i = 0; i < input.size(); i++) {
if (input.get(i) == null) c++;
}
return c;
}
}
Note: I have not tested the above UDF, and I don't claim it adheres to any best practices for writing clear, robust UDFs. You should add exception-handling code, for example.
A: I was thinking there is a better way of doing this without using the UDF, i.e, using SPLIT in Pig.
emp = load '/Batch1/pig/emp' using PigStorage(',') as (id:chararray, name:chararray, salary:int, dept:chararray);
SPLIT emp INTO emptyDept IF depart == '', nonemptyDept IF depart != '';
DUMP nonemptyDept;
The resulting relation nonemptyDept would display all the non-empty Department values of the emp relation.
| |
doc_23538407
|
import scrapy
import string
import itertools
class AmazonitemsSpider(scrapy.Spider):
name = 'amazonitems'
allowed_domains = ['www.amazon.ca']
def __init__(self):
self.total_count = []
self.f = open('csvfile.csv','w')
def start_requests(self):
alphabets = [ 'a', 'b' ]
amazon_urls = [ 'https://www.amazon.ca/gp/search/other/?rh=i%2Cn%3A6647368011&pickerToList=lbr_brands_browse-bin&indexField=', 'https://www.amazon.ca/gp/search/other/?rh=i%2Cn%3A2224133011&pickerToList=lbr_brands_browse-bin&indexField=' ]
for amazon_url in amazon_urls:
keywords = itertools.product(alphabets, repeat=1)
for keyword in keywords:
keyword = ''.join(keyword)
yield scrapy.Request(url=amazon_url + keyword, callback=self.parse)
def parse(self, response):
count_list = []
items = response.xpath('//*[@class="a-list-item"]')
for item in items:
item_count = item.xpath('.//*[@class="narrowValue"]/text()').extract_first()
item_count = item_count.replace('(','').replace(')','').strip()
count_list.append(int(item_count))
count_list = sum(count_list)
self.total_count.append(count_list)
def closed(self, reason):
self.total_count = sum(self.total_count)
self.f.write(str(total_count) + '\n')
self.f.close()
| |
doc_23538408
|
EXPRESSION : EXPRESSION BINARYOP EXPRESSION | UNARYOP EXPRESSION | NUMBER;
I need to add parenthesis to it but I'm not sure how to make a left parenthesis depend on a matching right parenthesis yet still optional. Can someone show me how? (Or am I trying to do entirely too much in lexing, and should I leave some or all of this to the parsing?)
A: You could add a recursive rule:
EXPRESSION : EXPRESSION BINARYOP EXPRESSION
| UNARYOP EXPRESSION
| NUMBER
| OPENPARENS EXPRESSION CLOSEPARENS
;
A: Yes, you're trying to do too much in the lexer. Here's how to get around the left-recursive rules:
http://www.antlr.org/wiki/display/ANTLR3/Expression+evaluator (see how the parser rule expr trickles down to the rule atom and then get called recursively from atom again)
HTH
| |
doc_23538409
|
useEffect(()=>{
let updated = data.filter(function(e){
if ((e.country === aaa|| e.country === undefined) && (e.age === bbb|| e.age === undefined)){
return true
}
})
setRows(updated)
},[aaa, bbb])
it works fine when "Select" for both the filters are selected if one if them is undefined then it does not show any data
A: I prefer making multiple functions when filtering criteria differs. It's more readable for other developers and easier to modify and maintain.
I don't know about the actual end result since I don't know your exact use case. But this structure of code should give you a hint on how to approach that:
const byCountry = (country) => (item) => {
return item.country === country || item.country === undefined;
};
const byAge = (age) => (item) => {
return item.age === age || item.age === undefined;
};
const getUpdated = (data, country, age) => {
return data
.filter(byCountry(country))
.filter(byAge(age));
};
const data = [{
country: 'Finland',
age: '42',
}, {
country: 'Sweden',
age: '39',
}, {
country: 'Sweden',
}];
console.log(getUpdated(data, 'Finland', '42'));
console.log(getUpdated(data, 'Sweden', '39'));
| |
doc_23538410
|
Here's what I get when I run the jar:
D:\Dokumente\workspace>java -jar Dame.jar
Exception in thread "main" java.lang.NoClassDefFoundError: [[Lcheckers/Board$EmptySquare;
at checkers.Board.<init>(Board.java:63)
at checkers.Board.<init>(Board.java:49)
at checkers.GameUI.main(GameUI.java:105)
Caused by: java.lang.ClassNotFoundException: checkers.Board$EmptySquare
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 3 more
Maybe it helps to know that EmptySquare is an inner class of Board?
What could be the problem? I tried both "extract required libraries" and "package required libraries" in the export wizard.
I also tried using jar from the command line, but it doesn't work as well. Here's what I did:
D:\Dokumente\workspace\Dame\bin\checkers>jar cvfe Dame.jar checkers.GameUI *.class
D:\Dokumente\workspace\Dame\bin\checkers>java -jar Dame.jar
Fehler: Hauptklasse checkers.GameUI.class konnte nicht gefunden oder geladen werden
(error: main class checkers.GameUI.class could not be found or loaded)
If I leave out the package name for the main class (GameUI), it also doesn't work:
D:\Dokumente\workspace\Dame\bin\checkers>jar cvfe Dame.jar GameUI *.class
D:\Dokumente\workspace\Dame\bin\checkers>java -jar Dame.jar
Exception in thread "main" java.lang.NoClassDefFoundError: GameUI (wrong name: checkers/GameUI)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
No clue.
The jar file content is:
D:\Dokumente\workspace\Dame\bin\checkers>jar tvf Dame.jar
0 Thu Jan 09 01:05:26 CET 2014 META-INF/
88 Thu Jan 09 01:05:26 CET 2014 META-INF/MANIFEST.MF
994 Thu Jan 09 00:14:30 CET 2014 Board$1.class
1840 Thu Jan 09 00:14:30 CET 2014 Board$EmptySquare.class
447 Thu Jan 09 00:14:30 CET 2014 Board$GamePiece.class
4051 Thu Jan 09 00:14:30 CET 2014 Board$Piece.class
4399 Thu Jan 09 00:14:30 CET 2014 Board$Queen.class
8381 Thu Jan 09 00:14:30 CET 2014 Board.class
2946 Thu Jan 09 00:14:30 CET 2014 Checkers.class
2708 Thu Jan 09 00:14:30 CET 2014 CheckersAB.class
4202 Thu Jan 09 00:14:30 CET 2014 CheckersABT.class
2464 Thu Jan 09 00:14:30 CET 2014 CheckersMinMax.class
1324 Thu Jan 09 00:14:30 CET 2014 CheckersPieces.class
951 Thu Jan 09 00:14:30 CET 2014 GameState.class
804 Thu Jan 09 00:14:30 CET 2014 GameUI$1.class
663 Thu Jan 09 00:14:30 CET 2014 GameUI$2.class
2535 Thu Jan 09 00:14:30 CET 2014 GameUI.class
739 Thu Jan 09 00:14:30 CET 2014 GUIBoard$1.class
6069 Thu Jan 09 00:14:30 CET 2014 GUIBoard.class
3776 Thu Jan 09 00:14:30 CET 2014 Move.class
607 Thu Jan 09 00:14:30 CET 2014 MoveComparator.class
610 Thu Jan 09 00:14:30 CET 2014 NodeVal.class
1078 Thu Jan 09 00:14:30 CET 2014 PlayCheckersAB.class
356 Thu Jan 09 00:14:30 CET 2014 PlayCheckersABT.class
357 Thu Jan 09 00:14:30 CET 2014 PlayCheckersMM.class
2466 Thu Jan 09 00:14:30 CET 2014 PlayTournament.class
1183 Thu Jan 09 00:14:30 CET 2014 Square.class
241 Thu Jan 09 00:14:30 CET 2014 ZeroSumGame.class
A: Ok, I found the answer. In post eclipse doesn't compile the project
someone suggests to switch to a new workspace. I did that because besides the mysteriously non-working-jar file, Eclipse also didn't build my java files anymore. I switched to a new workspace, re-imported the project, and voila, the exported jar file is runnable!
Thanks for your efforts, especially to divanov!
| |
doc_23538411
|
An error was encountered processing the command (domain=NSPOSIXErrorDomain, code=2):
Failed to install the requested application
An application bundle was not found at the provided path.
Provide a valid path to the desired application bundle.
Print: Entry, ":CFBundleIdentifier", Does Not Exist
Command failed: /usr/libexec/PlistBuddy -c Print:CFBundleIdentifier build/Build/Products/Debug-iphonesimulator/albums.app/Info.plis
Print: Entry, ":CFBundleIdentifier", Does Not Exist
How do you get the project to run?
A: My terminal pops out the same message due to deleting some simulators I don't use in Xcode.
If you run react-native run-ios with no specific parameters, react-native will run the default simulator which is iPhone 6 with iOS 10.3.1 in my case and I deleted this simulator by chance.
Here comes my error messages:
xcodebuild: error: Unable to find a destination matching the provided destination specifier:
{ id:F3A7BF54-B827-4517-A30D-8B3241C8EBF8 }
Available destinations for the "albums" scheme:
{ platform:iOS Simulator, id:CD64F26B-045A-4E27-B05A-5255924095FB, OS:10.3.1, name:iPad Pro (9.7 inch) }
{ platform:iOS Simulator, id:8FC41950-9E60-4264-B8B6-20E62FAB3BD0, OS:10.3.1, name:iPad Pro (10.5-inch) }
{ platform:iOS Simulator, id:991C8B5F-49E2-4BB7-BBB6-2F5D1776F8D2, OS:10.3.1, name:iPad Pro (12.9 inch) }
{ platform:iOS Simulator, id:B9A80D04-E43F-43E3-9CA5-21137F7C673D, OS:10.3.1, name:iPhone 7 }
{ platform:iOS Simulator, id:58F6514E-185B-4B12-9336-B8A1D4E901F8, OS:10.3.1, name:iPhone 7 Plus }
. . .
Installing build/Build/Products/Debug-iphonesimulator/myapp.app
An error was encountered processing the command (domain=NSPOSIXErrorDomain, code=2):
Failed to install the requested application
An application bundle was not found at the provided path.
Provide a valid path to the desired application bundle.
Print: Entry, ":CFBundleIdentifier", Does Not Exist
Command failed: /usr/libexec/PlistBuddy -c Print:CFBundleIdentifier build/Build/Products/Debug-iphonesimulator/myapp.app/Info.plist
Print: Entry, ":CFBundleIdentifier", Does Not Exist
In order to get rid of these, open up your Xcode and check for available simulators (as same as terminal listed) and run react-native run-ios --simulator="your device name"
For my case, I run react-native run-ios --simulator="iPhone 7", the problem solved.
A: What worked for me was opening the project in xcode and run the project there. Xcode then had a few problems for me. The first problem was that I had the wrong device selected to be used for testing.
I made sure that iPhone X simulator was selected (for some reason it was defaulting to my ipad which wasn't setup to be a dev device).
Then make sure when you run you have no red warnings. I had one more red warning and that was because I didn't select the project's team profile.
I also changed the bundle identifier to my company name to be unique.
Running it in xcode is the best way to know what the error is. Don't rely on react-native alone to figure out your errors.
A: it works for me when I deleted ~/.rncash
react-native info
React Native Environment Info:
System:
OS: macOS 10.14.1
CPU: x64 Intel(R) Core(TM) i5-4258U CPU @ 2.40GHz
Memory: 78.15 MB / 8.00 GB
Shell: 5.3 - /bin/zsh
Binaries:
Node: 8.11.3 - /usr/local/bin/node
Yarn: 1.9.4 - /usr/local/bin/yarn
npm: 6.3.0 - /usr/local/bin/npm
Watchman: 4.9.0 - /usr/local/bin/watchman
SDKs:
iOS SDK:
Platforms: iOS 12.1, macOS 10.14, tvOS 12.1, watchOS 5.1
IDEs:
Android Studio: 3.2 AI-181.5540.7.32.5056338
Xcode: 10.1/10B61 - /usr/bin/xcodebuild
npmPackages:
react: 16.6.0-alpha.8af6728 => 16.6.0-alpha.8af6728
react-native: 0.57.4 => 0.57.4
npmGlobalPackages:
create-react-native-app: 1.0.0
react-native-cli: 2.0.1
react-native-git-upgrade: 0.2.7
| |
doc_23538412
|
1) Apple has provided a function "addAttachment" and the doc says, to add any image in the content, we should use this function, but I tried that function, and sent an mail, I checked on my browser, it is recieved as an attachment.
2) Secondly, many blogs say to use base64 encoding, but that also wont work, image is sent as a broken one.
So friends, please help me out to find the best available solution to do this.
Regards
Ranjit
A: Set email format as HTML. This code is woking fine in my app.
MFMailComposeViewController *emailDialog = [[MFMailComposeViewController alloc] init];
NSString *htmlMsg = @"<html><body><p>This is your message</p></body></html>";
NSData *jpegData = UIImageJPEGRepresentation(emailImage, 1.0);
NSString *fileName = @"test";
fileName = [fileName stringByAppendingPathExtension:@"jpeg"];
[emailDialog addAttachmentData:jpegData mimeType:@"image/jpeg" fileName:fileName];
emailDialog setSubject:@"email subject"];
[emailDialog setMessageBody:htmlMsg isHTML:YES];
[self presentModalViewController:emailDialog animated:YES];
[emailDialog release];
Swift 5
import MessageUI
func composeMail() {
let mailComposeVC = MFMailComposeViewController()
mailComposeVC.addAttachmentData(UIImage(named: "emailImage")!.jpegData(compressionQuality: CGFloat(1.0))!, mimeType: "image/jpeg", fileName: "test.jpeg")
mailComposeVC.setSubject("Email Subject")
mailComposeVC.setMessageBody("<html><body><p>This is your message</p></body></html>", isHTML: true)
self.present(mailComposeVC, animated: true, completion: nil)
}
A: I've found that (at least in my case) a PNG will work in the message composer but NOT when the message is opened / received by the user.
Composer Dandily showing logo PNG image!
Viewer Not so much logo images over here.
(Occasionally there will be a light blue outline where the image should be.)
Using the HTML body string below and the conversion below that seems to do the trick.
Message Body HTML String using JPEG
NSString *body = [NSString stringWithFormat:
@"\
<html>\
<body>\
Check out the App!\
<br>\
Isn't this a terriffic logo?!.\
<br>\
<img src = \"data:image/jpeg;base64,%@\" width = 100 height= 100>\
<br>\
<a href = \"%@\" > CLICK ITTTTTTT! </a>\
</body>\
</html>",
imageString, @"http://www.LOLamazingappLOL.com"];
Convert Image to string with JPEG Data
+ (NSString *)dataStringFromImage:(UIImage *)image
{
NSData *imgData = UIImageJPEGRepresentation(image, 1);
return [imgData base64EncodedStringWithOptions:kNilOptions];
}
Additional Info:
*
*iOS Target = 8.0
*iOS Device = 9.1
*I am awful with HTML!
Thank you @Richard for the CORRECT answer to this question.
A: I just went through this recently for Swift.
Function to add photo to email in Swift:
func postEmail() {
var mail:MFMailComposeViewController = MFMailComposeViewController()
mail.mailComposeDelegate = self
mail.setSubject("your subject here")
var image = // your image here
var imageString = returnEmailStringBase64EncodedImage(image)
var emailBody = "<img src='data:image/png;base64,\(imageString)' width='\(image.size.width)' height='\(image.size.height)'>"
mail.setMessageBody(emailBody, isHTML:true)
self.presentViewController(mail, animated: true, completion:nil)
}
Function to return the formatted image:
func returnEmailStringBase64EncodedImage(image:UIImage) -> String {
let imgData:NSData = UIImagePNGRepresentation(image)!;
let dataString = imgData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
return dataString
}
A: Few things to note:
- Use addAttachmentData
- use setMessageBody and set isHTML:true
you dont have to add manually in your email body. the api will take care of that.
func postEmail() {
var mail:MFMailComposeViewController = MFMailComposeViewController()
mail.mailComposeDelegate = self
mail.setSubject("your subject here")
var image = // your image here
var imageData = UIImageJPEGRepresentation(image, 1)
mail.addAttachmentData(imageData, mimeType:"image/jpeg", fileName:"Your Filename"
var emailBody = "<html><body><p>This is your message</p></body></html>"
mail.setMessageBody(emailBody, isHTML:true)
self.presentViewController(mail, animated: true, completion:nil)}
| |
doc_23538413
|
2020-07-24 01:38:31,662 ERROR [io.sma.rea.mes.kafka] (executor-thread-870) SRMSG18207: Unable to dispatch message to Kafka: io.smallrye.mutiny.subscription.BackPressureFailure: Could not emit tick 211 due to lack of requests
at io.smallrye.mutiny.operators.multi.builders.IntervalMulti$IntervalRunnable.run(IntervalMulti.java:83)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294)
at org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
at org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:2046)
at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1578)
at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1452)
at org.jboss.threads.DelegatingRunnable.run(DelegatingRunnable.java:29)
at org.jboss.threads.ThreadLocalResettingRunnable.run(ThreadLocalResettingRunnable.java:29)
at java.lang.Thread.run(Thread.java:748)
at org.jboss.threads.JBossThread.run(JBossThread.java:479)
So I ve read https://smallrye.io/smallrye-mutiny/#_how_do_i_control_the_back_pressure
According to the documentation I ve add BackPressure control.
Before :
@Outgoing( "eqs-crossing-xxx" )
public Multi< EQSAlert > eqsCrossingXXX_XXX(){
final String series = CrossingEnum.XXX_XXX.getSeries();
final String equipment = CrossingEnum.XXX_XXX.getEquipment();
final String vehicleRegex = vehicleRegexService.getRegexBySeries( series );
log.info( "Incoming request for {} - {}", series, equipment);
log.info( "Vehicle regex : {}", vehicleRegex );
return Multi
.createFrom()
.ticks()
.every(
Duration.ofSeconds( poolingInterval )
)
.concatMap(i -> {
final Multi<CrossingState> crossingStateBySeriesAndEquipment = CrossingState.getCrossingStateBySeriesAndEquipment(client, series, equipment);
return crossingStateBySeriesAndEquipment.flatMap(crossingState ->
crossingState.isActive() ?
EQSAlert.getEQSAlertBySeriesAndEquipment(
client,
series,
vehicleRegex,
equipment
)
:
Multi.createFrom().empty()
);
});
}
After :
@Outgoing( "eqs-crossing-xxx" )
public Multi< EQSAlert > eqsCrossingXXX_XXX(){
final String series = CrossingEnum.XXX_XXX.getSeries();
final String equipment = CrossingEnum.XXX_XXX.getEquipment();
final String vehicleRegex = vehicleRegexService.getRegexBySeries( series );
log.info( "Incoming request for {} - {}", series, equipment);
log.info( "Vehicle regex : {}", vehicleRegex );
return Multi
.createFrom()
.ticks()
.every(
Duration.ofSeconds( poolingInterval )
)
.onOverflow()
.buffer(10)
.concatMap(i -> {
final Multi<CrossingState> crossingStateBySeriesAndEquipment = CrossingState.getCrossingStateBySeriesAndEquipment(client, series, equipment);
return crossingStateBySeriesAndEquipment.flatMap(crossingState ->
crossingState.isActive() ?
EQSAlert.getEQSAlertBySeriesAndEquipment(
client,
series,
vehicleRegex,
equipment
)
:
Multi.createFrom().empty()
);
});
}
And now evrything is ok.
The purpose of my post is to understand why I need to do it ?
https://smallrye.io/smallrye-mutiny/apidocs/io/smallrye/mutiny/subscription/BackPressureStrategy.html
Why the buffer can't keep u ?
As you can see I do a simple sql function call every 5s (poolingInterval). The function returns some records (never more than 10 by pooling)
So the traffic is very low
May I have some words to understand the buffer management please.
Thank you
A: Your downstream can only consume a certain number of items per unit of time. It depends on what you are doing. By default, Kafka limits itself to 5 concurrent writes (you can configure it).
So, if you emit more, in an unbounded - not back-pressure aware - manner, the downstream cannot keep up. Adding a buffer of 10 items may handle small bumps, but it might not be enough.
drop is more radical; if the downstream cannot keep up, the items are simply discarded. dropPreviousItems is dropping the already received items.
| |
doc_23538414
|
From a computer I need to run two versions, in two different enterprises.
Each version has a different jnlp file:
Version 1 JNLP 1- IBM-JRE1.5.0
...
...
<resources>
<j2se version="1.5.0-ibm" href="file://C:/Archivos de Programa/Java/ibm-jre1.5.0"/>
...
...
Version 2 - Oracle jre 1.6
...
...
<resources>
<j2se version="1.6" max-heap-size="1024m"/>
...
...
Running Windows XP, I can run both apps whith javaws, first one with the javaws command of ibm-jre1.5.0 and the second one with the javaws command of jre 1.6
Now, I have Windows 7, and when I try to run the first one, I get the next error
You can not load the resource: (file://C:/Program Files/Java/ibm-jre1.5.0, 1.5.0-ibm)
JNLPException[category: Download Error: Exception: java.net.UnknownHostException: C : LaunchDesc: null ]
at com.sun.javaws.cache.DownloadProtocol.doDownload(DownloadProtocol.java:686)
at com.sun.javaws.cache.DownloadProtocol.getJRE(DownloadProtocol.java:745)
at com.sun.javaws.LaunchDownload.downloadJRE(LaunchDownload.java:579)
at com.sun.javaws.Launcher.downloadResources(Launcher.java:1080)
at com.sun.javaws.Launcher.handleApplicationDesc(Launcher.java:424)
at com.sun.javaws.Launcher.handleLaunchFile(Launcher.java:254)
at com.sun.javaws.Launcher.run(Launcher.java:201)
at java.lang.Thread.run(Thread.java:801)
Any idea ?
Thanks a lot
| |
doc_23538415
|
JSONParser jsonParser = new JSONParser();
JSONObject obj = (JSONObject) jsonParser.parse(new FileReader(args[1]));
JSONObject transUnit = (JSONObject) obj.get("trans-unit");
id = (String) transUnit.get("id");
if (id == null) {
System.out.println("Id is required parameter!");
return;
}
source = (String) transUnit.get("source");
JSONObject targetList = (JSONObject) transUnit.get("target");
if (targetList != null) {
qualifier = (String) targetList.get("state-qualifier");
targetText = (String) targetList.get("target-text");
}
JSONObject altTransList = (JSONObject) transUnit.get("alt-trans");
if (altTransList != null) {
extype = (String) altTransList.get("extype");
match = (String) altTransList.get("match-quality");
origin = (String) altTransList.get("origin");
sourceAlt = (String) altTransList.get("source");
targetAlt = (String) altTransList.get("target");
}
It run, when I read json file below
"trans-unit": {
"id": "t1",
"source": "Text text text text",
"target": {
"state-qualifier": "exact-match",
"target-text": "Tekst tekst tekst tekst",
},
"alt-trans": {
"extype": "exact-match",
"match-quality": "100%",
"source": "Text text text text",
"target": "Tekst tekst tekst tekst"
}
}
}
But when a read this json:
{
"trans-unit": {
"id": "t1",
"source": "Text text",
"target": {
"state-qualifier": "match",
"target-text": "Tekst tekst"
},
"alt-trans": {
"extype": "match",
"match-quality": "100%",
"source": "Text text",
"target": "Tekst tekst"
}
},
"trans-unit": {
"id": "t2",
"source": "Hello there.",
"target": {
"state-qualifier": "mt",
"target-text": "Cześć"
},
"alt-trans": {
"extype": "TRANSLATION",
"match-quality": "nmt",
"source": "Hello there.",
"target": "Cześć"
}
}
}
JSON dont't read trans unit with id t1 but read only tran-unit t2.
I don't know where the problem lies. Can anyone help?
A: What do you really want to achieve?
I think the problem is, that the second json data is kind of List or Array.
So you only will get the last "object".
Are you allowed to use any library like gson ? This will make it a lot easier.
| |
doc_23538416
|
For example:
L = [3,1,2,5,4,7].
P = (2,5).
Given this example, I should get *Found* as 2,5 appears on 2nd and 3rd position in list L.
Here is my approach , but I am getting a false answer.
search_pair([_|[]],_).
search_pair([X|T],(F,L)) :-
first(Y, T),
write('searching: '),write(F),write(' '),write(L),nl,
write('trying: '),write(X),write(' '),write(Y),nl,
((F == L , L = Y) -> (write('Found'))
search_pair(T,(F,L),R).
A: The actual relation is quite easy to describe. There are two cases:
*
*case 1: The list starts with the given pair. In this case we're done.
*case 2: Otherwise we need to keep searching in the tail of the list.
This can be written with if_/3 and (',')/3 like so:
pair_in((X,Y),[A,B|Cs]) :-
if_((X=A,Y=B),
true, % <- case 1
pair_in((X,Y),[B|Cs])). % <- case 2
Querying this with your example and a counterexample:
?- pair_in((2,5),[3,1,2,5,4,7]).
yes
?- pair_in((2,4),[3,1,2,5,4,7]).
no
If you want to output the message *Found* in the case of success, I would suggest to relocate that to a calling predicate, e.g. your predicate search_pair/2:
search_pair(L,P) :- % <- calling predicate
pair_in(P,L), % <- actual relation
format('*Found*~n'). % <- output
Now let's query this predicate with the above examples:
?- search_pair([3,1,2,5,4,7],(2,5)).
*Found*
yes
?- search_pair([3,1,2,5,4,7],(2,4)).
no
As you can see *Found* is only displayed in the case of success. That is because in case the goal pair_in(P,L) fails, Prolog doesn't move on to the next goal, since the rule cannot become true any more.
| |
doc_23538417
|
The code below is my library. I call GetArticles() but it does not return any of the which creates a list of tasks that call GetComments() to asynchronously get the comments.
I've tried using Task.WaitAll in GetArticles to wait for the comments but it does not block the thread. Any help would be appreciated.
private const string ArticlesUri = "";
public async Task<List<ArticleBrief>> GetArticles()
{
var results = new List<ArticleBrief>();
try
{
var wfw = XNamespace.Get("http://wellformedweb.org/CommentAPI/");
var media = XNamespace.Get("http://search.yahoo.com/mrss/");
var dc = XNamespace.Get("http://purl.org/dc/elements/1.1/");
var t = await WebHttpRequestAsync(ArticlesUri);
StringReader stringReader = new StringReader(t);
using (var xmlReader = System.Xml.XmlReader.Create(stringReader))
{
var doc = System.Xml.Linq.XDocument.Load(xmlReader);
results = (from e in doc.Element("rss").Element("channel").Elements("item")
select
new ArticleBrief()
{
Title = e.Element("title").Value,
Description = e.Element("description").Value,
Published = Convert.ToDateTime(e.Element("pubDate").Value),
Url = e.Element("link").Value,
CommentUri = e.Element(wfw + "commentRss").Value,
ThumbnailUri = e.Element(media + "thumbnail").FirstAttribute.Value,
Categories = GetCategoryElements(e.Elements("category")),
Creator = e.Element(dc + "creator").Value
}).ToList();
}
var tasks = new Queue<Task>();
foreach (var result in results)
{
tasks.Enqueue(
Task.Factory.StartNew(async ()=>
{
result.Comments = await GetComments(result.CommentUri);
}
));
}
Task.WaitAll(tasks.ToArray());
}
catch (Exception ex)
{
// should do some other
// logging here. for now pass off
// exception to callback on UI
throw ex;
}
return results;
}
public async Task<List<Comment>> GetComments(string uri)
{
var results = new List<Comment>();
try
{
var wfw = XNamespace.Get("http://wellformedweb.org/CommentAPI/");
var media = XNamespace.Get("http://search.yahoo.com/mrss/");
var dc = XNamespace.Get("http://purl.org/dc/elements/1.1/");
var t = await WebHttpRequestAsync(uri);
StringReader stringReader = new StringReader(t);
using (var xmlReader = System.Xml.XmlReader.Create(stringReader))
{
var doc = System.Xml.Linq.XDocument.Load(xmlReader);
results = (from e in doc.Element("rss").Element("channel").Elements("item")
select
new Comment()
{
Description = e.Element("description").Value,
Published = Convert.ToDateTime(e.Element("pubDate").Value),
Url = e.Element("link").Value,
Creator = e.Element(dc + "creator").Value
}).ToList();
}
}
catch (Exception ex)
{
// should do some other
// logging here. for now pass off
// exception to callback on UI
throw ex;
}
return results;
}
private static async Task<string> WebHttpRequestAsync(string url)
{
//TODO: look into getting
var request = WebRequest.Create(url);
request.Method = "GET";
var response = await request.GetResponseAsync();
return ReadStreamFromResponse(response);
}
private static string ReadStreamFromResponse(WebResponse response)
{
using (Stream responseStream = response.GetResponseStream())
using (StreamReader sr = new StreamReader(responseStream))
{
string strContent = sr.ReadToEnd();
return strContent;
}
}
private List<string> GetCategoryElements(IEnumerable<XElement> categories)
{
var listOfCategories = new List<string>();
foreach (var category in categories)
{
listOfCategories.Add(category.Value);
}
return listOfCategories;
}
Updated Code from Solution, just added .UnWrap() on the Enqueue method:
var tasks = new Queue<Task>();
foreach (var result in results)
{
tasks.Enqueue(
Task.Factory.StartNew(async ()=>
{
result.Comments = await GetComments(result.CommentUri);
}
).Unwrap());
}
Task.WaitAll(tasks.ToArray());
A: It is waiting appropriately. The problem is that you are creating a Task which creates another task (i.e. StartNew is returning a Task<Task> and you are only waiting on the outer Task which completes rather quickly (it completes before the inner Task is complete)).
The questions will be:
*
*Do you really want that inner task?
*
*If yes, then you can use Task.Unwrap to get a proxy task that represents the completion of both the inner and outer Task and use that to Wait on.
*If no, then you could remove the use of async/await in StartNew so that there is not an inner task (I think this would be prefered, it's not clear why you need the inner task).
*Do you really need to do a synchronous Wait on an asynchronous Task? Read some of Stephen Cleary's blog: http://blog.stephencleary.com/2012/02/async-unit-tests-part-1-wrong-way.html
As an aside, if you are not using C# 5, then watch out for closing over the foreach variable result See
*
*Has foreach's use of variables been changed in C# 5?, and
*http://blogs.msdn.com/b/ericlippert/archive/2009/11/12/closing-over-the-loop-variable-considered-harmful.aspx)
A: In Microsoft.Bcl.Async we couldn't add any static methods to Task. However, you can find most of the methods on TaskEx, for example, TaskEx.WhenAll() does exist.
| |
doc_23538418
|
I went ahead and built what I thought was a good approach and looped through all the forms one-by-one and posted the data to a PHP page using AJAX. This worked fine, but like I mentioned, with 20+ photos, it's running 20 AJAX requests and 20 SQL updates, and now feel this is a poor effort.
I'm now looking at other ways that involve looping through each form, creating an array or object, and sending it in one request and have one nifty SQL query to update all rows at once.
This is where I'm at now. I'm struggling to get the form fields into a readable and usable object for my PHP to read.
MY FORM STRUCTURE
<form name="12344">
<div class="input_wrap">
<textarea id="12344_caption"></textarea>
</div>
<div class="input_wrap">
<input type="text" id="12344_keywords" />
</div>
<div class="input_wrap">
<input type="text" id="12344_credit" />
</div>
<div class="input_wrap">
<input type="text" id="12344_credit_url" />
</div>
</form>
<form name="12345">
<div class="input_wrap">
<textarea id="12345_caption"></textarea>
</div>
<div class="input_wrap">
<input type="text" id="12345_keywords" />
</div>
<div class="input_wrap">
<input type="text" id="12345_credit" />
</div>
<div class="input_wrap">
<input type="text" id="12345_credit_url" />
</div>
</form>
MY JQUERY SO FAR
var photo_annotations = {};
$('form').each(function(i) {
var id = $(this).attr('id');
var caption = $('#'+id+'_caption').val();
var keywords = $('#'+id+'_keywords').val();
var credit = $('#'+id+'_credit').val();
var credit_url = $('#'+id+'_credit_url').val();
// create object to post
photo_annotations[id].push({});
(help)
}
$.ajax({
type: 'POST',
url: 'ajax/save-annotations.php',
data: { json: JSON.stringify(photo_annotations) }
});
This is the kind of data I'd like to construct:
photo_annotations = {
"12344": {
"caption": "This is a caption for the photo ID 12344.",
"keywords": "Keyword1, Keyword2, Keyword3",
"credit": "John Doe",
"credit_url": "http://www.johndoe.com"
},
"12345": {
"caption": "This is a caption for the photo ID 12345.",
"keywords": "Keyword4, Keyword5, Keyword6",
"credit": "Joe Bloggs",
"credit_url": "http://www.joebloggs.com"
}
}
I'm struggling to get my form fields into JSON correctly, in the format I showed you above. I hope that somebody could show me how to achieve this format.
A: photo_annotations[id] = {
caption: caption
/* and so on */
};
A: You don't need push or separate variables. You can just build it directly like this:
photo_annotations[id] = {
id: $(this).attr('id'),
caption: $('#'+id+'_caption').val(),
keywords: $('#'+id+'_keywords').val(),
credit: $('#'+id+'_credit').val(),
credit_url: $('#'+id+'_credit_url').val()
}
| |
doc_23538419
|
The line overlap each other even if the point values are different.
IN the image there are two lines for different data, the point values are different they are 22 and 793..
| |
doc_23538420
|
Question:
How to deploy C# Windows Application (setup file) with SQL Server database with database connection string.
I create common connection string in app.config :
<connectionStrings>
<add name="conString"
providerName="System.Data.sqlclient"
connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=
'C:\Users\DEVELOPERS\Documents\Visual Studio 2015\Projects\Provision1\
Provision1\provision1.mdf';Integrated Security=True"/>
</connectionStrings>
Now connection string path location shows my machine.
Then after installation .exe how to connect database and how to manage connection string on client machine.
A: The easiest way you can do is:
*
*Save your connection string in app.config is absolutly common
*Compile your Project with Release settings
*Take your .exe file from /bin/release/.. Folder
*The Database should be connected via the connection string. If the database is not connected via network you need to deploy it as well.
*Make sure your clients have .Net Framework installed
If you definitive need a setup.exe which installs your software, you can make a new project which is of type setup-programm. Watch this link for description.
If you don't want your users to see the connectionstring you can use a ConnectionStringBuilder. Save just a part of your connection string to app.config and build the rest via Quellcode. Watch this MSDN-Article.
| |
doc_23538421
|
((MainActivity)getActivity()).nextPage(view);
This is the function in my MainActivity:
// To 2nd page from 1st
public void nextPage(View view) {
mViewPager.setCurrentItem(2);
}
Why can't I do this? All I want to do is move to the next fragment without actually replacing the view because this interrupts my app's experience. The following is how you would do it traditionally, but this will not work for my purposes:
NextFragment nextFrag= new NextFragment();
this.getFragmentManager().beginTransaction()
.replace(R.id.layout, nextFrag, TAG_FRAGMENT)
.addToBackStack(null)
.commit();
I get the following error message:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at com.app.test.TemplateFragment.DrawTemplateWithTransparency(TemplateFragment.java:894)
at com.app.test.MainActivity.SetupTemplate(MainActivity.java:443)
at com.app.test.MainActivity.nextPage(MainActivity.java:381)
at com.app.test.DesignerFragment.handleIncomingIntent(DesignerFragment.java:401)
at com.app.test.DesignerFragment.onResume(DesignerFragment.java:195)
at android.support.v4.app.Fragment.performResume(Fragment.java:2005)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1108)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1248)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1613)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:570)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1106)
at android.support.v4.view.ViewPager.populate(ViewPager.java:952)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1474)
at android.view.View.measure(View.java:18794)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
at android.view.View.measure(View.java:18794)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
at android.support.v7.internal.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:124)
at android.view.View.measure(View.java:18794)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
at android.view.View.measure(View.java:18794)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
at android.view.View.measure(View.java:18794)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
at android.view.View.measure(View.java:18794)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2643)
at android.view.View.measure(View.java:18794)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2100)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1216)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1452)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6013)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
at android.view.Choreographer.doCallbacks(Choreographer.java:670)
at android.view.Choreographer.doFrame(Choreographer.java:606)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(Zygo
| |
doc_23538422
|
I wrote down the following code:
imgnew = imread('C:\Users\vijay kant chadha\Downloads\earth.jpg');
//The following line's execution shows error
imshow(imgnew);
//error: invalid conversion of uint8 matrix to Matrix
Please help me for the same... :)
| |
doc_23538423
|
(1) environment.dev.ts
export const environment = {
"http://some.url": "value"
}
results in
var r = { http://some.url: "value" };
(2) environment.dev.ts
let _environment = {};
_environent["http://some.url"] = "value";
export const environment = _environment;
becomes:
var r = {};
r.http://some.url = "value";
A: Seems your are using environment.ts not in the correct way, usually it should be like below
export const environment = {
"apiUrl": "http://some.url"
}
and in your code you will use it like
const url = environment.apiUrl;
| |
doc_23538424
|
To test the plugin using mocha, mocha runs in a node environment and because of this, fetch isn't implemented.
It can be made to work in node using:
declare const require: any
fetch = require('cross-fetch');
fetch(url)
However, the require statement raises an ugly error when running in the browser.
Ideally I'd like to have something like:
if(typeof fetch !== 'undefined'){ const fetch = require('cross-fetch'); }
fetch(url)
However, this obviously scopes fetch to the if statement and it can't be used globally. If I try
if(typeof fetch !== 'undefined'){ fetch = require('cross-fetch'); }
Then typescript complains that fetch is already defined as a function (typescript is basing this on the browser environment). So it won't compile.
Is there a way to either 1.) tell typescript that fetch might NOT be defined even though it thinks that it is, or 2.) to enable fetch globally some other way
Meta-question: how are other people testing their browser-based javascript? Surely there's an easier way than making the javascript work in a node environment?
| |
doc_23538425
|
I'm trying to insert
<div onmouseover="alert(1)" style="position:fixed;left:0;top:0;width:9999px;height:9999px;">
</div>
inside a textarea. Server-side, I just want to display $_GET with a var_dump for now but it doesn't even get to that: when I click the button it just brings me back to the homepage and #3377832596384266514 is added to the URL. I don't get any error in PHP so maybe it's a server issue (Apache 2.4).
I'm guessing some part of the stack is being defensive, like when you add javascript: to a URL and the browser gets rid of it, but I don't know where to look. I've also tried
<script>alert(foo);</script>
and other variations but then the < and some other characters are stripped.
test.php
<!doctype html>
<head>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<form method="get" action="select.php">
<p>
<label for="select">Words
<textarea id="select"
name="select"
cols="50"
rows="1"
maxlength="100"
required
autofocus></textarea>
</label>
</p>
<p>
<button>Send</button>
</p>
</form>
</body>
</html>
select.php
<?php
var_dump($_GET);
Edit: textarea instead of input.
Edit: added all the code.
A: Input tags can't have any content, that's why you can set it as an self-closing element <input />
maybe you need another approach
A: Change the form method from GET to POST.
GET is possibly causing an issue with how the server handles certain markup in the URL.
OP verified this resolved the issue.
| |
doc_23538426
|
Confirmation confirmation = new Confirmation()
{
Title = "Confirmation",
Content = "Do you really want to do this?"
};
DeleteConfirmationRequest.Raise(confirmation, c => {
if (c.Confirmed)
{
// do something terrible
}
});
However, since I don't really care in this case whether the user cancelled the request or didn't even subscribe to the confirmation, I can do this instead:
Confirmation confirmation = new Confirmation()
{
Title = "Confirmation",
Content = "Do you really want to do this?"
};
DeleteConfirmationRequest.Raise(confirmation);
if (confirmation.Confirmed)
{
// do something terrible
}
As far as I can tell, there is no real difference between these two. Am I right, or am I missing something here?
A: Do you mean synchronous = a PopupWindowAction with IsModal=true for example?
In this case, the variant without the callback is fine, I guess.
Although the callback-variant is safer if implementations change, and, for example, the action's Invoke doesn't block anymore or the Confirmation is cloned internally and the callback doesn't get the same instance you passed in...
| |
doc_23538427
|
echo -n 'a' >/dev/udp/localhost/8125
echo -n 'b' >/dev/udp/localhost/8125
echo -n 'c' >/dev/udp/localhost/8125
Everything that is written to that file should be – instead of being handled by Datadog and sent to them via the agent – written to a log file. After executing the three lines above the log file should contain the following:
a
b
c
I thought that a named pipe and a background process that handles that would be perfect. However, it does not work as expected and the background process never writes anything, even though writing seems to work.
I created the following script:
#!/usr/bin/env bash
set -Eeuo pipefail
log=/var/log/datadog-agent.log
touch $log
# https://docs.datadoghq.com/developers/dogstatsd/datagram_shell/
pipe=/dev/udp/localhost/8125
if [[ ! -p $pipe ]]; then
rm -f $pipe
mkdir -p "$(dirname $pipe)"
mkfifo -m 0666 $pipe
fi
trap 'rm -f $pipe' EXIT
while :; do
read -r line <$pipe
echo "$line" >>$log
done
And the following systemd service:
[Unit]
Description=Fake Datadog Agent
[Service]
ExecStart=/usr/local/bin/datadog-agent
Type=exec
[Install]
WantedBy=multi-user.target
The service is started correctly after executing systemctl enable --now datadog-agent, however, as I said, nothing is ever being written to the log file.
This is very strange to me because opening two shell instances where I write the following in the first shell:
mkfifo pipe
while :; do read -r line <pipe; echo "$line"; done
And then start sending data in the second shell prints the lines correctly.
A: The answer to the question is found in the comments to it. Hence, this question should not go unanswered.
The code from the question works as expected, however, the path where the named pipe resides is a special path and this is the reason why the data that is being sent to it never reaches the script. The corresponding special casing in Bash for instance can be found in redir.c.
The solution to the problem is to use a real UDP server on that port:
socat -u -v -x udp-listen:8125,fork /dev/null &>/var/log/datadog-agent.log
| |
doc_23538428
|
protected void Button1_Click(object sender, EventArgs e)
{
lblDateToday = DateTime.Now.ToString("MMMMMM dd, yyyy HH:mm");
lblValiDate = <output date: 5 days from the current>
}
Any ideas? Thanks in advance!
A: Get the current DateTime as a DateTime type, then you can use the AddDays extension method to increment the Date.
protected void Button1_Click(object sender, EventArgs e)
{
DateTime dateToday = DateTime.Now;
DateTime dateInFiveDays = dateToday.AddDays(5);
lblDateToday = dateToday.ToString("MMMMMM dd, yyyy HH:mm");
lblValiDate = dateInFiveDays.ToString("MMMMMM dd, yyyy HH:mm");
}
https://msdn.microsoft.com/en-us/library/system.datetime.adddays(v=vs.110).aspx
A: DateTime.Now.AddDays(5).ToString(@"MMMMMM dd, yyyy HH:mm");
A: you can use AddDays to add days to your current date.
DateTime dt = DateTime.Now;
lblDateToday = dt.ToString("MMMMMM dd, yyyy HH:mm");
lblValiDate = dt.AddDays(5).ToString("MMMMMM dd, yyyy HH:mm");
Fiddler Demo
| |
doc_23538429
|
for example "hello" to "h", "l", "l", "o" and store them in an array.
A: Just use the string as if i would be a array. In a c++'s std::string if example equals "Hello world!" then example[0] equals 'H', example[1] equals 'e' and so on.
If you really need to copy the string to an array of chars for some reason, you can use the strcpy function from the string.h library. Here an example:
#include <iostream>
#include <string>
int main() {
std::string example = "Hello world!";
char arr[example.length()];
strcpy(arr,example.c_str());
for(int i = 0; i < example.length(); i++)
std::cout << arr[i];
return 0;
}
A: It's already an array. :)
Strings are (or are exposed as) arrays of characters, even when hidden behind a controlling class like std::string.
So, if you need to use it with array subscript syntax (e.g. myString[i]), then simply do that.
A: I think this will help you.
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
string s="Hello";
for(int i=0;i<s.length();i++)
{
printf("%c,",s[i]);
}
}
| |
doc_23538430
|
/db/migrate
how can I run them?
I've tried running
bundle exec rails g gem-name:install
but I get an error saying could not find generator gem-name:install.
I've run up against this problem with 3 different Gems this morning. What am I missing?
A: Old question, so sorry for the bump, but you were actually pretty dang close.
the correct command would be rails gem_name:install:migrations
| |
doc_23538431
|
A: You could save the player as a prefab and spawn it in with the Start method in the new scene.
Or, if you have a link to the player's gameobject use this:
DontDestroyOnLoad(PLAYER_GO);
If you don't have a link to it you could just put this on the Start method on the player
DontDestroyOnLoad(this.gameObject);
A: While you can use DontDestroyOnLoad as described by RadiantMin3, you actually can just move an object between scenes! https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.MoveGameObjectToScene.html
Just make sure to load game_scene_2 additively, and then unload game_scene_1 after moving the player. Example:
SceneManager.LoadScene(game_scene_2, LoadSceneMode.Additive);
SceneManager.MoveGameObjectToScene(player.gameObject, game_scene_2);
SceneManager.UnloadScene(game_scene_1);
This will load the game_scene_2 without unloading game_scene_1, move the player while both scenes are loaded and then unload game_scene_1.
| |
doc_23538432
|
Full path to the file : file:///D:/DYPLOM%20PROJECT/src/main/resources/static/slov.png
When I run in the browser full path, everything in working and image is uploading.
I tried different variants but have the same issue - image is not loading in my html page
———————————————————————-
It is my welcomePage where I need to load image
Image slov.png stores in the /resources/static, you can see it :
And when I go to localhost - welcomePage , I have it :
Console errors :
This errors with the path <img src="../../resources/static/slov.png">
A: You need to write like this.
<img src="../static/slov.png">
A: I would suggest rewriting the img tag like so:
<img src="../static/slov.png">
This will locate the resource correctly.
A: Try <img src="static/slov.png">
A: It looks like you're requesting a location of the image which doesn't exist.
Try changing your img tag to the following:
<img src="../../resources/static/slov.png">
With this edit, you should get your image now.
| |
doc_23538433
|
A: I'm not sure if this is the same, but I think you might mean a weak reference.
Weak references are used in languages that have garbage collection to have a reference to an object without blocking the garbage collection from deleting the object if no non-weak references exist.
Different languages have different semantics for this functionality. Java defines soft, weak and phantom references, each with slightly different mechanics.
This is useful in many situations. For example, on the Blackberry, you can define a Listener object that listens for system events (such as a call coming in). When you register your listener with the system, it keeps a weak reference to it. That way, when all other references to that object go away (such as when the application shuts down), the weak reference no longer points to the listener and the memory is for that listener is freed without the programmer having to remember to unregister it.
A: I think you might be referring to PhantomReference.
A: As I stated in the comment, I don't know of a ghost reference, but this article has a nice write-up on the various weak references (weak, soft, and phantom). It even mentions the ReferenceQueue issue, though I must say that I hadn't heard that before.
A: GhostReference the most recent concept that I know is PhantomReference, if you want to know it, by my experience, you should understand Strong reference then weak reference then soft reference. after these knowledge, you might more easily to understand PhantomReference.
In short word, these reference just help garbarge collector works more properly. (It means some times, you don't need to know these concepts and you program still run ... in short time)
| |
doc_23538434
|
is there a way to identify possible session-saving problem?
I init a session in such way
app.set("trust proxy", 1)
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: true,
cookie:
{
secure: false, httpOnly:false,
sameSite: false,
maxAge: 30 * 24 * 60 * 60 * 1000,
}
}));
i try to debug code, but don't a source of problem
| |
doc_23538435
|
Error: dictionary changed size during iteration
at startup. No exception trace given.
I'm starting gunicorn with:
gunicorn --chdir src main:app -w 2 -k uvicorn.workers.UvicornWorker -b :8000 --error-logfile=- --access-logfile=- -R --preload
no config file.
Offending line seems to be:
log = logging.getLogger((__name__[:8] + '..') if len(__name__) > 8 else __name__)
while running with
log = logging.getLogger('modifiers')
starts and runs as expected.
gunicorn==20.1.0
uvicorn==0.20.0
Python 3.11.2
Tested with the same breaking code on linux, windows in WSL, and in docker.
Most relevant issue I found is #2784 but it seems to have been long closed.
Starting it without --preload also does not cause the error, with or without my code that causes it, but I need --preload...
My attempts at debugging fail miserably as adding --log-level=debug to the start options of gunicorn seems to do nothing about my problem other than listing its "configuration".
Which (not sure how much that is helpful) is :
[2023-02-26 20:26:05 +0200] [5623] [DEBUG] Current configuration:
config: ./gunicorn.conf.py
wsgi_app: None
bind: [':8000']
backlog: 2048
workers: 2
worker_class: uvicorn.workers.UvicornWorker
threads: 1
worker_connections: 1000
max_requests: 0
max_requests_jitter: 0
timeout: 30
graceful_timeout: 30
keepalive: 2
limit_request_line: 4094
limit_request_fields: 100
limit_request_field_size: 8190
reload: False
reload_engine: auto
reload_extra_files: []
spew: False
check_config: False
print_config: False
preload_app: True
sendfile: None
reuse_port: False
chdir: /mnt/e/src/xxxxx/src
daemon: False
raw_env: []
pidfile: None
worker_tmp_dir: None
user: 1000
group: 1000
umask: 0
initgroups: False
tmp_upload_dir: None
secure_scheme_headers: {'X-FORWARDED-PROTOCOL': 'ssl', 'X-FORWARDED-PROTO': 'https', 'X-FORWARDED-SSL': 'on'}
forwarded_allow_ips: ['127.0.0.1']
accesslog: -
disable_redirect_access_to_syslog: False
access_log_format: %(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"
errorlog: -
loglevel: debug
capture_output: False
logger_class: gunicorn.glogging.Logger
logconfig: None
logconfig_dict: {}
syslog_addr: udp://localhost:514
syslog: False
syslog_prefix: None
syslog_facility: user
enable_stdio_inheritance: True
statsd_host: None
dogstatsd_tags:
statsd_prefix:
proc_name: None
default_proc_name: main:app
pythonpath: None
paste: None
on_starting: <function OnStarting.on_starting at 0x7f024794b7e0>
on_reload: <function OnReload.on_reload at 0x7f024794b920>
when_ready: <function WhenReady.when_ready at 0x7f024794ba60>
pre_fork: <function Prefork.pre_fork at 0x7f024794bba0>
post_fork: <function Postfork.post_fork at 0x7f024794bce0>
post_worker_init: <function PostWorkerInit.post_worker_init at 0x7f024794be20>
worker_int: <function WorkerInt.worker_int at 0x7f024794bf60>
worker_abort: <function WorkerAbort.worker_abort at 0x7f02479600e0>
pre_exec: <function PreExec.pre_exec at 0x7f0247960220>
pre_request: <function PreRequest.pre_request at 0x7f0247960360>
post_request: <function PostRequest.post_request at 0x7f0247960400>
child_exit: <function ChildExit.child_exit at 0x7f0247960540>
worker_exit: <function WorkerExit.worker_exit at 0x7f0247960680>
nworkers_changed: <function NumWorkersChanged.nworkers_changed at 0x7f02479607c0>
on_exit: <function OnExit.on_exit at 0x7f0247960900>
proxy_protocol: False
proxy_allow_ips: ['127.0.0.1']
keyfile: None
certfile: None
ssl_version: 2
cert_reqs: 0
ca_certs: None
suppress_ragged_eofs: True
do_handshake_on_connect: False
ciphers: None
raw_paste_global_conf: []
strip_header_spaces: False```
(venv_linux) teo@jailbreaker-pc:/mnt/e/src/price-optimizer$ gunicorn --chdir src main:app -w 2 -k uvicorn.workers.UvicornWorker -b :8000 --error-logfile=- --access-logfile=- -R --preload
[2023-02-26 22:58:17 +0200] [6181] [INFO] Starting gunicorn 20.1.0
Error: dictionary changed size during iteration
(venv_linux) teo@jailbreaker-pc:/mnt/e/src/price-optimizer$
So, what would be a smart way to proceed?
UPDATE 2023-02-27:
Went through the entire program (ca. 15 files) and stripped all the logging -- deleted import logging, changed all calls to log to print()s.
Then I left only one call to getLogger in a single file. And again, calling
log = logging.getLogger('modifiers')
or any "static" string works,but changing this to
log = logging.getLogger((__name__[:8] + '..') if len(__name__) > 8 else __name__)
yields
Error: dictionary changed size during iteration
on app start.
To me that makes no sense.
| |
doc_23538436
|
Within message-13, will appear a value either; 1,2,3,4 or 5 depending on the hotel on buttonclick
Before any query has been made, it will show 0 stars
I have tried wrapping the script contents into a function that gets called on button click, but that did not work either.
Here is the core code:
<p id="message-13"></p>
<script>
const ratings = {
hotel_a : 0
}
var hotel_a = parseInt(document.getElementById("message-13").innerHTML,10);
// total number of stars
const starTotal = 5;
for(const rating in ratings) {
const starPercentage = (ratings[rating] / starTotal) * 100;
const starPercentageRounded = `${(Math.round(starPercentage / 10) * 10)}%`;
document.querySelector(`.${rating} .stars-inner`).style.width = starPercentageRounded;
}
</script>
Once a query has been made, I want to pass the value from message-13 into the key: hotel_a
However, I am unable to update the hotel_a value
The search button:
<form>
<input placeholder="Search here">
<button>Search</button>
</form>
The search then calls an api to retrieve JSON parsed data of which includes the hotel rating. This is in the form of id=message-13 which returns the value 1 to 5
I have another javascript which fetches the data from a long url:
const messageThirteen = document.querySelector('#message-13')
const messageFourteen = document.querySelector('#message-14')
fetch('http://localhost:3000/search?address='+location+'&checkin='+checkindate+'&checkout='+checkoutdate).then((response) => {
response.json().then((data) => {
if (data.error) {
messageThirteen.textContent = ''
messageFourteen.textContent = ''
} else {
messageThirteen.textContent = data.hotelStar
messageFourteen.textContent = data.hotelRating
A: I don't know how you get the ratings but you can use the method below to get the value passed to hotel_a.
If the value is already passed in document.querySelector('#message-13').innerHTML; Just remove rating_paragraph = 5;
const ratings = {
hotel_a : 0
}
const button = document.querySelector('#search');
let rating_paragraph = document.querySelector('#message-13').innerHTML;
button.addEventListener('click', function() {
rating_paragraph = 5; //Assign your api call hotel value here as rating_paragragh
ratings.hotel_a = rating_paragraph;
console.log(ratings.hotel_a)
})
<p id="message-13"></p>
<button id="search">Search</button>
| |
doc_23538437
|
I want to hold the takePhotoButton to record the video and then it will be previewed where I preview my current still photos. Your help will really help me continuing my project. Thanks a lot!
import UIKit
import AVFoundation
@available(iOS 10.0, *)
class CameraViewController: UIViewController,AVCaptureVideoDataOutputSampleBufferDelegate {
let photoSettings = AVCapturePhotoSettings()
var audioPlayer = AVAudioPlayer()
var captureSession = AVCaptureSession()
var videoDeviceInput: AVCaptureDeviceInput!
var previewLayer = AVCaptureVideoPreviewLayer()
var frontCamera: Bool = false
var captureDevice:AVCaptureDevice!
var takePhoto = false
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
prepareCamera()
}
func prepareCamera() {
captureSession.sessionPreset = AVCaptureSessionPresetPhoto
if let availableDevices = AVCaptureDeviceDiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: AVMediaTypeVideo, position: .back).devices {
captureDevice = availableDevices.first
beginSession()
}
}
func frontCamera(_ front: Bool){
let devices = AVCaptureDevice.devices()
do{
try captureSession.removeInput(AVCaptureDeviceInput(device:captureDevice!))
}catch{
print("Error")
}
for device in devices!{
if((device as AnyObject).hasMediaType(AVMediaTypeVideo)){
if front{
if (device as AnyObject).position == AVCaptureDevicePosition.front {
captureDevice = device as? AVCaptureDevice
do{
try captureSession.addInput(AVCaptureDeviceInput(device: captureDevice!))
}catch{}
break
}
}else{
if (device as AnyObject).position == AVCaptureDevicePosition.back {
captureDevice = device as? AVCaptureDevice
do{
try captureSession.addInput(AVCaptureDeviceInput(device: captureDevice!))
}catch{}
break
}
}
}
}
}
func beginSession () {
do {
let captureDeviceInput = try AVCaptureDeviceInput(device: captureDevice)
if let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) {
self.previewLayer = previewLayer
containerView.layer.addSublayer(previewLayer as? CALayer ?? CALayer())
self.previewLayer.frame = self.view.layer.frame
self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
previewLayer.connection.videoOrientation = AVCaptureVideoOrientation.portrait
captureSession.startRunning()
let dataOutput = AVCaptureVideoDataOutput()
dataOutput.videoSettings = [(kCVPixelBufferPixelFormatTypeKey as NSString):NSNumber(value:kCVPixelFormatType_32BGRA)]
dataOutput.alwaysDiscardsLateVideoFrames = true
if captureSession.canAddOutput(dataOutput) {
captureSession.addOutput(dataOutput)
photoSettings.isHighResolutionPhotoEnabled = true
photoSettings.isAutoStillImageStabilizationEnabled = true
}
captureSession.commitConfiguration()
let queue = DispatchQueue(label: "com.NightOut.captureQueue")
dataOutput.setSampleBufferDelegate(self, queue: queue)
}
}
@IBAction func takePhoto(_ sender: Any) {
takePhoto = true
photoSettings.isHighResolutionPhotoEnabled = true
photoSettings.isAutoStillImageStabilizationEnabled = true
}
func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, from connection: AVCaptureConnection!) {
if takePhoto {
takePhoto = false
if let image = self.getImageFromSampleBuffer(buffer: sampleBuffer) {
let photoVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "PhotoVC") as! PhotoPreviewViewController
photoVC.takenPhoto = image
DispatchQueue.main.async {
self.present(photoVC, animated: true, completion: {
self.stopCaptureSession()
})
}
}
}
}
func getImageFromSampleBuffer (buffer:CMSampleBuffer) -> UIImage? {
if let pixelBuffer = CMSampleBufferGetImageBuffer(buffer) {
let ciImage = CIImage(cvPixelBuffer: pixelBuffer)
let context = CIContext()
let imageRect = CGRect(x: 0, y: 0, width: CVPixelBufferGetWidth(pixelBuffer), height: CVPixelBufferGetHeight(pixelBuffer))
if let image = context.createCGImage(ciImage, from: imageRect) {
return UIImage(cgImage: image, scale: UIScreen.main.scale, orientation: .leftMirrored)
}
}
return nil
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.captureSession.stopRunning()
}
func stopCaptureSession () {
self.captureSession.stopRunning()
if let inputs = captureSession.inputs as? [AVCaptureDeviceInput] {
for input in inputs {
self.captureSession.removeInput(input)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func DismissButtonAction(_ sender: UIButton) {
UIView.animate(withDuration: 0.1, animations: {
self.DismissButton.transform = CGAffineTransform.identity.scaledBy(x: 0.8, y: 0.8)
}, completion: { (finish) in
UIView.animate(withDuration: 0.1, animations: {
self.DismissButton.transform = CGAffineTransform.identity
})
})
performSegue(withIdentifier: "Segue", sender: nil)
}
}
A: To identify the holding down the button and releasing it, can be done in different ways. The easiest way would be adding a target for UIControlEvents.TouchUpInside and UIControlEvents.TouchDown for capture button like below.
aButton.addTarget(self, action: Selector("holdRelease:"), forControlEvents: UIControlEvents.TouchUpInside);
aButton.addTarget(self, action: Selector("HoldDown:"), forControlEvents: UIControlEvents.TouchDown)
//target functions
func HoldDown(sender:UIButton)
{
// Start recording the video
}
func holdRelease(sender:UIButton)
{
// Stop recording the video
}
There are other ways as well, like adding a long tap gesture recognizer to button or view and start/stop based on recognizer state. More info can be found here in another SO answer UIButton with hold down action and release action
Video Recording
You need to add AVCaptureMovieFileOutput to your capture session and use the method startRecordingToOutputFileURL to start the video recording.
Things to notice
*
*Implement AVCaptureFileOutputRecordingDelegate method to identify the start and didFinish recording
*File path should be meaningful, Which means you should give the correct file path which your app has access.
Have this code inside HoldDown() method to start recording
let videoFileOutput = AVCaptureMovieFileOutput()
self.captureSession?.addOutput(videoFileOutput)
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] as URL
let filePath = documentsURL.appendingPathComponent("tempMovie")
videoFileOutput.startRecording(toOutputFileURL: filePath, recordingDelegate: self)
to stop recording use vidoeFileOutput.stopRecording()
A: You need to use AVCaptureMovieFileOutput. Add AVCaptureMovieFileOutput to a capture session using addOutput(_:)
Starting a Recording
You start recording a QuickTime movie using
startRecording(to:recordingDelegate:). You need to supply a
file-based URL and a delegate. The URL must not identify an existing
file, because the movie file output does not overwrite existing
resources. You must also have permission to write to the specified
location. The delegate must conform to the
AVCaptureFileOutputRecordingDelegate protocol, and must implement the
fileOutput(_:didFinishRecordingTo:from:error:)
method.
See docs for more info.
| |
doc_23538438
|
Does anyone know of any guidelines?
Maybe a place to start would be how to create a many-to-many join that can be traversed from either side in a performant manner, even with vast numbers of rows entities?
A: It seems the phrases that are being used are:
*
*Spread your data out amongst many containers for best performance
*Modeling your data via Entities
*Process your queries in parallel for best performance
*Caching data in the service hosted middle tier
This would imply that we have to start thinking like OO modellers rather than in a relational mind-set. Performance seems to rely on the ability to massively parallelise an object query in a smiliar way to creating a LINQ query that can take advantage of parallelisation.
A: Well, the solution I went for in the end was: stop using SQL Data Services. It's so half-baked that it's barely worth using at the moment anyway.
| |
doc_23538439
|
starting from this string:
"Verticale dall'alto verso il basso, Verticale dal basso verso l'alto"
When sending it with jquery ajax (json), it becomes like this:
"Verticale dall\'alto verso il basso, Verticale dal basso verso l\'alto"
This is the sending code:
$.ajax({
url: ajax_url
,type: 'post'
,dataType:'JSON'
,data: data
Obviously, I don't want to get escaped single quotes. On my database I want to write "'", not "\'".
How to?
A: you could be smart and use a .replace all quotes to apostrophe
var str = "she's good";
var res = str.replace(/'/g, "’");
OR
You could try var json = encodeURIComponent(string)
A: Thanks to @Jintor, the solution was the following:
url: ajax_url
,type: 'post'
,dataType:'JSON'
,data: JSON.parse(JSON.stringify(data).replace(/'/g, "’"))
In my program, data comes to me from other sources in plain json format, then I have to add some other fields to it, and finally pass it to $.ajax. At that point, what I'm doing is to stringify the original object, replace all the straight quotes, than parse it to JSON again and pass it to ajax.
Probably I should also take care of double quotes, but anyway, this is my current solution.
| |
doc_23538440
|
I used this code to catch notFoundHandler error :
$container['notFoundHandler'] = function ($c) {
return function ($request, $response) use ($c) {
return $c['response']
->withStatus(404)
->withHeader('Content-Type', 'application/json')
->write('Page not found');
};
};
But I am able to catch the normal syntax error.
It is showing Warning: fwrite() expects parameter 2 to be string, array given in X-api\controllers\Products.php on line 42
Instead of this message, I want my custom error to handle syntax error reporting.
I used this also,
$container['phpErrorHandler'] = function ($c) {
return function ($request, $response, $exception) use ($c) {
//Format of exception to return
$data = [
'message' => "hello"
];
return $container->get('response')->withStatus($response->getStatus())
->withHeader('Content-Type', 'application/json')
->write(json_encode($data));
};
};
But not working for me.
A: The default error handler can also include detailed error diagnostic information. To enable this you need to set the displayErrorDetails setting to true:
$configuration = [
'settings' => [
'displayErrorDetails' => true,
],
];
$c = new \Slim\Container($configuration);
$app = new \Slim\App($c);
Note this is not appropriate for production applications, since it may reveal some details you would want not to reveal. You can find more in Slim docs.
EDIT
If you need to handle parseErrors, then you need to define phpErrorHandler in your container, just like you did define notFoundHandler.
$container['phpErrorHandler'] = function ($container) {
return function ($request, $response, $error) use ($container) {
return $container['response']
->withStatus(500)
->withHeader('Content-Type', 'text/html')
->write('Something went wrong!');
};
};
Note: this will work with PHP7+ only, because in older versions parseErrors cannot be catched.
A: I have used this short of code in my dependencies.php
$container['errorHandler'] = function ($c) {
return function ($request, $response) use ($c) {
$data = [
'message' => "Syntex error"
];
return $c['response']
->withStatus(200)
->withHeader('Content-Type', 'application/json')
->write(json_encode($data));
};
};
set_error_handler(function ($severity, $message, $file, $line) {
if (!(error_reporting() & $severity)) {
// This error code is not included in error_reporting, so ignore it
return;
}
throw new \ErrorException($message, 0, $severity, $file, $line);
});
Now its working for me.
| |
doc_23538441
|
$('body').on('mouseleave', '.avatar', function(e) {
var to = e.toElement || e.relatedTarget;
if (!$(to).is(".card")) {
setTimeout(function() {
$('.card').remove();
}, 1000);
}
});
The jQuery code must be working like: if not to = e.toElement || e.relatedTarget then remove the .card div. But if you mouseleave the black div (.card) it should stay on there, not remove().
Can anyone help me here ?
DEMO
$(document).ready(function() {
$("body").on("mouseenter", ".avatar", function() {
var offset = $(this).offset();
var posY = offset.top - $(window).scrollTop() + $(this).height();
var posX = offset.left - $(window).scrollLeft();
var available = $(window).width() - posX;
if ($(window).width() > 800) {
$("body").append('<div class="card" style="position: fixed; top: ' + posY + 'px; left:' + posX + 'px"></div>');
}
});
$('body').on('mouseleave', '.avatar', function(e) {
var to = e.toElement || e.relatedTarget;
if (!$(to).is(".card")) {
setTimeout(function() {
$('.card').remove();
}, 1000);
}
});
$('body').on('mouseleave', '.card', function() {
$('.card').remove();
});
});
.container {
position:relative;
width:100%;
max-width:660px;
margin:0px auto;
overflow:hidden;
margin-top:100px;
}
.post {
position:relative;
width:100%;
display:inline-block;
margin-bottom:30px;
}
.avatar {
width:40px;
height:40px;
position:realtive;
border-radius:50%;
overflow:hidden;
}
.avatar img {
width:160%;
}
.card {
width:300px;
padding:100px 0px;
background-color:#000000;
border:1px solid #d8dbdf;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="post">
<div class="avatar" id="1"><img src="https://images.pexels.com/photos/56866/garden-rose-red-pink-56866.jpeg"></div>
</div>
<div class="post">
<div class="avatar" id="2"><img src="https://images.pexels.com/photos/56866/garden-rose-red-pink-56866.jpeg"></div>
</div>
<div class="post">
<div class="avatar" id="3"><img src="https://images.pexels.com/photos/56866/garden-rose-red-pink-56866.jpeg"></div>
</div>
</div>
A: Change this:
JS
Add a cover div to make it fill from the avatar "Y coord".
$("body").append('<div class="cover_card" style="position: fixed; top: ' + posY + 'px; left:' + posX + 'px"><div class="card"></div></div>');
Modify the posY to reposition the cover from the avatar "Y coord".
posY = posY-50;
On mouse leave just remove the cover card container.
$('body').on('mouseleave', '.cover_card', function() {
$(this).remove();
});
CSS
Modify css margin to adjust the posY change.
.card {
width:300px;
padding:100px 0px;
background-color:#000000;
border:1px solid #d8dbdf;
margin-top:60px;
}
https://codepen.io/anon/pen/ejrZMJ
A: Use this part of mouseleave, close card when mouse leave .post
$('body').on('mouseleave', '.post', function() {
$('.card').remove();
});
And change this line in mouseenter, make .card part of .post
$(".post").append('<div class="card" style="position: fixed; top: ' + posY + 'px; left:' + posX + 'px"></div>');
Hope this helps.
| |
doc_23538442
|
test:client:
before_script:
- node -v
- yarn install
cache:
untracked: true
key: client
paths:
- node_modules/
script:
- npm test
build:client:
before_script:
- node -v
- yarn install
cache:
untracked: true
key: client
paths:
- node_modules/
policy: pull
script:
- npm build
I would like to know, with the merge syntax, if I can extract the common part to reuse it efficiently in the context of these two parts.
.node_install_common: &node_install_common
before_script:
- node -v
- yarn install
cache:
untracked: true
key: client
paths:
- node_modules/
But the real question is: at which indent level do I have to merge the block to ensure policy: pull is applied to the cache section. I tried to so that:
test:client:
<<: *node_install_common
script:
- npm test
test:build:
<<: *node_install_common
policy: pull
script:
- npm build
But I get an invalid yaml error. How to indent to get the correct merge behavior?
A: Note that merge keys are not part of the YAML specification and therefore are not guaranteed to work. They are also specified for the obsolete YAML 1.1 version and have not been updated for the current YAML 1.2 version. We intend to explicitly remove merge keys in upcoming YAML 1.3 (and possibly provide a better alternative).
That being said: There is no merge syntax. the merge key << must be placed like a normal key in a mapping. This means that the key must have the same indentation as other keys. So this would be valid:
test:client:
<<: *node_install_common
script:
- npm test
While this is not:
test:build:
<<: *node_install_common
policy: pull
script:
- npm build
Note that compared to your code, I added : to the test:client and test:build lines.
Now merge is specified to place all key-value pairs of the referenced mapping into the current mapping if they do not already exist in it. This means that you can not, as you want to, replace values deeper in the subtree – merge does not support partial replacement of subtrees. However, you can use merge multiple times:
.node_install_common: &node_install_common
before_script:
- node -v
- yarn install
cache: &cache_common
untracked: true
key: client
paths:
- node_modules/
test:client:
<<: *node_install_common
script:
- npm test
test:build:
<<: *node_install_common
cache: # define an own cache mapping instead of letting merge place
# its version here (which could not be modified)
<<: *cache_common # load the common cache content
policy: pull # ... and place your additional key-value pair
script:
- npm build
| |
doc_23538443
|
For now i'm using
m_outputBuffer.erase(
m_outputBuffer.begin(),
m_outputBuffer.begin()+read_samples);
when read_samples samples have been read from the buffer (I have to clear it to free RAM).
But I know erase() is very expensive so what alternative do I have, considering I basically only have to move the pointer to the first element of my buffer and free the beginning ?
A: std::deque appears to be a container that's best suited for something like this. std::deque is a random access container, like std::vector, but has (amortized) constant insertion and deletion complexity at the beginning of the container, unlike std::vector (and at the end of the container as well).
A: Finally I'm still using
m_outputBuffer.erase(
m_outputBuffer.begin(),
m_outputBuffer.begin()+read_samples);
as it's really efficient : the erasing is done in one chunk, and the data left is relocated at the beginning of my vector, thus no pointer changes.
A: Don't use C++ for this. Write it in C, which is of course also a subset of C++.
The buffer consists of a region of memory, and two pointers, one to the start position, one to the end. When data comes in, you add it to the end pointer, until you wrap. When data goes out, you increment the read pointer. You never need to delete or erase data. If the buffer overflows, likely that means something has gone wrong and you need to shut down the system - expanding it will just prolong the crash process.
| |
doc_23538444
|
string dir = Convert.ToString(folderBrowserDialog1.SelectedPath);
DirectoryInfo di = new DirectoryInfo(dir);
int asm = comboBox1.SelectedIndex + 1;
int prt = comboBox2.SelectedIndex + 1;
int drw = comboBox3.SelectedIndex + 1;
var assembliesToBeDeleted = (from a in di.GetFiles("*.asm.*", SearchOption.TopDirectoryOnly)
orderby a.LastWriteTime descending, a.Name ascending
select a).ToArray();
foreach (var assembly in assembliesToBeDeleted)
{
//assembly.Delete();
}
The list I end up with looks like this:
scumbox_ga.asm.338
scumbox_ga.asm.337
manway_nozzle.asm.3
inputcheck.asm.452
inputcheck.asm.451
inputcheck.asm.450
inputcheck.asm.449
inputcheck.asm.448
inputcheck.asm.447
cover_w_holes.asm.10
cls_halftank.asm.426
cls_halftank.asm.425
cls_half_final.asm.423
cls_half_final.asm.422
cls_half_final.asm.421
cls_half_final.asm.420
cls_half_final.asm.419
cls_half_final.asm.418
cls_half_final.asm.417
cls_half_final.asm.416
cls_half_final.asm.415
cls_half_final.asm.414
cls_half_final.asm.413
cls_half_final.asm.412
cls_half_final.asm.411
cls_half_final.asm.410
cls_half_final.asm.409
I hope this clarifies the question.
A: I think the method you are looking for is:
File.Delete(assembly);
Defined: here
So your code would end up looking like:
string dir = Convert.ToString(folderBrowserDialog1.SelectedPath);
DirectoryInfo di = new DirectoryInfo(dir);
int asm = comboBox1.SelectedIndex + 1;
int prt = comboBox2.SelectedIndex + 1;
int drw = comboBox3.SelectedIndex + 1;
var assembliesToBeDeleted = (from a in di.GetFiles("*.asm.*", SearchOption.TopDirectoryOnly)
orderby a.LastWriteTime descending, a.Name ascending
select a).ToArray();
foreach (var assembly in assembliesToBeDeleted)
{
File.Delete(assembly);
Console.WriteLine(assembly);
}
A: Assuming that the extension added by your backup procedure is padded to be a three character extension padding the missing numbers with zero
So having a set of files with this pattern
"ABCD.001"
"ABCD.002"
"ABCD.003"
"ABCD.004"
"ABCD.005"
you want to keep the files 003, 004, 005 then you could change your code to
DirectoryInfo di = new DirectoryInfo(dir);
// Get the distinct base file names of every file in that directory
// So for a bunch of files 'Name.XX1','Name.XX3','Name.XX3' we
// get an IEnumerable of only the Name part
var files = di.GetFiles("*.*", SearchOption.TopDirectoryOnly)
.Select(x => Path.GetFileNameWithoutExtension(x.Name)).Distinct();
// Now loop over each base file name
foreach (string file in files)
{
// Get the files with that base name in descending order but skipping the first 3
var toDelete = di.GetFiles(file + ".*").OrderByDescending(d => d.Name).Skip(3);
// Delete if any file is in the IEnumerable returned
foreach(FileInfo fileToDelete in toDelete)
fileToDelete.Delete();
}
If your extension are not padded with three characters then you should revert to use the LastWriteTime of the FileInfo
var toDelete = di.GetFiles(file + ".*").OrderByDescending(d => d.LastWriteTime).Skip(3);
A: I would create a filename object to hold the three parts.
class AssemblyFilename
{
public string Name { get; set; }
public string Part { get; set; }
public int Version { get; set; }
}
Create a constructor to parse out the parts
public AssemblyFilename(string filename) { /*...*/ }
and then you can use LINQ
var fileGroups = assemblyFilenames.GroupBy(af => af.Name);
foreach(var group in fileGroups)
{
foreach(var filenameToDelete in group.OrderByDescending(g => g.Version).Skip(3))
{
// delete
}
}
| |
doc_23538445
|
I have written an application using Python 2.6 and Django 1.2.1.
I would like to deploy this application on a system that does not have Python 2.6 or Django installed. The system itself doesn't have many things installed - sqlite3, pysqlite2, gcc, etc. The system does have Python 2.4.3, however.
What would be the most sane way to create RPMs of Python 2.6, Django, and my application itself (a standard Django app) so that each can be installed separately to allow for upgrades of different components?
I don't know much about creating source RPMs but I suspect that is information readily available. If there are any especially good resources for creating source RPMs, I would appreciate them too.
The system is ESX 4 Update 1, if it matters.
Thanks!
UPDATE:
It also never occurred to me that distributing Python eggs or even using setup.py is a viable solution to content distribution. I would be interested in hearing about that too.
A: On top of all the normal issues encountered when packaging Python code, Django projects have a few other issues that need to be handled:
*
*Playing nice with system paths
*Playing nice with system facilities
*Handling translations
*Randomizing the secret key
I had to solve these issues for packaging Transifex, and I recommend you investigate the various bits that have put in place in order to make it work:
*
*Install under /usr/share/<projectname>
*Use execfile() to load settings from /etc/<projectname>
*The huge translation-handling runaround
*Replacement of the secret key in the post-install script
*All the other bloody changes and fudges that were required
A: Python packages are normally distributed with setuptools/distribute. Generally you can install every python package (and it's dependencies) with easy_install <package_name> (optionally with a specific version number). I would recommend you to use setuptools as our primary distribution method, because:
*
*it works on all platforms
*is the preferred way for Python packages in general
*.rpm or .deb install scripts can reuse parts of it too
*you can install this packages inside a virtualenv without the need of root privileges, conflict-free of the rest of the installed web applications on the server
A good resource for you to read is Deploying with Distribute. It focuses on Flask (another web framework), but simply replacing "Flask" with "Django" will do the trick :)
Another python tool which is great for distributing and deploying things is fabric, which you can use in addition to distribute (or without it, however you want). With fabric you can for example, bootstrap and install your application (inclusive dependencies) on N servers at once, manage several development, testing and production servers and update them all concurrently with a single command.
This article might help you to get started with Fabric: Deploying with Fabric
And additionally I would also recommend you to publish your repository (or mirror an existing one) on github or bitbucket for people who want to get the latest sources manually and install your application with python setup.py install afterwards. The setup.py install script is part of distribute which I've mentioned before.
A: Refer to chapter 5 of the Python documentation. It will show how to deal with the bdist Python utility. With it, you'll be able to generate packages (or, how it says, "built distribution") of several types, includding RPM.
A: There are already RPM's of python 2.6 and django available - so those at least are (relatively) easy to grab and install via RPM. FOr creating an RPM for your project, there's a write up on some of the details using Distutils, that goes into the details of what you need in a spec file and what you invoke to make it happen.
There's also a note about creating RPM's from python on StackOverflow at Creating Python RPM that has a touch of detail as well.
From experience, packaging up python itself as an RPM is the trickiest of the critters, so taking advantage of what's already there is something I'd definitely recommend. For a few programs where I've seen this done, we have a Makefile (yeah, old school) run the setup.py bdist_rpm command on a continuous integration server, making the RPM available as the result of that build and immediately available on the CI server.
A: I've written up a blog post on how to use setuptools and it's bdist_rpm command to create the rpm for you. So indeed, use setuptools, but indeed, distribute your app as an rpm.
There's a few catches and weird under documented things in setuptools you can use to eventually end up in a nice workflow.
The key is you need a post install script that runs your migrations and collects your static files, that gets run after the rpm is installed
export DJANGO_SETTINGS_MODULE=accountpage.settings
mkdir -p /var/www/django/static && chown apache:apache /var/www/django/static
runuser -m apache -c 'echo "yes" | django-admin collectstatic'
django-admin migrate
service httpd restart
and you can tell setuptools to add this to the spec file before it creates the rpm by giving this option in the setup call:
options = {'bdist_rpm':{'post_install' : 'bdist_rpm_post_install.sh'}},
See the link above for a full working setup.py script, post install hook, and a testsuite that works with python setup.py test that will install all your dependencies locally, and run the django tests.
To have the rpm also automatically install it's dependencies, create a setup.cfg file which tells bdist_rpm about it's dependencies
[bdist_rpm]
requires = python >= 2.7
django >= 1.8
httpd
Django-Select2 >= 4.3.1
django-easy-select2
django-model-utils
pytz
django-oauth-toolkit
| |
doc_23538446
|
I recently started learning JWT and found that it is a 3 part token issued by server to client for authenticity along with passing data like user-scope/roles/permission etc in forms of claims.
My question however are:
*
*The claim part of token still is base64 encoded string which can easily be parsed using atob/btoa. So is the transmission really secure ? What is the real gain here ?
*There are multiple articles on generating and sending token to UI. However, almost no good articles on what UI does exactly with it. Is it a common practice to decode the token using atob and use the content within it ? Or is there a different way of validating and retrieving data from it.
*Is it really secure to transmit data via headers. I mean is it safe against things like MITM, XSS etc.
I would really appreciate some efforts from the expert in resolving these queries ?
A: For question #1, the gain is not on the client side. If you can't trust what you received from the server, you can't trust it no matter how it's obfuscated/encoded/encrypted/. The point is that you send this token back to the server. On the server, a quick check will tell that this token is legitimate. Imagine a complex login scenario, where MegaCorp looks up permissions for the user across 739 subsystems, combines them into a single payload, and then doesn't have to do that again on further requests. When the client sends the token back, it validates that you are properly logged in and uses the permissions to do further processing.
For #2, you can put whatever you like into this payload, so long as it isn't meant to be too secure. I mostly use it for basic user info and for application permissions. So I can paint the user's name and offer a link to the specific user settings page. I can check whether the user has access to an administrative page or whatever permissions I need to check. While a malicious user can fool the system by manipulating that data client-side, and can therefore, say, see the admin page, when the call goes back to the server to get the data for that page, the token is either illegitimate and the request will be rejected, or it won't contain the proper permissions and, again, it will be rejected.
I don't really know enough about security to attempt an answer to #3.
Some people use JWT only for isLoggedIn, which is fine, but I think misses some useful possibilities. Used properly, this can be the single mechanism to capture user information for both the client and the server. But the important side to my mind is the server. This can be done in many ways on the client. But it's hard to find something better for the server.
A:
The claim part of token still is base64 encoded string which can
easily be parsed using atob/btoa. So is the transmission really secure
? What is the real gain here ?
The transmission is secure (cannot be read/modified by others) if you send the token via https. JWT contains 2 important parts: a payload and a verify signature.
The signature can be produced and verified only by one person and prove that the payload is legit for that person.
Here is a simple use case:
*
*Client send is credential to the Auth server to receive the right to publish something
*The server receives the credential and valid them through a complex process then send back to the client a JWT saying: {I give Client the right to publish signed the Auths erver}
*The Client store locally the token
*When the client needs to publish something he sends the JWT and is work to server B which share the signing key with Auth server.
*Server B verify easily the token and publish the work of the client
Another example of usage is authentication via mail only.
There are multiple articles on generating and sending token to UI.
However, almost no good articles on what UI does exactly with it. Is
it a common practice to decode the token using atob and use the
content within it ? Or is there a different way of validating and
retrieving data from it.
In general, the client wants to obtain a token from some server to send it back later. The client cannot verify the signature because he does not share the private key with the server, he is not a source of trust.
Is it really secure to transmit data via headers. I mean is it safe
against things like MITM, XSS etc.
Using https it is safe: Are HTTPS headers encrypted?
| |
doc_23538447
|
I went through https://learn.microsoft.com/en-us/cpp/c-runtime-library/file-permission-constants?view=vs-2019. _S_IREAD seem to be one option. But it just says "Reading permitted". Not sure whether it will full fill my requirement
| |
doc_23538448
|
In chrome, session id's change for every page, only if I use rewrite rules. When using rewrite rules the cookies path oddly changes to /pages_name/ instead of remaining /.
In opera, session id's change even if I refresh the page. So does in IE.
In both cases the cookies are accepted by the browsers.
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-zA-Z]+)/([a-zA-Z0-9]+)/([a-zA-Z0-9]+)/?$ index.php?page=$1&info1=$2&info2=$3 [L]
RewriteRule ^([a-zA-Z]+)/([a-zA-Z0-9]+)/?$ index.php?page=$1&info1=$2 [L]
RewriteRule ^([a-zA-Z]+)/?$ index.php?page=$1 [L]
After searching i came across some "solutions" none of which worked
Session save path is working, files are being writen. Using default session handler.
Setting session.cookie_path to /
Setting session.cookie_lifetime to other then 0
I am not using session_regenerate_id
session_start( ); is the first line of code on all pages
If more information is needed I will update this post, thank you.
On further research it turns out to be an issue with the RewriteRules, no idea how to fix it yet.
Also the cookies from session_start( ) are set to localhost/home/ as if, it was a folder yet it's a variable localhost/index.php?page=home. Because of this every page gets its own session id, any ideas for a fix?
A: Instead of starting a new session by session_start();, first check if browser already sent current session_id.
if (isset($_POST['session_id'])) {
$_COOKIE['PHPSESSID'] = $_POST['session_id'];
session_start();
} else {
session_start();
}
If that does not work, then your PHP and/or Apache configuration seems to be broken.
Why don't you try default configs?
| |
doc_23538449
|
I have two buttons using the same class but the color of the text is different in each button
screenshot
.button {
margin: 10px;
padding-top: 10px;
color: black;
background-color: yellow;
border-radius: 10px;
}
.button a:link,
a:visited {
color: #000;
}
.button a:hover {
background-color: orange;
color: #000;
}
<div>
<button class="button"><a href="https://twitter.com/*hidden*">Find me on <img width="50" alt="Twitter" src="images/twitter.png" /></a></button>
<button class="button"><a href="https://www.facebook.com/*hidden*">Find me on <img width="50" alt="Twitter" src="images/twitter.png" /></a></button>
</div>
The Twitter button "Find me on" text is black as designed, but the Facebook button the "Find me on" text is white. What am I missing here? (I have tried it with just links, no HTML button, the color difference remains.)
A: You are referring a:visited but not .button a:visited
Therefor I „think“ the different color you see is the browser visited color and not what you defined.
A: Okay, found the stupid mistake. I noticed on inspection that the link color was being inherited from my footer. I apparently managed to quote out a closing div at the bottom of my page and somehow that I still don't understand the css for my footer links was overriding my button class. That makes sense to me, but I still can't figure why it only affected one button. With the div properly closed everything is good.
| |
doc_23538450
|
ALTER PROCEDURE [dbo].[GetStudentRegistrationDetails]
@TotalDataCount INT OUT,
@currentPage INT = 1,
@pageSize INT = 0,
@Username NVARCHAR(500) = NULL,
@Userstatus INT = NULL,
@Userregisteredby INT = NULL
AS
BEGIN
SET NOCOUNT ON;
SELECT
@TotalDataCount = COUNT (*)
FROM VW_UserDetails
WHERE RoleId=2
AND USERFULLNAME LIKE ISNULL(RTRIM(@UserName) + '%',USERFULLNAME)
AND CAST(ISNULL(Status,0) AS INT) = ISNULL(@Userstatus,Status)
AND CreatedBy = CASE
WHEN @Userregisteredby = 0 THEN 0
ELSE CreatedBy
END
For Status my table has to values either 1 or NULL.
AND CAST(ISNULL(Status,0) AS INT) = ISNULL(@Userstatus,Status)
With this line of code, I am able to get values for 1 if I send 1 from my front end as parameter & for null I am able to get all null if I send 0 from my front end as parameter.
Actually I am sending 0 or 1 as parameter from RadioButtonList value fields. But I want to get also both NULL & 1 together also with a single parameter from from front end.
What should I send from front end or what correction do I need o get both ?
Guide me please.
A: Set the parameter to 2 and use or @Userstatus = 2.
| |
doc_23538451
|
#main {
height: 90px;
width: 400px;
overflow-y: auto;
}
.wrapper-dropdown {
text-transform: uppercase;
letter-spacing: .08em;
font-size: 12px;
position: relative;
width: 200px;
padding: 12px 15px;
background: #fff;
border-radius: 6px;
border: 1px solid #d9e2f6;
cursor: pointer;
outline: none;
-webkit-transition: all .3s ease-out;
-moz-transition: all .3s ease-out;
-o-transition: all .3s ease-out;
transition: all .3s ease-out;
}
.wrapper-dropdown .dropdown {
position: absolute;
top: 100%;
left: -1px;
right: -1px;
background: #fff;
border-radius: 0 0 5px 5px;
border: 1px solid #d9e2f6;
border-top: none;
border-bottom: none;
list-style: none;
padding: 0 5px;
-webkit-transition: all .3s ease-out;
-moz-transition: all .3s ease-out;
-o-transition: all .3s ease-out;
transition: all .3s ease-out;
max-height: 0;
overflow: hidden;
margin: 0;
z-index: 5;
}
.wrapper-dropdown .dropdown li {
padding: 0 10px;
width: 100%;
}
.wrapper-dropdown .dropdown li a {
display: block;
text-decoration: none;
color: #6a759e;
padding: 15px 0;
transition: all .3s ease-out;
border-bottom: 1px solid #d9e2f6;
margin-right: 20px;
}
.wrapper-dropdown.active .dropdown {
-webkit-box-shadow: 0 10px 20px 0 rgba(217, 226, 246, .8);
-moz-box-shadow: 0 10px 20px 0 rgba(217, 226, 246, .8);
box-shadow: 0 10px 20px 0 rgba(217, 226, 246, .8);
max-height: 400px;
}
<div id="main">
CLICK OPTION 1 TO SHOW LIST
<div class="wrapper-dropdown">
<span class="selectedtext">Option1</span>
<ul class="dropdown">
<li><a href="#" val="Option1">Option1</a></li>
<li><a href="#" val="Option2">Option2</a></li>
<li><a href="#" val="Option3">Option3</a></li>
</ul>
</div>
</div>
I'm trying to get the absolute positioned element (which is the list of options) to appear outside of the bounds of the main container which has overflow-y set.
I understand why this happening this due to this answer.
But am simply asking if anyone has any insights/tips/suggestions on a way to get around this or if it's generally not possible without moving the dropdown items outside of the container with the overflow set.
My example is here
| |
doc_23538452
|
So if I run sails generate api user I want a user model accessible via a users route.
Thanks.
A: Nevermind, just found it in config/blueprint.js under the setting pluralize.
| |
doc_23538453
|
<div id="register-box">
<div id="register-box-inner">
<h2>Register</h2>
<form action="/register" method="post" id="register-form">
<p><label for="username">Username:</label><input type="text" name="username"></p>
<p><label for="password">Password:</label><input type="password" name="password"></p>
<p><label for="email">E-mail:</label><input type="text" name="email"></p>
<p><input type="submit" value="Register" class="register"></p>
</form>
</div>
</div>
and my Javascript code thus far:
$('#register-form').submit(function(e){
e.preventDefault();
alert("hi");
});
Problem is, the form still goes through. I wanted to submit the form using AJAX but with a fallback for users who don't have Javascript enabled. No errors pop up in the Javascript console, either.
A: Try
$("form").live("submit", function() {
alert("hi");
return false;
});
A: Try returning false from the handler.
$('#register-form').submit(function(e){
e.preventDefault();
alert("hi");
return false;
});
A: Try:
<p><input type="submit" value="Register" class="register" onclick="submit(); return false;"></p>
| |
doc_23538454
|
For example my word list can be comprised of this:
good
bad
cupid
banana
apple
Then I want to compare each of these individual words with my html/text file which may be like this:
Sometimes I travel to the good places that are good, and never the bad places that are bad. For example I want to visit the heavens and meet a cupid eating an apple. Perhaps I will see mythological creatures eating other fruits like apples, bananas, and other good fruits.
I wish my output to generate how many times each occurrence of the listed words happen. I have a way to do this with a for-loop but I really wish to avoid the for-loop since it will take forever since my real words list is about 10000 words long.
So in this case my output should be (I think) 9 since it counts total occurrences of a word on that list.
Also if there is a way to display which words where matched and how many occurrences, that would be even more helpful.
A: $words = '...'; // fill these with your stuff
$text = '...';
// split the word list
$expr = explode("\n", $words);
// sanitize the words contained
$expr = array_map(function ($v) { return preg_quote(trim($v)); }, $expr);
// prepare words for use in regex
$expr = '/('. implode('|', $expr) . ')/i'; // remove "i" for case sensitiviy
// matex prepared words against provided text
preg_match_all($expr, $text, $matches);
// calculate result
echo 'Count: ' . count($matches[1]);
A: Try preg_match_all
$text = 'Sometimes I travel to the good places that are good, and never the bad places that are bad. For example I want to visit the heavens and meet a cupid eating an apple. Perhaps I will see mythological creatures eating other fruits like apples, bananas, and other good fruits.';
preg_match_all('/good|bad|cupid|banana|apple/', $text, $matches);
// ECHO OUT NUMBER OF MATCHES
echo sizeof($matches[0]); // 9
// TO SHOW ALL MATCHES
print_r( $matches );
| |
doc_23538455
|
Secret name: user-list
Below is what's inside of user-list:
USER_1: 10 bytes
With my limited knowledge on k8s, it looks like I can pull the values of USER_1 into values.yaml this way:
env:
- name: SECRET_USERNAME_1
valueFrom:
secretKeyRef:
name: user-list
key: USER_1
My question is:
Is it possible to get USER_1 value into configmap.yaml ?
My configmap looks like below:
apiVersion: v1
kind: ConfigMap
metadata:
name: user-test
data:
user.properties: |
connector.name: {{ USER_1 }} ---> I want to be able to pull USER_1 value here
postgresql.array-mapping=AS_JSON
decimal-default-scale=20
decimal-mapping=ALLOW_OVERFLOW
decimal-rounding-mode=HALF_DOWN
A: Kind of. You can't pull values per se but you can can grab data via the lookup function. However this is a very slippery slope to unmaintainable code.
More likely what you want is the ConfigMapSecrets operator which allows basic runtime templating using CM and Secret data.
| |
doc_23538456
|
I've looked through the code and changed a ton of things to no avail.
A: The current .wsite-menu-wrap class has top:80px which is causing the gap between the menu and the submenu.
Changing it to top:0px will remove this gap
A: Remove margin-top from header and change
.page-content-wrapper {
height: 100%;
position: relative;
}
to
.page-content-wrapper {
height: 100%;
width:100%;
position: absolute;
}
Maybe these modifications can break something else, let me know
| |
doc_23538457
|
<test>
<p>Some text (page 24)</p>
<p>Some text (Page 24)</p>
<p>there is some text here (page 24) and here (page 25)</p>
<p>some text (pages 24, 7, 9)</p>
</test>
and I want to use some regex to wrap all page text snippets into a page_ref tag, so result would look like this :
<test>
<p>Some text <page_ref>(page 24)</page_ref></p>
<p>Some text <page_ref>(Page 24)</page_ref></p>
<p>there is some text here <page_ref>(page 24)</page_ref> and here <page_ref>(page 25)</page_ref></p>
<p>some text <page_ref>(pages 24, 7, 9)</page_ref></p>
</test>
my code looks as follows
<xsl:template match="text()">
<xsl:analyze-string select="." regex="\(([pP]age).*\)">
<xsl:matching-substring>
<page_ref><xsl:value-of select="."/></page_ref>
</xsl:matching-substring>
<xsl:non-matching-substring>
<xsl:value-of select="."/>
</xsl:non-matching-substring>
</xsl:analyze-string>
</xsl:template>
but it fails on my 3d p tag, as it produces
<p>there is some text here <page_ref>(page 24) and here (page 25)</page_ref></p>
So if someone is able to point me the error I'll be a happy guy.
Thanks in advance !
A: Try this regular expression:
\(pages?\s+\d+(,\s*\d+)*\)
PS: This was tested using .NET regular expressions, but it should work with XSLT as well
A: You could try matching any character except for ), up to the next ).
"\(([pP]age)[^)]*\)"
| |
doc_23538458
|
To import use a PHP script with the following statement:
exec("mysql -u Myuser -pMySrtongPassword -e \"USE MyDatabase;
TRUNCATE MyTable;
LOAD DATA LOCAL INFILE '/var/www/html/upload/file.csv' IGNORE INTO TABLE MyTable FIELDS TERMINATED BY ';' LINES TERMINATED BY '\n' IGNORE 1 LINES ;\"; ");
This works well for most of the .csv files that I need to import. However, I have some .csv files that have the following format:
"field1"; "field2"; ..... "fieldN";
They are separated by semicolons and delimited by quotes.
Does anyone have any ideas on how to import these files correctly?
A: Add a OPTIONALLY ENCLOSED BY '\"' to the `LOAD DATA
TRUNCATE MyTable;
LOAD DATA LOCAL INFILE '/var/www/html/upload/file.csv' IGNORE INTO TABLE MyTable FIELDS TERMINATED BY ';' OPTIONALLY ENCLOSED BY '\"' LINES TERMINATED BY '\n' IGNORE 1 LINES ;
| |
doc_23538459
|
HTML
<div class="filter-menu-toggle">
Sort <span class="menu-toggle-name">End Date</span><i class="icon-arrow_drop_down"></i>
</div>
<div id="campaign-sort-filter">
<div class="filter-menu-dropdown menu-pos-2">
<ul>
<li class="filter-menu-item">
<a href="#" class="filter-menu-link">End Date</a>
</li>
<li class="filter-menu-item">
<a href="#" class="filter-menu-link">Start Date</a>
</li>
</ul>
</div>
</div>
jQuery
var menuwashandled=false;
jQuery('#campaign-sort-filter').on('click', function(){
if (jQuery('#campaign-sort-filter .filter-menu-dropdown').css('display') == 'none')
jQuery('#campaign-sort-filter .filter-menu-dropdown').fadeIn(100);
else
jQuery('#campaign-sort-filter .filter-menu-dropdown').fadeOut(100);
menuwashandled = '#campaign-sort-filter';
});
/* catch global click event and hide all menues expect for the one that was handled if such exists */
jQuery('html').click(function() {
if (menuwashandled != '#campaign-sort-filter')
jQuery('#campaign-sort-filter .filter-menu-dropdown').fadeOut(100);
menuwashandled = false;
});
Is there a better way of doing this that is more mobile friendly? Or just better in general?
| |
doc_23538460
|
SMS's have a bunch of limitations and regulations in different countries and TOTP happens to be so not friendly to non-technical users.
I understand I can have custom flow but we would like to continue using Amplify for the login. What's the most straightforward way to achieve this in the cognito service?
A: There isn't an email solution out-of-box, but the setup is relatively straightforward using custom flow, lambda triggers and amazon SES. You can follow this tutorial on the AWS blog: https://aws.amazon.com/blogs/mobile/extending-amazon-cognito-with-email-otp-for-2fa-using-amazon-ses/
A: No, you can't be using the Amplify
import { Auth } from 'aws-amplify';
##You can select preferred mfa type, for example:
##Select TOTP as preferred
Auth.setPreferredMFA(user, 'TOTP').then((data) => {
console.log(data);
// ...
}).catch(e => {});
// Select SMS as preferred
Auth.setPreferredMFA(user, 'SMS');
// Select no-mfa
Auth.setPreferredMFA(user, 'NOMFA');
| |
doc_23538461
|
(define (pred value lst)
...)
(pred 3 (list 8 3 7 3)) should return 8
(pred 2 (list 1 2 2 2 2)) should return 1
Note that I only want to return the "first" occurrence of a predecessor, therefore in this first example the number 7 does not have to be returned.
I'm currently stuck because I "loose information" about the predecessor value, once I call a recursion by (pred value (rest lst)) ... I don't know to "store" this information in e.g. a list.
Thanks for any help! I'm already trying for hours...
A: So here is how to fix this. You make a helper that takes additional arguments. One of those can be the previous element. eg.
(define (iterate-pred value last lst)
...)
(pred 3 '(1 2 3 4)) ; ==>
(iterate-pred 3 1 '(2 3 4)) ; ==>
(iterate-pred 3 2 '(3 4)) ; ==>
; ==> 2
So to update the variables you just call the same procedure again with the new values. It is just as easy as iterating the list to begin with, which uses the same strategy.
You can implement these as internal procedure either with define/letrec or you can use named let. Then you can omit value in the helper since you have access to it through the scope.
Good luck!
| |
doc_23538462
|
sapie_columns = sapie_df_working.columns.tolist()
sapie_columns = [sapie_columns[-1]] + sapie_columns[3:-1]
sapie_df_working = sapie_df_working[sapie_columns]
but it turns my dataframe (initially with 32 columns) into one with 164 columns. I think this is because a number of the existing columns have the same column name (i.e., "90% CI Lower Bound"). I'm curious about why is is happening and how I can rearrange and edit my dataframe's columns as I want to.
For reference, here is a snippet of my dataframe:
# sapie_df_working
2 State FIPS Code County FIPS Code Postal Code Name Poverty Estimate, All Ages 90% CI Lower Bound 90% CI Upper Bound Poverty Percent, All Ages 90% CI Lower Bound 90% CI Upper Bound ... 90% CI Upper Bound Median Household Income 90% CI Lower Bound 90% CI Upper Bound Poverty Estimate, Age 0-4 90% CI Lower Bound 90% CI Upper Bound Poverty Percent, Age 0-4 90% CI Lower Bound 90% CI Upper Bound
3 00 000 US United States 38371394 38309115 38433673 11.9 11.9 11.9 ... 14.9 67340 67251 67429 3146325 3133736 3158914 16.8 16.7 16.9
4 01 000 AL Alabama 714568 695249 733887 14.9 14.5 15.3 ... 20.7 53958 53013 54903 66169 61541 70797 23.3 21.7 24.9
5 01 001 AL Autauga County 6242 4930 7554 11.2 8.8 13.6 ... 19.3 67565 59132 75998 . . . . . .
6 01 003 AL Baldwin County 20189 15535 24843 8.9 6.8 11 ... 16.1 71135 66540 75730 . . . . . .
7 01 005 AL Barbour County 5548 4210 6886 25.5 19.3 31.7 ... 47.2 38866 33510 44222 . . . . . .
A: df = df[specific_column_names] is indeed producing this result because of duplicate column names. Filtering with column names in this case is tricky, as it's unclear exactly which column is being referred to.
In case of duplicate column names I would instead use column indices to filter the DataFrame.
Let's look at an example:
>>> import pandas as pd
>>> mock_data = [[11.29, 33.1283, -1.219, -33.11, 930.1, 33.91, 0.1213, 0.134], [9.0, 99.101, 9381.0, -940.11, 55.41, -941.1, -1.3913, 1933.1], [-192.1, 0.123, 0.1243, 0.213, 751.1, 991.1, -1.333, 9481.1]]
>>> mock_columns = ['a', 'b', 'c', 'a', 'd', 'b', 'g', 'a']
>>> df = pd.DataFrame(columns=mock_columns, data=mock_data)
>>> df
a b c a d b g a
0 11.29 33.1283 -1.2190 -33.110 930.10 33.91 0.1213 0.134
1 9.00 99.1010 9381.0000 -940.110 55.41 -941.10 -1.3913 1933.100
2 -192.10 0.1230 0.1243 0.213 751.10 991.10 -1.3330 9481.100
>>> columns = df.columns.tolist()
>>> filtered_column_indices = [len(columns) - 1] + list(range(3, len(columns) - 1))
>>> df.iloc[:, filtered_column_indices]
a a d b g
0 0.134 -33.110 930.10 33.91 0.1213
1 1933.100 -940.110 55.41 -941.10 -1.3913
2 9481.100 0.213 751.10 991.10 -1.3330
In the example, instead of extracting column names with [sapie_columns[-1]] + sapie_columns[3:-1], I extracted the equivalent indices and used that to filter the DataFrame using iloc.
| |
doc_23538463
|
I tried the reverse() method of the InternetAddress class from the dart:io package, but this only gets me the IP address back.
Example:
InternetAddress(ip).reverse().then((value) => print(value));
Is there another package or something I can use, to scan the local network of the app and get the IP address and the hostname back?
A: OK, I got it working and want to share my solution.
I used the network_info_plus package and the dart:io package.
import 'dart:io';
import 'package:network_info_plus/network_info_plus.dart';
Future<void> scanNetwork() async {
await (NetworkInfo().getWifiIP()).then(
(ip) async {
final String subnet = ip!.substring(0, ip.lastIndexOf('.'));
const port = 22;
for (var i = 0; i < 256; i++) {
String ip = '$subnet.$i';
await Socket.connect(ip, port, timeout: Duration(milliseconds: 50))
.then((socket) async {
await InternetAddress(socket.address.address)
.reverse()
.then((value) {
print(value.host);
print(socket.address.address);
}).catchError((error) {
print(socket.address.address);
print('Error: $error');
});
socket.destroy();
}).catchError((error) => null);
}
},
);
print('Done');
}
I'm "scanning" the local network by trying to connect to a given ip and port. If that works, I found a device, I'm looking for. In that cause I also try to get the hostname by using the "reverse()" method.
I have tested it on several iOS and Android devices and it works fine with no errors, so I think its a proper solution.
A: This does not work on the desktop as I think it is not implemented.
Only for iOS and Android.
| |
doc_23538464
|
Every so often we get an exception when trying to do an add/edit/update:
(3260) Could not update; currently
locked by user 'admin' on machine
'abc123'.
I am confident that the problem is related to record locking in the database.
We're using CDaoRecordset to access the data. From reading docs it appears that the default is to optimistically lock the database page that the record is in. If another process tries to edit/update a record in the same page they get the error we're seeing.
Moving to SQL Server isn't an option at this point - it's not a simple change because of how things are structured.
I'm wondering if I can make the records in the affected tables large enough so that only one record fits into each 2k data page. If I make each record 1100 bytes long then each record should get its own page, solving the locking problem. I know it will use up more disk space however that is not a problem at the moment as the affected tables are pretty low volume ones.
Would that work? Can a record in Access 2000 be split across two pages?
A: Bloating records just to avoid a locking conflict is not a very practical method. For one thing, Access databases are limited to 2 Gb. That includes system tables. I suggest you trap the error and try the action again. Not knowing C++, I can't give you the code to do that but I assume you already know how to do that.
A: From viewing differences in behavior batween Access 97/Jet 3.5 and Access 2000/Jet 4.0 I believe that new records in Access 2000 are already placed in their own pages. I noticed a lot more "bloating" in Access 2000 database files compared to Access 97 files.
Thus I suspect your problem is more to do with basic table and index locking rather than record locking. It can take a while, that is milliseconds, to update all the indexes. As Bill states retry the operation. I'd suggest adding a delay of say 10 or 50 milliseconds. And limit the retries to say 10.
A: A random Autonumber PK may allow you to have increased concurrency, since Jet/ACE tables are stored clustered on the PK (i.e., in PK order). With a random Autonumber, the compacted table will stored in an essentially random order, rather than with the older records at the top and the newer records clustered together at the end.
However, records added after a compact will be in temporary fragmented data pages instead of in clustered PK order, so I don't actually know if this enhances concurrency in a practical sense. It may be only theoretical (i.e., you'd have to compact after every record was added).
| |
doc_23538465
|
Turns out it was the querying that is the problem. Well, not on my side, at least not that I think so. This problem has been bugging me for many hours now. Unfortunately, it something I don't know how to fix.
Please check this code:
public function get_calendar_content($y,$m){
$query = $this->db->query("SELECT * from events WHERE event_date LIKE '$y-$m%'");
$content=array();
foreach($query->result() as $q){
$content[substr($q->event_date,8,2)]=$q->event_details;
}
return $content;
}
This function ignores whatever I supply for the $m, or the month. It only cares about the year. Plus, when I tried selecting all data from the events table instead of having a where clause, it still only returns the entries or data from the events table which is is dated in the month of August.
When I tried writing the where clause explicitly to event_date LIKE '2013-09%', it wouldn't return any data at all. I don't understand what's going on. For some unknown reason, the function would only return data from August. I already tried writing the query on phpMyAdmin, and it works just how it's supposed to do. It only produces irregularity in my app. What could my problem be?
Edit: I'm now using multidimensional array. It fixed the confusion about multiple events, but still does not return data from other months.
public function get_calendar_content($y,$m){
$query = $this->db->query("SELECT * from events WHERE event_date LIKE '$y-$m%'");
$content=array();
foreach($query->result() as $q){
$content[substr($q->event_date,8,2)][]=$q->event_details;
}
return $content;
}
A: The problem is in how you're building the return array:
substr($q->event_date,8,2) will get the day for each event (1-31) and you're using it as your key, but an array can't have repeating keys, so only the last value will be kept.
The solution is to change the key values for your array so they don't repeat
| |
doc_23538466
|
Currently, I just try to connect via the local IP and then try the external if it fails... but the timeout takes a bit too long and I was wondering if there's a way to find out what domain the machine is connected to before trying.
Edit: Patrick> Essentially, the app runs on a tablet pc that is connected to the local network a couple of times a day. It's roughly equal between the number of times it connects over the network and the times that it connects locally.
All machines have a domain account when they are connected to the network (and have domain accounts with a naming convention of like "LOCTabletx" where x is a number given to the machine when it's ghosted.
What I'm looking for is a fast way to see if the machine is connected on our local network or the internet. Using Environment.UserDomainName gets me LOCTabletx and not the domain name.
EDIT
If it helps anyone, I just try to DNS Resolve the name of a machine that I can guarantee will be on the network (one of the servers). It works sufficiently well for me.
A: Have you tried:
Environment.UserDomainName
You could also take a look at the active IP addresses on the machine, and query for one that works on your local network...
var x = NetworkInterface.GetAllNetworkInterfaces()
.Where(ni => ni.OperationalStatus == OperationalStatus.Up)
.SelectMany(ni => ni.GetIPProperties().UnicastAddresses);
// do something with the collection here to determine if you're on the right network.
// just looping & printing here for example.
foreach (var item in x)
{
Console.WriteLine(item.Address);
}
And after you've figured out the network that you're on, you could subscribe to the System.Net.NetworkInformation.NetworkChange.NetworkAddressChanged event to handle your computer jumping networks while your app is running.
A: System.Environment.UserDomainName
A: System.Security.Principal.WindowsIdentity.GetCurrent().AuthenticationType
This will return "NTLM" when not connected to the network.
A: You want to look at the Network Location Awareness API. Available on Windows Vista or later, it allows you to programmatically discover which network you're connected to, and be notified when this changes.
It might be familiar to you in the form of the "Is this a home / work / public network?" dialog box.
A: Another way, but I don't know if it is actually any better than the other solutions is:
System.Security.Principal.WindowsIdentity.GetCurrent().AuthenticationType
this is a string that returns "Kerberos" under active directory. Not sure what it would say when not connected to the domain though.
A: Environment.UserDomainName ...gives you the machine name if you are not joined to a domain. It gives you the domain name if you are joined to a domain. If you take a machine that is joined to a domain off the network and out "into the wild", Environment.UserDomainName will continue to provide the domain name even if you reboot and log back in (to your domain account). Your machine caches the domain credentials for about 30 days.
If you log in to your machine account, then you will get the machine name.
| |
doc_23538467
|
Something like:
int a = 97;
int b = 98;
int c = 99
int enter = 65293;
String character = Keysym.get(a); //outputs a
A: Solution
You simply need to cast to char :
static char getCode(int key) {
return (char) key;
}
Use as
public static void main(String[] args) {
System.out.println(getCode(97)); // a
System.out.println(getCode(98)); // b
System.out.println(getCode(99)); // c
}
| |
doc_23538468
|
I still need the original image and so cannot modify the original array.
This function is called to process each frame of a video stream.
Do you know possibilities to optimize the function for speed?
Thanks!
QImage* createQImage(uchar *ptr, uint width, uint height, uint channels)
{
static uint size = width * height * channels;
static uchar *buffer = new uchar[size];
//Take every second byte (upper byte)
for(uint i=0; i<size; i++) {
buffer[i] = (*(ptr+1));
ptr = ptr+2;
}
static QImage img = QImage(buffer, width, height, QImage::Format_BGR888);
static QImage *ptr_img = &img;
return ptr_img;
}
A: If you are just moving an input buffer to an output buffer doing it one byte at a time isn't the fastest. Simply casting uchar *ptr to uint64_t* and pulling out the bytes using bit shifting/masks maybe the way to optimise this. You will end up with some bytes left at the end that you will need to process "manually", in the same way that you already are. Assuming that your images are 16-bit then 16/64 == 4, giving you a 4 times speed improvement.
This assumes that your hardware can load 64 bits at a time, you could make this code load 32 bits at a time by using uint32_t instead but it is a fair assumption that most people have 64 bit hardware. The code assumes you are using little endian hardware.
The code (untested).
QImage* createQImage(uchar* ptr, uint width, uint height, uint channels) {
uint64_t* nptr = (uint64_t*)ptr;
static uint size = width * height * channels;
static uchar *buffer = new uchar[size];
static uint bytesize = size*2;
uint idx = 0;
uint i = 0;
for(; i + sizeof(uint64_t) <= bytesize; i+=sizeof(uint64_t)) {
//get 64 bits at a time
uint64_t val = nptr[i/sizeof(uint64_t)];
//get 4 bytes at a time
//note inverted due to little endian assumed (maybe wrong)
buffer[idx] = (uchar)(val >> (8 * 6));
++idx;
buffer[idx] = (uchar)(val >> (8 * 4));
++idx;
buffer[idx] = (uchar)(val >> (8 * 2));
++idx;
buffer[idx] = (uchar)(val >> (8 * 0));
++idx;
}
//We have some bytes left at the end, process these a byte at a time
//Take every second byte (upper byte)
for(; i < bytesize; i+=2) {
buffer[idx] = (*(ptr + i + 1));
++idx;
}
static QImage img = QImage(buffer, width, height, QImage::Format_BGR888);
static QImage *ptr_img = &img;
return ptr_img;
}
| |
doc_23538469
|
while True:
global opened, filepath
command = input("save or open: ")
opened = False
filepath = "Empty"
if command == "save":
if opened:
print(f"yes you opened a file {filepath}")
else:
print(f"no you didn't open a file {filepath} {opened}")
elif command == "open":
filepath = "/home/pi/Desktop/testing.txt"
opened = True
print(f"opened {filepath} {opened}")
else:
print("typo")
hello()
I want to change the opened and the filepath variable as i've tried to demonstrate but am failing to do so, i need the filepath to change when i want it to, but it doesn't. It just dosen't regester and change both of the variables and prints out Empty and Fasle respectively.
btw this is my output:
save or open: open
opened /home/pi/Desktop/testing True
save or open: save
no you didn't open a file Empty False
A: You are setting opened = True, but you will overwrite it in the next loop iteration with opened = False.
You will need to initialize variables before the while loop.
Also, there is no need to use global here.
A: def hello():
opened = False #moved these
filepath = "Empty"
while True:
command = input("save or open: ")
if command == "save":
if opened:
print(f"yes you opened a file {filepath}")
else:
print(f"no you didn't open a file {filepath} {opened}")
elif command == "open":
filepath = "/home/pi/Desktop/testing"
opened = True
print(f"opened {filepath} {opened}")
else:
print("typo")
hello()
result:
save or open: open
opened /home/pi/Desktop/testing True
save or open: save
yes you opened a file /home/pi/Desktop/testing
| |
doc_23538470
|
{"name":"http.server.requests","baseUnit":"seconds","measurements":
[{"statistic":"COUNT","value":2.0},{"statistic":"TOTAL_TIME","value":0.325170155},
{"statistic":"MAX","value":0.250113973}],"availableTags":
[{"tag":"requiredMetricName","values":["http.server.requests"]}]}
And all tags don't work
For example
/actuator/metrics/http.server.requests?tag=status:200
gets 404
I use Spring boot 2
implementation 'org.springframework.boot:spring-boot-starter-actuator'
I have
public static void main(String[] args) {
SpringApplication application = new SpringApplication(Application.class);
Properties properties = new Properties();
properties.put("management.metrics.web.server.auto-time-requests", true);
properties.put("management.endpoints.web.exposure.include", "*");
application.setDefaultProperties(properties);
application.run(args);
}
A: Looks like I had extra bean. It was the reason
@Bean
public WebMvcTagsProvider webMvcTagsProvider() {
return new WebMvcTagsProvider() {
@Override
public Iterable<Tag> getTags(HttpServletRequest request, HttpServletResponse response, Object handler, Throwable exception) {
return ((Map<String, String>) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE))
.entrySet()
.stream()
.map(entry -> new ImmutableTag(entry.getKey(), entry.getValue()))
.collect(Collectors.toList());
}
@Override
public Iterable<Tag> getLongRequestTags(HttpServletRequest request, Object handler) {
return new ArrayList<>();
}
};
}
| |
doc_23538471
|
HKEY hKey;
char *path = "SYSTEM\\CurrentControlSet\\Control\\IDConfigDB\\Hardware Profiles\\0001\\HwProfileGuid";
LONG result = RegOpenKeyExA(HKEY_LOCAL_MACHINE, path, 0, KEY_ALL_ACCESS, &hKey);
QString q = QString::number(result);
if (result == ERROR_SUCCESS) {
QMessageBox messageBox1;
messageBox1.critical(0,"Error", "Success");
messageBox1.setFixedSize(500,200);
} else {
QMessageBox messageBox2;
messageBox2.critical(0,"Error", q);
messageBox2.setFixedSize(500,200);
}
The error I am getting:
Where the key is in my Registry:
I think the problem is related to the way I put the info in the path variable, but I am not sure.
A: Dont pass Computer\\HKEY_LOCAL_MACHINE to the string. just SYSTEM\\CurrentControlSet\\Control\\IDConfigDB\\Hardware Profiles\\0001 Because HKEY_LOCAL_MACHINE are exist in RegOpenKey First Parameter. And dont try to open the value of key just the key RegSetKeyValue() For writing value of key
here the working code:
HKEY hKey;
LONG result = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Control\\IDConfigDB\\Hardware Profiles\\0001", 0, KEY_ALL_ACCESS, &hKey);
cout << result << "\n";
A: You have HwProfileGuid in the wrong place.
HwProfileGuid is a value inside of the 0001 key, but you are trying to open HwProfileGuid as a sub-key of 0001 instead, which is why you are getting error 2 (ERROR_FILE_NOT_FOUND), because there is no sub-key named HwProfileGuid.
Also, KEY_ALL_ACCESS is too many rights to request just to read a value from a key. Use KEY_QUERY_VALUE instead. Don't request more rights than you actually need.
Try this:
const char *path = "SYSTEM\\CurrentControlSet\\Control\\IDConfigDB\\Hardware Profiles\\0001";
const char *valueName = "HwProfileGuid";
char guid[40] = {0};
HKEY hKey;
LONG result = RegOpenKeyExA(HKEY_LOCAL_MACHINE, path, 0, KEY_QUERY_VALUE, &hKey);
if (result == ERROR_SUCCESS) {
DWORD size = sizeof(guid);
result = RegQueryValueExA(hKey, valueName, NULL, NULL, reinterpret_cast<LPBYTE>(guid), &size);
RegCloseKey(hKey);
}
QMessageBox messageBox;
if (result == ERROR_SUCCESS) {
messageBox.critical(0, "Success", guid);
} else {
messageBox.critical(0, "Error", QString::number(result));
}
messageBox.setFixedSize(500, 200);
Alternatively, you can use RegGetValueA() instead of using
RegOpenKeyExA()+RegQueryValueExA():
const char *path = "SYSTEM\\CurrentControlSet\\Control\\IDConfigDB\\Hardware Profiles\\0001";
const char *valueName = "HwProfileGuid";
char guid[40] = {0};
DWORD size = sizeof(guid);
QMessageBox messageBox;
LSTATUS result = RegGetValueA(HKEY_LOCAL_MACHINE, path, valueName, RRF_RT_REG_SZ, NULL, guid, &size);
if (result == ERROR_SUCCESS) {
messageBox.critical(0, "Success", guid);
} else {
messageBox.critical(0, "Error", QString::number(result));
}
messageBox.setFixedSize(500, 200);
| |
doc_23538472
|
Exception in thread "main" Unexpected token END OF FILE at position 0.
at org.json.simple.parser.JSONParser.parse(JSONParser.java:257)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:92)
at readjson.ReadJson.readFileToWriteJSON(ReadJson.java:121)
at readjson.ReadJson.main(ReadJson.java:40)
I have no clue how to catch this exception. Any idea?
EDIT
Here is the code:
private static void readFileToWriteJSON(final File folder) throws FileNotFoundException, IOException, ParseException {
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
readFileToWriteJSON(fileEntry);
} else {
try{
String query=fileEntry.getName();
fop=new FileOutputStream(file+"\\"+query+".txt");
JSONParser jsonParser = new JSONParser();
File file = new File(fileEntry.getPath());
Object object = jsonParser.parse(new FileReader(file));//exception happens here.
JSONObject obj= (JSONObject) object;
parseJson(obj);
for(String url:writeThis){
fop.write(url.getBytes());
fop.write(System.getProperty("line.separator").getBytes());
}
writeThis=new ArrayList<>();
}
}
catch(){}//how to fill this part
}
}
A: This is thrown from inside the library to your calling code. So find the calling line from your code to this error throwing code (at readjson.ReadJson.main(ReadJson.java:40)) and put a try catch there..
A: First of all remove your try and catch as they are in the wrong place - assuming that you want to continue reading other files.
Then change your code to
Object object = null;
try {
object = jsonParser.parse(new FileReader(file));//exception happens here.
} catch (Exception e) {
e.printStackTrace();
continue; // go to the top of the for loop
}
A: Try this:
try {
// your code
} catch (EOFException e) {
// handle EOF exception
} catch(IOException e) {
// handle not expected exception
e.printStackTrace();
}
| |
doc_23538473
|
But is there a better way to do it?
This is how it looks like without the placeholder label (View in full page to see it better):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css" rel="stylesheet" />
<div class="containter-fluid">
<div class="h-100">
<div class="d-flex flex-row-reverse flex-wrap justify-content-start">
<div class="form-group justify-content-end text-right form-inline">
<div class="d-flex flex-column align-items-end">
<label for="select1" dir="rtl">select1:</label>
<select title="select1" class="selectpicker">
<option>option</option>
</select>
</div>
</div>
<div class="form-group justify-content-end text-right form-inline">
<div class="d-flex flex-column align-items-end">
<label for="select2" dir="rtl">select1:</label>
<select title="select2" class="selectpicker">
<option>option</option>
</select>
</div>
</div>
<div class="form-group justify-content-end text-right form-inline">
<div class="d-flex flex-column align-items-end">
<label for="select3" dir="rtl">select1:</label>
<select title="select3" class="selectpicker">
<option>option</option>
</select>
</div>
</div>
<div class="form-group justify-content-end text-right form-inline">
<div class="d-flex flex-column align-items-end">
<button type="button" class="btn btn-primary">Click</button>
</div>
</div>
</div>
</div>
</div>
And this is how it looks like with the placeholder label (And how I want it to look like):
.placeholder_label {
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css" rel="stylesheet" />
<div class="containter-fluid">
<div class="h-100">
<div class="d-flex flex-row-reverse flex-wrap justify-content-start">
<div class="form-group justify-content-end text-right form-inline">
<div class="d-flex flex-column align-items-end">
<label for="select1" dir="rtl">select1:</label>
<select title="select1" class="selectpicker">
<option>option</option>
</select>
</div>
</div>
<div class="form-group justify-content-end text-right form-inline">
<div class="d-flex flex-column align-items-end">
<label for="select2" dir="rtl">select1:</label>
<select title="select2" class="selectpicker">
<option>option</option>
</select>
</div>
</div>
<div class="form-group justify-content-end text-right form-inline">
<div class="d-flex flex-column align-items-end">
<label for="select3" dir="rtl">select1:</label>
<select title="select3" class="selectpicker">
<option>option</option>
</select>
</div>
</div>
<div class="form-group justify-content-end text-right form-inline">
<div class="d-flex flex-column align-items-end">
<label class="placeholder_label" dir="rtl">
placeholder label
</label>
<button type="button" class="btn btn-primary">Click</button>
</div>
</div>
</div>
</div>
</div>
A: Add a new class to the container div <div class="d-flex flex-row-reverse flex-wrap justify-content-start"> for example align-items, so you will have a new div <div class="d-flex flex-row-reverse flex-wrap justify-content-start align-items">
And then apply this CSS to the newly created role
.align-items{
align-items:flex-end; //puts all items to the bottom of container - in your case it aligns them
}
| |
doc_23538474
|
We've setup a good continuous integration-deployment-delivery pipeline; basically, our process is like that:
New development happens on the default branch (we use Mercurial, but git would have the same issue); usually we develop just one small improvement there;
Once the improvement is ready and tested (something that usually happens twice or three times a week, our cycle is pretty short), it's merged into the release branch (which actually stands for release candidate), it's tested again in a production-like environment and if it passes all our testing it's pushed to the production environment.
If we need to make a bugfix, we do it on the release branch, we test it and then push it to the production env.
An artifact (usually an RPM package) is built from each branch; when there's a release in production, the very artifact from the release branch is promoted to our public repository. There's no branch for the production environment, because we usually don't need it (there's a very short timespan when something it's on the release branch but it's not in production; code doesn't linger there unattended).
In this context, there's a small issue for us.
In order to distinguish packages, we usually set version to 1 for packages on the release branch, and 2 to packages on the default branch. Our CI system then adds its build number, so we've got packages like oursoftware-1.0-build37 for release and oursoftware-1.0-build902 for default. Such version is written either in our .spec file or in our pom.xml files (or other files for different softwares, like .gemspec or simila)
Whenever we want to put something in release candidate, we merge the default branch to the release branch.
What happens there? the version gets merged as well. So after each merge we need to get back at the file containing the version and put the old version in them. We should need to do it just once (Mercurial does not try to re-merge things that were already merged) but whenever we need to do a merge from release from default (e.g. in order to merge a fix done on release to the dev branch) the problem rises again.
I'd like some advice on how to prevent this problem completely; how do I set versions outside of my branches? I sometimes actually need to change them (e.g. I want to change from 1 to 2 on release and from 2 to 3 on default) and I wouldn't like to hardcode them in our CI system, I'd like some system which is "outside" the scope of branches and it's kind of "global" for a repository. Or I would need something like "ignore modification for some files".
In many situations I actually need versions in my files as well; for example I cannot omit version info from a Maven pom.xml file or from a .gemspec, otherwise it won't work when developing.
Thanks,
A: Well, I see 3 4 a lot of possible solution, more or less "native" (random order without priorities and own personal preferences)
*
*Instead of "Monolitic $DEVEL branch" you can use "Branch Per task": in this case file with (hardcoded) version-info will not appear as mergeable file (TBT!)
*Branch-specific version change can be moved from (permanent) changeset of branch into patch of MQ (as results - versions /and files/ are identical across branches, permanent default changes have to appear as result of applying patch)
*Files with version-info doesn't contain hardcoded versions, they are more "templates", than "data", and real data appear as result of some preprocessing inside build process (you know transformation-rules and can code it)
*You can change nothing in developent|deploy process and if version-info files are unique inside repository, you can use trick, similar to merging hgtags (special mergetool for only some files in repo - in your case in must be internal:local special mergetool)
*Maybe using just merge-patterns will be OK for you, check Mercurial - Exceptions to internal:local merge-patterns? and Default to trunk version for Mercurial merges? for details and some additional notes+discoveries
| |
doc_23538475
|
public static void main(String[] args) throws Exception {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
JFrame frame = new JFrame("Test");
frame.setLocationRelativeTo(null);
SwingUtilities.invokeAndWait(JFXPanel::new);
frame.add(new JFXPanel());
Platform.runLater(() -> {
JPanel panel = new JPanel();
System.exit(0);
});
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(200, 100);
frame.setVisible(true);
}
First of all, the code is compiled with OpenJDK-11 and OpenJFX-11, and in Windows this runs just fine (i.e. exits at the System.exit(0) call).
However, if I run this on Linux (specifically Ubuntu 20.04), the call to new JPanel() locks the thread, and the program never exits. Commenting out the UIManager.setLookAndFeel call will get it to work normally again.
Am I just running into a bug in the com.sun.java.swing.plaf.gtk.GTKLookAndFeel (which is what the SystemLookAndFeel returns) or am I doing something wrong/unexpected here?
A:
am I doing something wrong/unexpected here?
Yes, you are doing something wrong: you're violating the Swing threading policy, which states
All Swing components and related classes, unless otherwise documented, must be accessed on the event dispatching thread.
This answer will show you how to refactor your code so it obeys that
(and other) threading rules. I don't have a Linux environment to test this on, so it's possible there are also bugs in the Linux implementation of JavaFX and/or Swing or in the GTKLookAndFeel, but
this at a minimum gives you a correct way to test that.
Most of the code in your main method should be executed on the AWT event dispatch thread. You can achieve this by wrapping it in SwingUtilities.invokeLater(...).
The exceptions to that are:
*
*Platform.runLater(...), which schedules something to be run on the FX Application thread, can itself be called from anywhere. However, the new JPanel() which you call inside it should not be executed on the FX Application Thread, it should be executed on the AWT event dispatch thread.
*SwingUtilities.invokeAndWait(...) must not be called from the AWT event dispatch thread. This schedules code to be executed on the AWT event dispatch thread, and pauses the current thread until it is completed. Thus calling SwingUtilities.invokeAndWait(...) from the AWT event dispatch thread will result in deadlock. The code
SwingUtilities.invokeAndWait(JFXPanel::new);
schedules new JFXPanel() to be executed on the AWT event dispatch thread, and blocks the current thread until that has completed. If you are already on the AWT event dispatch thread, simply calling
new JFXPanel();
achieves the same thing.
I understand that your code is an attempt to create a minimum reproducible example, but it's not really clear what it's an example of, as there's code there whose purpose is completely unclear. For example, you create two JFXPanel instances, the first of which you discard. And you create a JPanel, which you similarly discard, deliberately on the incorrect thread.
I don't have a Linux environment to test this, but the closest "correct" version of the code you posted is something like this. If this code still hangs, I believe there is a bug in the library implementation somewhere.
public static void main(String[] args) throws Exception {
// We are not on the AWT event dispatch thread, so if we
// want to create and access Swing components, we must wrap
// that code inside SwingUtilities.invokeLater(...):
SwingUtilities.invokeLater(() -> {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
JFrame frame = new JFrame("Test");
frame.setLocationRelativeTo(null);
// We must not call SwingUtilities.invokeAndWait(...)
// from the event dispatch thread, so remove this:
// SwingUtilities.invokeAndWait(JFXPanel::new);
// To create new JFXPanel and block until the call is
// complete, we just create it in the usual way (since
// we're already on the event dispatch thread)
new JFXPanel();
frame.add(new JFXPanel());
Platform.runLater(() -> {
// This code block is executed on the FX Application Thread
// To create a swing component, we must wrap the
// code in SwingUtilities.invokeLater(...), so it's
// executed on the Event Dispatch Thread:
SwingUtilities.invokeLater(() -> {
JPanel panel = new JPanel();
System.exit(0);
});
});
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(200, 100);
frame.setVisible(true);
});
}
As an aside, note that the Look and Feel will only affect Swing components; it will not affect JavaFX controls, whose appearance and behavior are managed by JavaFX (by default by the default CSS stylesheet). So anything you place in the JFXPanel will not be affected by the look and feel.
And finally, you should not mix multiple UI toolkits unless you have a very compelling reason to do so. As you can see, working with two independent single-threaded toolkits is challenging.
| |
doc_23538476
|
DECLARE @g geometry;
SET @g = geometry::STPolyFromText('POLYGON ((5.177074447274207 60.32819571126778,
5.177074447274207 60.32533671620816,
5.172660537064075 60.32533671620816,
5.172660537064075 60.32819571126778,
5.177074447274207 60.32819571126778)
)', 4326).MakeValid();
DECLARE @h geometry;
SET @h = geometry::Point(5.1752474, 60.3290297, 4326)
Select @g.STDistance(@h)
and the following is the result I get
0.000833988732217961
But when I find the distance between points on Google Map and Bing Map, I get 100mtr.
I have also checked the documentation related to SRID and as I use SRID 4326 it uses the meter as the measurement. So, if I consider the return result as the meters then there is a vastly different result.
So is there any issue with the function STDistance or should I consider this as Km instead of meters or something?
A: First: Since Earth is not flat, use geography types instead:
--Closest point from polygon
DECLARE @g geography = geography::Point(60.32819571126778, 5.1752474, 4326)
--Reference point
DECLARE @h geography = geography::Point(60.3290297, 5.1752474, 4326)
SELECT @g.STDistance(@h)
It returns 92,9212347595042 [meters] which seems to be correct.
Second: To use polygon you must take care of orientation. There is distinction between 'inside polygon' and 'outside polygon' in geography type. If polygon covers half of Earth - which half should be selected? This is determined by orientation. I switched points #2 and #4. See following example:
DECLARE @g geography = geography::STPolyFromText('POLYGON ((
5.177074447274207 60.32819571126778,
5.172660537064075 60.32819571126778,
5.172660537064075 60.32533671620816,
5.177074447274207 60.32533671620816,
5.177074447274207 60.32819571126778))', 4326);
DECLARE @h geography = geography::Point(60.3290297, 5.1752474, 4326)
SELECT @g.STDistance(@h)
It returns 92,9192581745513 [meters] which seems to be correct.
Third: Make sure your latitude and longitude coordinates are not switched: see Point vs STPolyFromText.
| |
doc_23538477
|
http://jsfiddle.net/2F55j/5/
$(function() {
$( "table tr" ).selectable(
{filter: ":not(.belegt)"}
);
});
Now I would like to only select cells next to each other, that form a continous line. So when there is a filtered out cell in between, the one after it cannot be selected.
On a sidenote: when I select cells in row 1, then select some in row 2, the selected ones in row 1 do not get removed..How to get this to work?
Could you help me please?
I have been on this now for hours and it just won't work.
Thanks in advance :)
A: $(function() {
$( "table tr" ).selectable({
filter: "td",
start: function(event, ui){
$("td.ui-selected").removeClass("ui-selected");
},
stop: function(event, ui){
var selected = $("td.ui-selected");
if(selected.hasClass("belegt"))
selected.removeClass("ui-selected");
}
});
});
| |
doc_23538478
|
i HAVE A .jspx page where clients will be able to send emails through it.
in the body I am using ADF Rich Text Editor. In this ADF rich text editor the user will be able to insert in it images and text. the image needs to be inside the editor and not Attachment.
usually this image will be a screen shot were the user will press the PrtScn button and then past the screen shot inside the editor.
If I go to the source code i will find the source code of the image will look like this
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABaAAAAOECAYA.........>
Also I am using Java outlook connector in order to be able to send the email to outlook.
I bound the Editor to my bean and below is how I'm sending it:
`Outlook outlookApplication = new Outlook();
OutlookFolder outbox = outlookApplication.getDefaultFolder(FolderType.OUTBOX);
OutlookMail mail = (OutlookMail) outbox.createItem(ItemType.MAIL);
mail.setSubject("Hello HELLO!!!");
mail.setTo("User");
String edtrContent = geteditor().getValue().toString();
mail.setHTMLBody("<HTML><Body>" + edtrContent + "</Body></HTML>");
mail.send
The email is sent successfully to my outlook mail and I can only read the text sent. On the other hand I am not able to see the image that was sent in the rich text editor and it is appearing as a small box having X in red.
A: HTML messages in Outlook are rendered by Word, not IE. Word does not handle embedded (src=data/image) images.
You can either refer to external images or to image attachments <img src="cid:xyz"> where xyz is the value of the Content-ID MIME header of the image attachment.
A: As Dmitry noticed, you need to add an embedded attachment to add images to the message body.
*
*Add the attachment using the Attachments.Add method.
*Set the PR_ATTACH_CONTENT_ID property using the PropertyAccessor object.
*Set the cid value (see #2) for the reference in the message body.
string img = "<br/><p><o:p><img src=\"" + att.FileName
+ "\" width=1 height=1 border=0 /></o:p></p>";
item.HTMLBody = item.HTMLBody.Replace("</body>", img + "</body>");
string PR_ATTACH_CONTENT_ID = "http://schemas.microsoft.com/mapi/proptag/0x3712001E";
string HIDDEN_ATTACHMENT = "http://schemas.microsoft.com/mapi/proptag/0x7FFE000B";
var pa = att.PropertyAccessor;
if (pa != null)
{
pa.SetProperty(PR_ATTACH_CONTENT_ID, att.FileName);
pa.SetProperty(HIDDEN_ATTACHMENT, false);
}
| |
doc_23538479
|
Here is my controller:
public function index($fooElement = '')
{
$query = $this->Properties->find()->where(['fooElement' => $fooElement]);
//The fooFunction needs an array cause for an internal call of cakes HASH::NEST function
$data= $this->FooModel->_fooFunction($query->enableHydration(false)->toList();
//Error: Not a paginable object
$data = $this->paginate($data)
$this->set(compact('fooElement', 'data'));
$this->set('_serialize', ['data']);
if (empty($fooElement)) {
$this->render('otherView');
}
}
EDIT: Here is the fooFunction:
public function _fooFunction($data)
{
$out = [];
$cache = [];
$nested = Hash::nest($data, ['idPath' => '{n}.id', 'parentPath' => '{n}.parent_id']);
$out = $this->_setOrderAndLevel($nested);
return $out;
}
protected function _setOrderAndLevel($items, $level = 0, $number = 0)
{
$out = [];
$items = Hash::sort($items, '{n}.orderidx');
foreach ($items as $item) {
$item['level'] = $level;
if (!empty($item['children'])) {
$children = $item['children'];
unset($item['children']);
$out[] = $item;
$out = array_merge($out, $this->_setOrderAndLevel($children, $level + 1));
} else {
$out[] = $item;
}
}
return ($out);
}
The _fooFunction takes the casted database query, makes some adjustments, adds two new properties and returns a nested Array. It maps id with parent_id in order to get children and a level description. The level description will be used for indentations in the view to display a hierarchical order.
IMPORTANT NOTICE: I am already beware of TreeBehavior in CakePHP but the problem is that our database has no left/right fields and I am not able to add them. Within this project I have to choose this way.
However $data contains exactly what I want but I need to transform it into a compatible object for pagination.
EDIT: Thanks to ndm I could build a paginable object with the necessary constraints. The last problem I still have in front of me is to merge all children and possible sub-children. A parent can have nth children and also a children can sometimes have nth sub-children. Therefore I solved this with a recursive call of my _setOrderAndLevel function within the fooFunction.
This is the current structure:
array(
[0] = fooEntity(
id = 1,
orderidx = 1,
parentId = null,
level = 0,
children(
id = 2,
orderidx = 2,
parentId = 1,
level = 1
children(
id = 3,
orderidx = 3,
parentId = 2,
level = 2
........
But it should be this:
array(
[0] = fooEntity(
id = 1,
orderidx = 1,
parentId = null
level = 0
[1] = fooEntity(
id = 2,
orderidx = 2,
parentId = 1,
level = 1
[2] = fooEntity(
id = 3,
orderidx = 3,
parentId = 2,
level = 2
........
I tried to build a second result formatter but it does not work:
...
return $results
->nest('id', 'parent_id', 'children')
->map($decorate);
})
->formatResults(function (\Cake\Collection\CollectionInterface $results) {
return $results->map(function ($data) {
call_user_func_array('array_merge', $data);
});
});
Maybe a "combine->" call could be the solution but I am not sure.
Any help is welcome
A: Generally if you need to format the results in some way, you should most likely use a result formatter, in order to be able to keep query object intact, and rom looking at the resulting format that your function produces, that is what you should use in this case, a result formatter.
If you need the ordering you could do that on SQL level already, and for nesting the results you could use the result collection's nest() method, ie you could ditch using the Hash class:
$query = $this->Properties
->find()
->where(['fooElement' => $fooElement])
->order(['orderidx' => 'ASC'])
->formatResults(function (\Cake\Collection\CollectionInterface $results) {
$fold = function ($rows, $level = 0) use (&$fold) {
$folded = [];
foreach ($rows as $row) {
$row['level'] = $level;
$children = $row['children'] ?: null;
unset($row['children']);
$folded[] = $row;
if ($children) {
$folded = array_merge(
$folded,
$fold($children, $level ++)
);
}
}
return $folded;
};
$nested = $results->nest('id', 'parent_id', 'children');
$folded = $fold($nested);
return collection($folded);
});
Note that you must return an instance of \Cake\Collection\CollectionInterface from the result formatter. The docs say that returning an(y) iterator would be enough, but as soon as there are additional formatters appended that expect a collection, things would break.
See also
*
*Cookbook > Database Access & ORM > Query Builder > Adding Calculated Fields
*Cookbook > Collections > Working with Tree Data
| |
doc_23538480
|
I am building and app which is passing through the Azure AD sign in and redirecting back after a successful handshake. All works fine when using https://localhost:port as my RedirectURI in Azure, for example:
Under Web Redirect URIs this following works just fine:
https://localhost:7280/signin-oidc
I login with my AD credentials and I am redirected back to my app's landing page, so all good there.
The problem is however, when I use the following in the hosts file, I am just redirected back to the Azure AD sign in page, even though when I check the azure sign in logs, it states the login was successful.
Question: Is it possible to use a custom URI using the hosts file in a local development environment, when developing an app passing through an Azure sign in? Or am I restricted to using https://localhost:portNumber for my web redirectURIs? Thanks in advance.
Here is the hosts file and the web RedirectURIs in Azure. As mentioned earlier, https://localhost:port works fine. Note: I already have an SSL Certificate for the local development environment which is fine.
My hosts file:
127.0.0.1 dev.operations.co.uk
My web redirectUri(s) in Azure which I have tested:
https://dev.operations.co.uk/signin-oidc
https://dev.operations.co.uk/
| |
doc_23538481
|
I need to make a search with some keywords in search engines such as google. I got two class here to do this:
package com.sh.st;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class EventSearch extends SearchScreen implements ActionListener {
public EventSearch(){
btsearch.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==btsearch){
String query=txtsearch.getText();
}
}
}
and
package com.sh.st;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class HttpRequest extends SearchScreen
{
URL url = new URL("google.com" + "?" + query).openConnection();
URLConnection connection = url.openConnection();
connection.setRequestProperty("Accept-Charset", "UTF-8"); //Possible Incompatibility
InputStream response = connection.getInputStream();
}
So, txtsearch comes from another class named SearchScreen and I attributed the value to one string named query. I need to pass query to HttpRequest class and to do this I just extend, I'm sure it's wrong but I saw someone else doing this; and this is the first problem, how may I do this?
the second and most important I'm receiving syntax error:
I didn't fully understand the meaning and utility of "connection.setRequestProperty("Accept-Charset", "UTF-8");"
'course reading I can understand that is regarding the caracters that probably will come up from my request but even though the syntax error is not clear for me
I made research in links such:
*
*How to send HTTP request in java?
*getting text from password field
*http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139
*Using java.net.URLConnection to fire and handle HTTP requests
All of them have a good material but I can't fully understand everything on it and the part the I'm trying to follow is not working. Could anyone help me please?
Edit: [Topic Solved]
A: Try this code: (comments inlined)
// Fixed search URL; drop openConnection() at the end
URL url = new URL("http://google.com/search?q=" + query);
// Setup connection properties (this doesn't open the connection)
URLConnection connection = url.openConnection();
connection.setRequestProperty("Accept-Charset", "UTF-8");
// Actually, open the HTTP connection
connection.connect();
// Setup a reader
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
// Read line by line
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println (line);
}
// Close connection
reader.close();
| |
doc_23538482
|
libxml_use_internal_errors(true);
$RSS_DOC = simpleXML_load_file($feed_url);
if (!$RSS_DOC) {
echo "Failed loading XML\n";
foreach (libxml_get_errors() as $error) {
echo "\t", $error->message;
}
}
I've the code above to load other rss feeds such as:
http://example.blogspot.com/feeds/posts/default?alt=rss
and
$feed_url ="http://www.quiltexamples.com/rss.xml";
However with the URL that I'm currently trying to load, I get:
PHP Warning: simplexml_load_file(http://www.example.com/examplestring?format=RSS):
failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request
in ExamplelogParser.php on line 7
Failed loading XML
failed to load external entity "http://www.example.com/examplestring?format=RSS"
| |
doc_23538483
|
select field4 from label with ur
1.5000
0.006
9.0001
104.2500
17.0000
3.5000
Is it possible to eliminate the trailing zeros after the decimal point with an update query in DB2?
If all the digits are zeros after the decimal point, I need to keep that as .0, however.
Expected output:
1.5
0.006
9.0001
104.25
17.0
3.5
A: You should probably consider changing the column to some kind of numeric. Anyhow, heres an idea:
with t(s) as (
values '1.5000', '0.006', '9.0001','104.2500','17.0000','3.5'
)
select translate(rtrim(translate(s,' ','0')),'0',' ')
|| case when translate(rtrim(translate(s,' ','0')),'0',' ') like '%.'
then '0'
else ''
end
from t
1.5
0.006
9.0001
104.25
17.0
3.5
Using a CTE for translate(rtrim(translate(s,' ','0')),'0',' ') will minimize the number of function calls.
with t(s) as (values '1.5000', '0.006', '9.0001','104.2500','17.0000','3.5')
, u(s) as (
select translate(rtrim(translate(s,' ','0')),'0',' ')
from t
)
select s || case when s like '%.' then '0' else '' end
from u
1.5
0.006
9.0001
104.25
17.0
3.5
A: This is really hacky, but it should work for you.
SELECT
trimmed || CASE WHEN LOCATE('.',trimmed) = LENGTH(trimmed) THEN '0' ELSE '' END
FROM (
SELECT TRIM(TRAILING '0' FROM field4) AS trimmed
FROM lablel
) A
The CASE statement re-adds a trailing zero if a decimal is the last character. If your string contains other decimals for whatever reason, this would break. If you were on DB2 9.7 (I'm assuming LUW here), then a better option would be to use LOCATE_IN_STRING, which can work backwards from the end of the string when you provide a negative start:
SELECT
trimmed || CASE WHEN LOCATE_IN_STRING(trimmed,'.',-1) = LENGTH(trimmed) THEN '0' ELSE '' END
FROM (
SELECT TRIM(TRAILING '0' FROM field4) AS trimmed
FROM lablel
) A
| |
doc_23538484
|
interface MyImage {
URI: string,
Width?: number,
Height?: number,
}
Is there a way to disable eslint rule (naming-convention) for the whole interface (I have many of them inside one file)
A: Override the rule at the top of your file by turning the format off for interfaces, try this:
/* eslint @typescript-eslint/naming-convention: ["off", { "selector": "interface", "format": ["camelCase"] }] */
Original answer:
You'd have to find the rule name that's enforcing the style, I'm guessing it's the @typescript-eslint/camelcase.
When you find the rule name, you can turn the rule off for the current file by writing
/* eslint-disable @typescript-eslint/camelcase */
at the top of your file.
A: Since disabling eslint on each file doesn't seem to be the most convenient approach, you can make some changes in your .eslintrc and have it for all files across your project in a more maintainable way.
This has been already answered here:
Turn off eslint camelCase for typescript interface identifiers
| |
doc_23538485
|
I am using Swing to create a GUI. When I try to connect to the database and run a query, I get this error:
Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: javax/xml/bind/DatatypeConverter
at sqljdbc42/com.microsoft.sqlserver.jdbc.SQLServerConnection.sendLogon(SQLServerConnection.java:4098)
at sqljdbc42/com.microsoft.sqlserver.jdbc.SQLServerConnection.logon(SQLServerConnection.java:3160)
at sqljdbc42/com.microsoft.sqlserver.jdbc.SQLServerConnection.access$100(SQLServerConnection.java:43)
at sqljdbc42/com.microsoft.sqlserver.jdbc.SQLServerConnection$LogonCommand.doExecute(SQLServerConnection.java:3123)
at sqljdbc42/com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:7505)
at sqljdbc42/com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:2445)
at sqljdbc42/com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1981)
at sqljdbc42/com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:1628)
at sqljdbc42/com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:1459)
at sqljdbc42/com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:773)
at sqljdbc42/com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1168)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:677)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:251)
at main_package.inchisoare$2.actionPerformed(inchisoare.java:65)
at java.desktop/javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1967)
at java.desktop/javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2308)
at java.desktop/javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:405)
at java.desktop/javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:262)
at java.desktop/javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:279)
at java.desktop/java.awt.Component.processMouseEvent(Component.java:6636)
at java.desktop/javax.swing.JComponent.processMouseEvent(JComponent.java:3342)
at java.desktop/java.awt.Component.processEvent(Component.java:6401)
at java.desktop/java.awt.Container.processEvent(Container.java:2263)
at java.desktop/java.awt.Component.dispatchEventImpl(Component.java:5012)
at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2321)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4844)
at java.desktop/java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4918)
at java.desktop/java.awt.LightweightDispatcher.processMouseEvent(Container.java:4547)
at java.desktop/java.awt.LightweightDispatcher.dispatchEvent(Container.java:4488)
at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2307)
at java.desktop/java.awt.Window.dispatchEventImpl(Window.java:2762)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4844)
at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:772)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:721)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:715)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:95)
at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:745)
at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:743)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:742)
at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
I am using Eclipse with WindowBuilder and Java 13.0.2.
A: I solved it 20 minutes after I posted this. The problem was with JDBC, I was using an older version. I got the new one and everything works fine now.
| |
doc_23538486
|
nav-util.js:23 invalid page component: null
This works fine for devices - I can move through the links, but for browser I am not. I mean the trouble if I manually add something in the hash. According to cordova's rules on device, I can't specify url, but in browser I can. I am trying to develop application that will work on devices and in the browser like an app.
I have this links:
const links = [
{ component: LoginPage, name: 'Login', segment: 'login', useAsDefault: true },
{ component: ContactsPage, name: 'Contacts', segment: 'contacts' },
{ component: ChangeContactPage, name: 'NewContact', segment: 'change-contact', defaultHistory: [ContactsPage] },
{ component: ChangeContactPage, name: 'ChangeContact', segment: 'change-contact/:contactId', defaultHistory: [ContactsPage] }
];
And then I have this:
imports: [
IonicModule.forRoot(App, {}, {links})
]
So here we have
**ionic info:**
Cordova CLI: 6.4.0
Ionic Framework Version: 2.0.0-rc.5
Ionic CLI Version: 2.2.1
Ionic App Lib Version: 2.2.0
Ionic App Scripts Version: 1.0.0
ios-deploy version: 1.9.0
ios-sim version: 5.0.8
OS: macOS Sierra
Node Version: v6.9.2
Xcode version: Xcode 8.2.1 Build version 8C1002
Can someone help me?
| |
doc_23538487
|
//How I want to write my loops
for(int i = 0; i < 10; i++)
{
/*Custom tab space*/
}
and not like this
//How Replit formats for loops
for (int i = 0; i < 10; i++) {
}
| |
doc_23538488
|
getTitleArea().getStyle().setPadding(0, 0, 0, 0);
getTitleArea().setVisible(false);
getTitleComponent().setVisible(false);
however it does nothing, this code worked other applications that did not target asha 1.0 platform. Is there a different way of modifying this. Have tried using lwuit resource editor as well,can change different components such as button,form background and others but still it does not change title or softbutton commands which is what I want to change.
Please help.
A: As I have said in others questions, the native header in Nokia SDK is not editable. This methods that you are using are invalid to modify the style of the header, the Nokia SDK don't get access to do that. And if you want to follow the Nokia guidelines in your app, you should keep it as the SDK gives to you.
Instead, if you still want to change this header, you can try to set your app in fullscreen and build a custom header on your own. Be careful, if you do that, you will lose the native navigation. If you want more info, take a look here in Stackoverflow, there are so many questions talking about that. In the Nokia developer forum, you can find many posts talking about that.
| |
doc_23538489
|
I tried to use gdbm but it's to slow, now i am trying to make my own solution.
I have two main ideas.
1-direct addressing. I create a big file of empty records. the ammount or empty records is twice bigger than i want to store, according this probability that index of new record (new_key%(total record in file)) is index of empty record at least equal to 1/2, If record with this index already busy the next index=hash(key)%total record in file and so far.
This approach gives me good speed of find operation. On the average I need 1.65 read record operation to find appropriate.
But it's very slow to initially fill this file because of a lot of random access operations. It can takes 4 hours.
2 - binary search. just performing parallel merge sort to create file.
But binary search takes 12 times more random read operations with random access to find appropriate record.
My applications very sensitive to speed of find operations but i need to speed up proccess of creatiing this file. Have you any ideas?
A: Assuming that you have, e.g., 1 GB of available RAM, divide the hash table into 15 pieces and partition the data by which piece of the hash table it belongs in. Then build each piece in RAM and write it out.
| |
doc_23538490
|
I tried the following code :
DateTime passexpiredate = DateTime.ParseExact(app_user.GetPasswordExpiry(empCode), "dd-MMM-yyy hh:mm tt", null);
lblPassExpiry.InnerText = "Password Expiry Date: "+passexpiredate.ToString();
A: Life is to easy using DateTime.ParseExact:
DateTime.ParseExact("12/02/21 10:56:09 AM", "yy/MM/dd HH:mm:ss tt", CultureInfo.InvariantCulture).ToString("dd-MMM-yyyy HH:mm:ss tt");
A: You've to pass the required date time format in ToString() method as mentioned below:
DateTime passexpiredate = DateTime.Parse(app_user.GetPasswordExpiry(empCode));
lblPassExpiry.InnerText = "Password Expiry Date: " + passexpiredate.ToString("dd-MMM-yyy hh:mm tt");
A: You need to make DateTime from string 6/26/2016 9:14:03 AM. And then format it to dd-mmm-yyyy hh:mm:ss am/pm
A: DateTime.ParseExact requires you to specify format exactly as it matches with string representation of datetime value. So that's not going to work for your case.
You will have to first convert string to DateTime instance and then format it while displaying.
string date = "6/26/2016 9:14:03 AM";
var dt = DateTime.Parse(date);
var dtStr = dt.ToString("dd-mmm-yyyy hh:mm:ss tt");
Console.WriteLine(dtStr); // Output: 26-14-2016 09:14:03 AM
| |
doc_23538491
|
date
address1
address2
2015-01-01
2
8
2015-01-02
3
7
2015-01-03
7
3
2015-01-04
3
1
2015-01-05
9
4
2015-01-06
3
4
I want to get 3 days average of value at each address like this
date
address1
address2
2015-01-03
4
6
2015-01-06
5
3
I have tried to extract date by every three days like d<-date[seq(1,length(date),by=3)]. I calculated the value using dat<-rowsum(df[,-1],rep(1:6,each=3)). Then divided the whole dataframe by 3 and combined d and dat.
I have tried to find rowmean works like rowsum, but did not manage to. Also, rolling means does not suit my case as it averages rows with overlapping (multiple use of rows).
Please help me to improve my method. Thanks a lot.
A: You can create group of every 3 rows and take mean of all the "address" columns -
library(dplyr)
df %>%
mutate(date = as.Date(date)) %>%
group_by(grp = ceiling(row_number()/3)) %>%
summarise(date = last(date),
across(starts_with('address'), mean, na.rm = TRUE)) %>%
select(-grp)
# date address1 address2
# <date> <dbl> <dbl>
#1 2015-01-03 4 6
#2 2015-01-06 5 3
Another option is to cut by 3 days but it will give the date of starting of the group.
df %>%
mutate(date = as.Date(date)) %>%
group_by(date = cut(date, '3 days')) %>%
summarise(across(starts_with('address'), mean, na.rm = TRUE))
A: The solutions below use the input shown reproducibly in the Note at the end. The first two use only base R. The first requires that the number of rows be a multiple of 3 but the others so not have this restriction.
1) rowsum Create a grouping vector, date, and use it in the second argument to rowsum giving the numeric matrix shown.
nr <- nrow(df)
date <- df$date[ 3 * col(matrix(0, 3, nr/3)) ]
rowsum(df[-1], date) / 3
## address1 address2
## 2015-01-03 4 6
## 2015-01-06 5 3
2) aggregate Alternately use aggregate giving a 3 column data frame.
nr <- nrow(df)
date <- ave(df$date, seq(0, length = nr) %/% 3, FUN = max)
aggregate(df[-1], data.frame(date), mean)
## date address1 address2
## 1 2015-01-03 4 6
## 2 2015-01-06 5 3
3) collap collap from the collapse package can be used in place of aggregate. date is from (2).
library(collapse)
collap(df[-1], date)
## date address1 address2
## 1 2015-01-03 4 6
## 2 2015-01-06 5 3
4) data.table Using data.table and date from (2) this returns a data.table (which is also a data frame).
library(data.table)
as.data.table(df[, -1])[, lapply(.SD, mean), by = .(date)]
## date address1 address2
## 1: 2015-01-03 4 6
## 2: 2015-01-06 5 3
Note
The input in reproducible form is:
df <-
structure(list(date = c("2015-01-01", "2015-01-02", "2015-01-03",
"2015-01-04", "2015-01-05", "2015-01-06"), address1 = c(2L, 3L,
7L, 3L, 9L, 3L), address2 = c(8L, 7L, 3L, 1L, 4L, 4L)), class = "data.frame", row.names = c(NA,
-6L))
A: Another base R option with aggregate + ave
aggregate(
. ~ date,
transform(
df,
date = ave(date, ceiling(seq_along(date) / 3), FUN = max)
),
mean
)
gives
date address1 address2
1 2015-01-03 4 6
2 2015-01-06 5 3
| |
doc_23538492
|
my @col1 = ('A', 'B', 'C', 'D');
my @col2 = ('2', '4', '6', '8');
my @col3 = ('Abc', 'Ghy', 'Tgh', 'Yth');
How would I combine these 3 arrays to be side by side so the result will look like
col1 | col2 | col3
A 2 Abc
B 4 Ghy
C 6 Tgh
D 8 Yth
A: Update
I hope it's clear how to generate a 2D array given the same function. Here it is just in case
use strict;
use warnings;
use List::MoreUtils qw/ each_array /;
my @col1 = qw/ A B C D /;
my @col2 = qw/ 2 4 6 8 /;
my @col3 = qw/ Abc Ghy Tgh Yth /;
my $iter = each_array @col1, @col2, @col3;
my @result;
while ( my @row = $iter->() ) {
push @result, \@row;
}
use Data::Dump;
dd \@result;
output
[
["A", 2, "Abc"],
["B", 4, "Ghy"],
["C", 6, "Tgh"],
["D", 8, "Yth"],
]
Or if you'd rather do it without using a non-core module then this will do as you ask
use strict;
use warnings;
use List::Util qw/ max /;
my @col1 = qw/ A B C D /;
my @col2 = qw/ 2 4 6 8 /;
my @col3 = qw/ Abc Ghy Tgh Yth /;
my @cols = \(@col1, @col2, @col3);
my @result;
for my $i ( 0 .. max map $#$_, @cols ) {
push @result, [ map $_->[$i], @cols ];
}
The resulting @result is identical
Original post
I suggest that you make use of the each_array function from List::MoreUtils. Given a list of arrays, it returns an iterator function which will hand back the next set of values from those arrays each time it is called
Here is some example code that uses your own data
use strict;
use warnings;
use List::MoreUtils qw/ each_array /;
my @col1 = qw/ A B C D /;
my @col2 = qw/ 2 4 6 8 /;
my @col3 = qw/ Abc Ghy Tgh Yth /;
my $iter = each_array @col1, @col2, @col3;
while ( my @row = $iter->() ) {
print "@row\n";
}
output
A 2 Abc
B 4 Ghy
C 6 Tgh
D 8 Yth
A: Well, one is just 'stick them together':
my @combined = ( \@col1, \@col2, \@col3);
Because your output is just a question of displaying it.
However alternatively:
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Dumper;
my @col1 = ( 'A', 'B', 'C', 'D' );
my @col2 = ( '2', '4', '6', '8' );
my @col3 = ( 'Abc', 'Ghy', 'Tgh', 'Yth' );
my @combined;
while ( @col1 or @col2 or @col3 ) {
push( @combined, [ map { shift ( @$_ ) // '' } (\@col1, \@col2, \@col3 ) ] );
}
print Dumper \@combined;
Will rotate your array, such that you can:
print join ( "|", @$_ ),"\n" for @combined;
| |
doc_23538493
|
SELECT * FROM (
SELECT DISTINCT cod_arq,
(SELECT description FROM [serverTwo].[perg].dbo.marc_section WHERE paragraph = 10 AND cod_arq = AC.cod_arq) AS author,
(SELECT description FROM [serverTwo].[perg].dbo.marc_section WHERE paragraph = 24 AND cod_arq = AC.cod_arq) AS title,
(SELECT description FROM [serverTwo].[perg].dbo.marc_section WHERE paragraph = 25 AND cod_arq = AC.cod_arq) AS edt
FROM [serverTwo].[pergamarc].dbo.marc_section AC
) AS ACN
WHERE ACN.author IS NOT NULL
AND ACN.title IS NOT NULL
I tested some sql from serverOne to serverTwo and it's ok, I can call them from one server to another.
But this sql above works just fine if I run it on the "serverTwo" (means the the sintaxe is correct), but not if I run it from the serverOne. But if I remove the DISTINCT keyword, it works (showing duplicated rows, but works).
What could be happening with this DISTINCT? Maybe some COLLATE conflict?
A: I think you just want conditional aggregation:
SELECT acn.*
FROM (SELECT ac.cod_arq,
MAX(CASE WHEN paragraph = 10 THEN description END) as author,
MAX(CASE WHEN paragraph = 24 THEN description END) as title,
MAX(CASE WHEN paragraph = 25 THEN description END) as edt
FROM [serverTwo].[pergamarc].dbo.marc_section AC
GROUP BY ac.cod_arq
) AS ACN
WHERE ACN.author IS NOT NULL AND ACN.title IS NOT NULL;
The subquery is not strictly necessary. You can use a HAVING clause instead.
| |
doc_23538494
|
All these types comes as part of a base-class (BaseResponse), that have alot of child-classes, these child-classes also includes loads of different complex-datatypes.
I would love if there was a way so I only had to implement the Parcelable on for example the child-classes, but it seems all members of classes implementing Parcelable needs to be Parcelable as well?
If the answer is something other than "No, stop being lazy" you win some of my Internets for today.
PS. These types are all auto-generated from a WSDL so I sort of wish I didn't have to edit them all manually.
DS.
Quick edit: I know of the Serializable interface but it would pose the same problem.
2nd edit: I noticed you could pass Arrays of Objects through the Intent, Im not sure if this is going to serialize it as an Object (aka with no members) or if I can just type-cast it back when I receive the Array.
Ill try it out and report back
3rd edit: The whole putting Object-arrays in the Intent wont work I guess and being lazy I'm going with the JSON-serializing option and marking it as answer (even though I havent tried it but guess it should work if a stranger on the Internet says so)
Final edit: I am now using the Json-serializing way marked as correct answer and it works just fine. There are some limitations to what objects Gson can serialize but nothing that concern me. There is probably a very in-efficient way (in terms of cpu) of doing this but the time it saved me from having to implement the interface explicitly for ~300 classes is worth it.
Thank you all for the rapid answers and suggestions, StackOverFlow is without a doubt the best community on all of history of mankind.
A: There's no other alternative I think, Else you can use Database to fill that data (if possible), and then pass its key (Table's primary key) or something to achieve it. Don't kill me if you have considered it also already! :O
A: I used GSON library to first convert my object into string(JSON string) and then put into intent extra.
And at the time of receiving it convert it back to original object.
Works fine for me but don't know if it is an efficient way of doing it.
A: Implementing Parcelable for all classes (not sure why it is a surprise to you :) is the right way of doing this on Android.
| |
doc_23538495
|
AppDomain.CurrentDomain.UnhandledException
but the app still exit in release mode. Thanks!
A: I believe that you're looking for this:
public partial class App
{
public App()
{
this.Dispatcher.UnhandledException += OnDispatcherUnhandledException;
}
private async void OnDispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
await ErrorService.HandleError(e.Exception, "An unhandled exception occurred", true, true);
e.Handled = true;
}
}
| |
doc_23538496
|
Activity1.java
public void Story1(View view) {
String link=getResources().getResourceName(R.drawable.image1of1);
Intent in = new Intent(Activity1.this,Activity2.class);
in.putExtra("image",link);
startActivity(in);
}
Activity2.java
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_story_cat1);
i1 = (ImageView) findViewById(R.id.img1);
Intent in = getIntent();
Bundle b = in.getExtras();
String img=getIntent().getStringExtra("image");
i1.setImageURI(Uri.parse(img));
}
A: Try to send id in integer form
Activity1.java
public void Story1(View view) {
int link=R.drawable.image1of1;
Intent in = new Intent(Activity1.this,Activity2.class);
in.putExtra("image",link);
startActivity(in);
}
Activity2.java
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_story_cat1);
i1 = (ImageView) findViewById(R.id.img1);
Intent in = getIntent();
Bundle b = in.getExtras();
int img=getIntent().getIntExtra("image",-1);
i1.setImageResource(img);
}
A: You need to send as byte array,
to send,
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image_name);
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] data = os.toByteArray();
Intent intent = new Intent(this, Activity2.class);
intent.putExtra("image", data);
startActivity(intent);
To receive in Activity2,
Bundle extras = getIntent().getExtras();
byte[] data = extras.getByteArray("image");
Then convert into bitmap in second activity,
Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
Finally set into imageview,
imageView.setImageBitmap(bmp);
** *Try to send and receive using id
to send,
get id using - getResources().getIdentifier(image name,"drawable", .getPackageName());
send - intent.putExtra("image",id);
to receive - intent.getIntExtra("image",-1);
get drawable - getResources().getDrawable(id_in_activity2);
then set into imageview
| |
doc_23538497
|
<div id="car" data-details='{ "color":"blue", "price":2000" }'></div>
I would like to change the property "price" using jQuery or JS:
Please check out this JSfiddle:
http://jsfiddle.net/mLuz9/
I've tried:
$("#car").attr("data-details", '{"color" : "red", "price": 5000}');
but this requires the "color" to be set at the same time, I only want to set the "price" property.
A: Pull your JSON out of the data attribute to a variable, edit the variable, and re-set the attribute with your the updated variable.
Something like this should work:
<div id="car" data-details='{ "color":"blue", "price":2000 }'></div>
// Pull the info from the data-details attribute into a variable called 'details'
var details = JSON.parse($('#car').attr('data-details'));
// Change the price property in our variable
details.price = 5000;
// Write the variable version of details back to the data-details
// attribute on the DOM element
$('#car').attr('data-details', JSON.stringify(details));
$("html").append($("#car").attr("data-details"));
An updated version of your fiddle: http://jsfiddle.net/mLuz9/3/
| |
doc_23538498
|
I've followed the instructions in the styled-components docs regarding SSR.
styled-components instructions on SSR
The page loads, prerendered, however when the javascript kicks in, instead of hydrating existing HTML, it replaces the HTML. This results in the page going blank for .3 seconds.
The example in the docs feel rather inconclusive. Here is how I tried to implement the example:
import { ServerStyleSheet } from 'styled-components';
import { h, render } from 'preact';
import { default as renderToString } from 'preact-render-to-string';
import './style'; // eslint-disable-line
import App from './components/app';
if (typeof window === undefined) {
const sheet = new ServerStyleSheet();
renderToString(sheet.collectStyles(<App />));
sheet.getStyleElement();
}
if (typeof window !== 'undefined'){
const FontLoader = require('./FontLoader').default;
// Loading fonts, defered
FontLoader();
}
export default App;
Anyone who has done this, and is willing to give some hints?
Am on preact-cli 2.2.1
A: Was able to solve it, had the initial page loaded async. Which caused the issue.
| |
doc_23538499
|
Have used serde row format to specify the quote character. and used normal row format delimiter with line delimited by Line Feed ascii as well. But as of now, none of it seems to be working.
CREATE EXTERNAL TABLE schema.ext_table
(
id varchar (18),
name varchar (80)
)
ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.OpenCSVSerde'
WITH SERDEPROPERTIES ( 'separatorChar' = ',', 'quoteChar' = '"', 'escapeChar' = '\\' )
STORED AS textfile
LOCATION 's3://path/'
TABLE PROPERTIES ('skip.header.line.count'='1')
;
For a file like this:
id,name,addCRLF
1,abc,defCRLF
2,"a,b",mnoCRLF
3,"aLF
b",xyzCRLF
Please note that the CRLF and LF, in the above file, can be seen by notepad++ like tools.
I want the output to be like:
1 abc def
2 a,b mno
3 a xyz
b-------this b need to be in the same cell as that of the a above
BUT the Output is coming like :
1 abc def
2 a,b mno
3 a null
null null null
A: Got the official response from AWS support. Redshift Spectrum doesn't support embedded line breaks in a csv file.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.