_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d19701 | test | You're looking to use $.fn.live:
$('a').live('click', function(e) {
e.preventDefault();
alert('im attached even if the DOM has been updated!');
});
http://docs.jquery.com/Events/live
A: Your question is a bit general, but I have a feeling that what you're looking for is jquery live
A: http://www.thewebsqueeze.com/tips-and-tricks/tip-for-jquery-live-event.html
http://simpable.com/code/jquery-live-events/
http://www.thefutureoftheweb.com/blog/jquery-live-events
http://kylefox.ca/blog/2009/feb/09/live-event-binding-jquery-13/ | unknown | |
d19702 | test | There is no difference in the way self-referencing loops are handled in ASP.NET 4 compared to ASP.NET Core (previously Asp.Net 5). The principles outlined in the question you referenced in your post still apply. However, setting this property in ASP.NET Core is obviously slightly different, given the new method of configuring and bootstrapping the app:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddJsonOptions(options => {
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});
services.AddEntityFramework().AddSqlServer().AddDbContext<IvoryPacketDbContext>(
options => options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"])
);
} | unknown | |
d19703 | test | Maybe:
def myfucn(vars):
vars = vars.split()
try:
float(vars[0])
if not "." in vars[0]:
raise Exception("First var should be INT not Float")
except ValueError:
print("Error not Float found")
try:
int(vars[2])
except ValueError:
print("Error Int no found")
#answer
a_float, b_str, c_int = vars
print(" Yes ")
greetings
A: You are on the right track if the split() function. The problem is that when you say that user will give three values separated by ' ', you are taking in a string.
The following is a string:
'34.44 35.45 5'
Maybe what you can do is after using split, you can cast each returned item to a variable. If you still need to check the type of variable, you can use the type() function.
Hope this helps! | unknown | |
d19704 | test | Based on your question, I'm assuming that you already have experience with WWF and are really just asking about how it interacts with Silverlight. The short answer is that it would not be noticeably different from how you would implement a WWF-enabled application in traditional ASP.NET. Remember that Silverlight is only a UI client that usually lives on top of a traditional ASP.NET web application. Your WWF-related logic and code would live in the ASP.NET layer -- not in Silverlight at all.
So if you already know how to make a WWF-enabled application in ASP.NET, all you really need to learn is how to wire up a shiny Silverlight interface to an ASP.NET web app. For that, you of course only need to hit up http://silverlight.net/, which you're probably already doing.
Good luck! | unknown | |
d19705 | test | Answering my own question
it looks like I should have imported by output name not output export name, which is bit weird and all the docs I have seen point to export name, but this is how I was able to make it work
replaced this -
authorizerId:${myAppservices-${self:provider.stage}.ExtApiGatewayAuthorizer-${self:provider.stage}}
with -
authorizerId: ${myApp-services-${self:provider.stage}.ApiGatewayAuthorizerId}
A: If you come across Trying to request a non exported variable from CloudFormation. Stack name: "myApp-services-test" Requested variable: "ExtApiGatewayAuthorizer-test"., when exporting profile i.e.,
export AWS_PROFILE=your_profile
It must be done on the terminal window where you are doing sls deploy not on another terminal window. It is a silly mistake but I don't want anyone else waste their time around that | unknown | |
d19706 | test | I don’t know what microcontroller you’re using, but sometimes printf use interrupts to send characters through the UART and the like, if you make it a critical section that means the interrupt will never fire. Comment out the critical section lines to see if that’s the case.
Another possibility is that you have the MPU (memory protection unit) enabled, and it is not allowing access to the NVIC registers from a user task. AFAIK FreeRTOS has support for the MPU in Cortex-M microcontrollers, check if that is enabled in your case. | unknown | |
d19707 | test | Try:
$file = file_get_contents($url);
$only_body = preg_replace("/.*<body[^>]*>|<\/body>.*/si", "", $file); | unknown | |
d19708 | test | The error itself is quite self-explainatory, the server is trying to send some headers but some output has already started.
The warnings at start of the page are very likely to be generated from the PHP interpreter on your machine, either you have a weird display_errors directive in your php.ini or the constant WP_DEBUG on your wp-config.php is set to true.
Double check both configuration files and make sure the display of the errors are set to off and WP_DEBUG to false. | unknown | |
d19709 | test | I also faced the same issue. For future people, make sure you have made the bucket
public. From the same method you can also generate thumbnails and secured urls to your images
public static String getImageURL(String inFilename) {
String key = "/gs/" + BUCKETNAME + "/" + inFilename;
ImagesService imagesService = ImagesServiceFactory.getImagesService();
ServingUrlOptions options = ServingUrlOptions.Builder
.withGoogleStorageFileName(key).imageSize(150).secureUrl(true);
String servingUrl = imagesService.getServingUrl(options);
return servingUrl;
} | unknown | |
d19710 | test | No one can know how to cheat on Content ID
Obviously, as Content ID is a private algorithm developed by Google, no one can know for sure how do they detect copyrighted audio in a video.
But, we can assume that one of the first things they did was to make their algorithm pitch-independent. Otherwise, everyone would change the pitch of their videos and cheat on Content ID easily.
How to use Youtube to get your subtitles anyway
If I am not mistaken, Content ID blocks you because of musical content, rather than vocal content. Thus, to address your original problem, one solution would be to detect musical content (based on spectral analysis) and cut it from the original audio. If the problem is with pure vocal content as well, you could try to filter it heavily and that might work.
Other solutions
Youtube being made by Google, why not using directly the Speech API that Google offers and which most likely perform audio transcription on Youtube? And if results are not satisfying, you could try other services (IBM, Microsoft, Amazon and others have theirs). | unknown | |
d19711 | test | You can use indexing with str with zfill:
df = pd.DataFrame({'FLIGHT':['KL744','BE1013']})
df['a'] = df['FLIGHT'].str[:2]
df['b'] = df['FLIGHT'].str[2:].str.zfill(4)
print (df)
FLIGHT a b
0 KL744 KL 0744
1 BE1013 BE 1013
I believe in your code need:
df2 = pd.DataFrame(datatable,columns = cols)
df2['a'] = df2['FLIGHT'].str[:2]
df2['b'] = df2['FLIGHT'].str[2:].str.zfill(4)
df2["UPLOAD_TIME"] = datetime.now()
...
... | unknown | |
d19712 | test | The fragment you sent is actually an incomplete XML fragment. It's lacking for instance the closing </Policy> element.
The fragment you sent corresponds to a XACML 3.0 policy. This means that before you close the policy you should also have 1 or more rules (technically the schema does allow zero rules but that doesn't make sense).
To marshall and unmarshall using JAX-B, you need to use the XACML 3.0 schema which you can find here. It's pretty straightforward to configure JAXB to create the Java objects based on that schema. You'll need to create a simple XJB file to configure the marshalling.
That said, considering there are several XACML engines out there (both open source and vendor such as the one I work for, Axiomatics), what's your rationale for implementing a XACML parser yourself?
Cheers,
David. | unknown | |
d19713 | test | If you import
import parser
then you have to use parser.Sentence()
myarg = parser.Sentence('let us kill the bear')
If you import
from parser import Sentence
then you can use Sentence()
myarg = Sentence('let us kill the bear')
Python first looks for file in "current working directory" ("cwd"). If you run code in different folder then it can import from library module with the same name instead of your file.
You can check what file was imported
import parser
print(parser.__file__)
To check current working directory
import os
print(os.getcwd()) | unknown | |
d19714 | test | It's basically the same way to convert Java Object to XML with JAXBContext and Marshaller with an addition of validation the XML validation with DTD.
See the sample code:
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
JAXBContext jc = JAXBContext.newInstance("blog.log4j");
Unmarshaller unmarshaller = jc.createUnmarshaller();
UnmarshallerHandler unmarshallerHandler = unmarshaller.getUnmarshallerHandler();
xr.setContentHandler(unmarshallerHandler);
FileInputStream xmlStream = new FileInputStream("src/blog/log4j/sample1.xml");
InputSource xmlSource = new InputSource(xmlStream);
xr.parse(xmlSource);
Log4JConfiguration config = (Log4JConfiguration) unmarshallerHandler.getResult();
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(config, System.out);
Source.
A: First you need to serialize object to xml, then you need validate id against dtd.
Here
you have example how to serialzie classes to xml.
This one shows how to validate xml file with dtd that is outside or inside xml file. | unknown | |
d19715 | test | You have made a couple of mistakes in the line that calculates the mean. The most significant one is that when you try to calculate the mean for the last 9 rows of your dataframe, you go out of bounds. ie, if your dataframe has 100 rows, by row 92 your are trying to get the mean of rows 92:101; of course, there is no row 101.
It should be something like this:
for(i in 1: length(data[ , 5]-9)) {
data$Mean [i] <- mean(data[i:min(i+9, nrow(data)),5])
}
Also, it's generally a bad idea to use data as a variable name, since there already is a data() function in base R. Simply choose a similar name, like "mydata"
A reproducible example follows, that will get the mean of the next ten rows, OR the mean of the n next rows for the last 9 rows.
mydata <- data.frame(col_1 = rnorm(100),
col_2 = rnorm(100),
col_3 = rnorm(100),
col_4 = rnorm(100),
col_5 = rnorm(100))
for(i in 1: length(mydata[ , 5]-9)) {
mydata$Mean [i] <- mean(mydata[i:min(i+9, nrow(mydata)),5])
}
head(mydata)
If you dont' want to get the mean for the last ten rows, do this instead:
for(i in 1: length(mydata[ , 5]-9)) {
mydata$Mean [i] <- ifelse( i + 9 <= nrow(mydata),
mean(mydata[i:min(i+9, nrow(mydata)),5]),
NA)
} | unknown | |
d19716 | test | consul kv put -release -session=sessionid my-key-value | unknown | |
d19717 | test | The sqlSchemaManagementEnabled switch is managed by the JaVers Spring Boot starter, see https://javers.org/documentation/spring-boot-integration/
If you don't use the starter the switch won't be read, but still you can set this switch when building a Javers instance:
def javers = JaversBuilder.javers()
.registerJaversRepository(sqlRepository()
.withConnectionProvider({ DriverManager.getConnection("jdbc:h2:mem:empty-test") } as ConnectionProvider)
.withSchemaManagementEnabled(false)
.withDialect(getDialect())
.build()).build() | unknown | |
d19718 | test | Your query is almost certainly related to table corruption in MyISAM.
I did
root@localhost [kris]> create table crawler (
id integer not null auto_increment primary key,
provider_id int(11) DEFAULT NULL,
PRIMARY KEY (id),
KEY crawler_provider_id (provider_id)
) engine = myisam;
root@localhost [kris]> insert into crawler ( id, provider_id ) values ( NULL, 1 );</code>
and then repeated
root@localhost [kris]> insert into crawler ( id, provider_id)
select NULL, rand() * 120000 from crawler;
until I had
root@localhost [kris]> select count(*) from crawler;
+----------+
| count(*) |
+----------+
| 524288 |
+----------+
1 row in set (0.00 sec)
I now have
root@localhost [kris]> SELECT COUNT(*) FROM `crawler` WHERE `crawler`.`provider_id` > 1371;
+----------+
| COUNT(*) |
+----------+
| 518389 |
+----------+
1 row in set (0.27 sec)
which is somewhat comparable in size to what you gave in your example above. I do get two different plans for the query with and without a LIMIT clause.
Without a LIMIT clause I get a full table scan (ALL) not using any index:
root@localhost [kris]> explain SELECT `crawler`.`id` FROM `crawler` WHERE `crawler`.`provider_id` > 1371\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: crawler
type: ALL
possible_keys: crawler_provider_id
key: NULL
key_len: NULL
ref: NULL
rows: 524288
Extra: Using where
1 row in set (0.00 sec)
With the LIMIT clause, the INDEX is used for a RANGE access
root@localhost [kris]> explain SELECT `crawler`.`id` FROM `crawler` WHERE `crawler`.`provider_id` > 1371 LIMIT 10\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: crawler
type: range
possible_keys: crawler_provider_id
key: crawler_provider_id
key_len: 5
ref: NULL
rows: 518136
Extra: Using where
1 row in set (0.00 sec)
In your example, without the LIMIT clause (full table scan) you get no data, but with the LIMIT clause (range access using index) you get data. That points to a corrupted MYD file.
ALTER TABLE, as REPAIR TABLE or OPTIMIZE TABLE, will normally copy the data and the kept indexes from the source table to a hidden new version of the table in a new format. When completed, the hidden new table will replace the old version of the table (which will be renamed to a hidden name, and then dropped).
That is, by dropping the indexes you effectively repaired the table.
A: Maybe you can delete and recreate the index, and after that repair or optimize the table so all indices get rebuilt. That may help you. And look at your configuration to see if the memory settings are appropriate. | unknown | |
d19719 | test | 1 . 1
2 . .
. . 4
ColSums would look like:
3 . 5
RowSums would look like:
2
2
4
I would like to iterate over A and do this
(1,1) > 3*2
(2,1) > 2*3
(1,3) > 2*5
(3,3) > 4*5
Creating B:
6 . 10
6 . .
. . 20
How would I go about doing this in a vectorized way?
I would think the function foo would look like:
B=fooMap(A,fun)
And fun would look like:
fun(row,col) = RowSums(row) * ColSums(col)
What's fooMap?
EDIT:
I went with flodel's solution. It uses summary to convert the sparse matrix into an i,j,x data frame, then uses with & friends to perform an operation on that frame, and then turns the result back into a sparse matrix. With this technique, the with/within operator is fooMap; the sparse matrix just has to be converted into the i,j,x data frame first so that with/within can be used.
Here's a one-liner that solved this particular problem.
B = with(summary(A), sparseMatrix(i=i, j=j, x = rowSums(A)[i] * colSums(A)[j]))
A: Whenever I have element-wise operations on sparse matrices, I go back and forth between the matrix itself and its summary representation:
summ.B <- summary(A)
summ.B <- within(summ.B, x <- rowSums(A)[i]*colSums(A)[j])
B <- sparseMatrix(i = summ.B$i, j = summ.B$j, x = summ.B$x)
B
# 3 x 3 sparse Matrix of class "dgCMatrix"
#
# [1,] 6 . 10
# [2,] 6 . .
# [3,] . . 20
A: Here's an approach that works with sparse matrices at each step.
## Load library and create example sparse matrix
library(Matrix)
m <- sparseMatrix(i = c(1,2,1,3), j = c(1,1,3,3), x = c(1,2,1,4))
## Multiply each cell by its respective row and column sums.
Diagonal(x = rowSums(m)) %*% (1*(m!=0)) %*% Diagonal(x = colSums(m))
# 3 x 3 sparse Matrix of class "dgCMatrix"
#
# [1,] 6 . 10
# [2,] 6 . .
# [3,] . . 20
(The 1* in (1*(m!=0)) is being used to coerce the logical matrix of class "lgCMatrix" produced by m!=0 back to a numeric matrix class "dgCMatrix". A longer-winded (but perhaps clearer) alternative would to use as(m!=0, "dgCMatrix") in its place.) | unknown | |
d19720 | test | Well the problem is you are binding a Enum to a string, this will only work one way due to the default ToString operation in the binding engine.
If you are only using the string value change your ObjectDataProvider method name to GetNames this will return the string values for your Enum and will bind both ways, the other option is to not bind to a string but the Enum type.
<ObjectDataProvider x:Key="Currencies" MethodName="GetNames" ObjectType="{x:Type System:Enum}">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="ConfigManager:CurrenciesEnum" />
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
A: I load the enum into a Dictionary
public static Dictionary<T, string> EnumToDictionary<T>()
where T : struct
{
Type enumType = typeof(T);
// Can't use generic type constraints on value types,
// so have to do check like this
if (enumType.BaseType != typeof(Enum))
throw new ArgumentException("T must be of type System.Enum");
Dictionary<T, string> enumDL = new Dictionary<T, string>();
//foreach (byte i in Enum.GetValues(enumType))
//{
// enumDL.Add((T)Enum.ToObject(enumType, i), Enum.GetName(enumType, i));
//}
foreach (T val in Enum.GetValues(enumType))
{
enumDL.Add(val, val.ToString());
}
return enumDL;
} | unknown | |
d19721 | test | Have your /folder/app/.htaccess like this:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /folder/app/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/$1 [L]
</IfModule>
then in /folder/app/application/config/config.php you need to have this config:
$config['base_url'] = '';
$config['index_page'] = '';
$config['uri_protocol'] = 'AUTO'; | unknown | |
d19722 | test | Instead of insert(Mono.just(batchDetailEntity))
put insert(batchDetailEntity) It may work for you. | unknown | |
d19723 | test | Find: else if
Replace: \r\nelse if
Search Mode: Extended
A: Have a try with:
Find what: (\belse if\b)
Replace with: \n$1 | unknown | |
d19724 | test | Your PizzaSet class is using a List of Enums, which will not map to a database schema in EF.
If you want to use an enum for Sauces and Toppings and want to allow multiple selections, you need to use the [Flags] property for the enum, to treat it as a bit field.
public class PizzaSet
{
[Flags]
public enum Toppings { GreenOlives = 1, BulgarianCheese = 2, Onions = 4, Mushrooms = 8, Peppers = 16, Basil = 32, Sausage = 64, Pepperoni = 128, Ham = 256, Beef = 512 }
[Flags]
public enum Sauces { BBQ = 1, Islands = 2 }
public enum Size { Personal, Medium, Family }
public Size PizzaSize { get; set; }
public Sauces PizzaSauces { get; set; }
public Toppings PizzaToppings { get; set; }
}
Then Toppings and Sauces become a bit field of possible values (notice the values will need to represent unique bits)
To select multiple toppings:-
PizzaSet ps = new PizzaSet();
ps.Toppings = Toppings.GreenOlives | Toppings.Peppers;
However, given your list of toppings and sauces may change over time, it's probably better to have a separate table that lists toppings, and use a join table (since it's EF Core)
A: You have enums as your list type.
If youre storing this data in a database. The database needs a placeholder to store the enum values.
In general this is done by a table.
So, if you make classes of your enums, these will be translated to tables and the mapping will work.
public class Topping
{
public string Name {get;set;}
}
Use this class as your list type.
Do note that you need to fill the topping, sauces and etc. tables. The good news is: you can extend them without changing the code :-)
Alternatively, you can put the
[NotMapped]
attribute on your property. Do note that this won't help you in your specific case because it would not store the toppings in the database then. | unknown | |
d19725 | test | As I understand this is not a client-server application, but rather an application that has a common remote storage.
One idea would be to change to web services (this would solve most of your problems on the long run).
Another idea (if you don't want to switch to web) is to refresh periodically the data in your interface by using a timer.
Another way (and more complicated) would be to have a server that receives all the updates, stores them in the database and then pushes the changes to the other connected clients.
The first 2 ideas you mentioned will have maintenance, scalability and design uglyness issues.
The last 2 are a lot better in my opinion, but I still stick to web services as being the best. | unknown | |
d19726 | test | You can mock the whole Consumer
*
*Make sure Consumer is the default export of its file
import Consumer from './consumer';
///...
jest.mock('./consumer'); // SoundPlayer is now a mock constructor
beforeEach(() => {
// Clear all instances and calls to the constructor and all methods:
Consumer.mockClear();
});
/// Your tests
More details:
https://jestjs.io/docs/es6-class-mocks | unknown | |
d19727 | test | One option is to edit the @page directive in the Index.cshtml and Home.cshtml files to configure the routes:
/* Home.cshtml.cs */
@page "/"
/* Index.cshtml.cs */
@page "/Index"
This applies explicit routes for the two pages, so that the Home Razor Pages page becomes the root page, and the Index page maps only to /Index.
Note that with this approach, the call to AddPageRoute shown in your question is not needed. | unknown | |
d19728 | test | You're trying to use a dictionary like an array, which doesn't work (obviously). You should not count on a fixed order for [self.personen allKeys], it can change at any point during runtime, which would result in the wrong person being passed along.
You need to use a mutable array as your storage vessel for people names, then address them by the row of the index path.
A: First of all you need to use NSmutablearray to save data of people so make sure that self.personen is an NSmutablearray then you need just to use ObjectAtindex function to get the selected row .
vcGevensView.persoon=[self.personen objectAtIndex:indexPath.row]; | unknown | |
d19729 | test | When you do a LEFT JOIN, you are taking all the rows from the first table and if there are no matches for the first join condition, the resulting records for table x will be a NULL record which is why you're using the AND operator 'c.name IS NULL' but I think you have some issues with your query. It's been a while for me so I'm trying not to make an error here but you don't appear to have a table name in your FROM clause and your select can't be in the from clause (i don't think)...maybe I'm wrong but I had to clean up the statement to understand what you are doing better...so please clarify and I can improve my answer.
SELECT
[a].[date] AS 'Date'
,[b].[amt] AS 'Amount'
,[b].[code] AS 'Code'
,[c].[type] AS 'Type'
FROM [table].[name] (NOLOCK)
LEFT JOIN [table].[name] (NOLOCK) date ON [c].[date] = [b].[date]
LEFT JOIN [table].[name] (NOLOCK) name ON [c].[name] = [b].[name]
WHERE (SELECT date
FROM [t]
WHERE DATEADD (hh,-6, DATEADD (ss,[table].[name],'1970')) BETWEEN '2017-04-01' AND '2018-09-30')
AND [a].[date] = [b].[date] //Not sure if this is what you meant
AND [a].[name] = [b].[name]
AND [c].[name] IS NULL
GROUP BY [a].[date],[b].[amt],[b].[code],[c].[type]
A: With some guesswork involved, I could imagine you want:
SELECT DISTINCT
t.date,
b.amt,
b.code,
c.type
FROM t
LEFT JOIN b
ON b.date = t.date
AND b.name = t.name
LEFT JOIN c
ON c.date = b.date
AND (c.name = b.name
OR c.name is null)
WHERE t.date BETWEEN '2017-04-01'
AND '2018-09-30';
*
*Your subquery from t isn't really needed, that check on date can be moved in the WHERE clause. But it wasn't strictly wrong. It depends on what the optimizer makes of it what's better.
*Though your GROUP BY has the same effect, I changed it to a DISTINCT, which might be more clear to understand at a glance.
*And I'm not sure about your join condition for c.
*
*I guessed you want the date to match but allow c.name to be null if it doesn't match. That means you have to use parenthesis to counter the higher precedence of AND over OR.
*You probably want to change the b.s in the join condition to t.s, if record from c should also be added if no matching record from b exists for a record from t. Like it is right now, no record from c is joined for a record from t without a matching record from b. | unknown | |
d19730 | test | Your mistake is a simple one - you are setting propagateChange in both registerOnChange and registerOnTouched. Instead, assign to onTouch in registerOnTouched.
registerOnTouched(fn: any): void {
this.onTouch = fn;
}
registerOnTouched is getting called after registerOnChange by the framework, so you are emitting touch events when you are intending to emit change events.
DEMO https://stackblitz.com/edit/angular-ve8sri | unknown | |
d19731 | test | One of possible solution is transliteration Cyrillic text into Latin analog. It works but it far from expected results (words pronounces not as good as can be).
var transliterate = function(word) {
var a = { "Ё": "YO", "Й": "I", "Ц": "TS", "У": "U", "К": "K", "Е": "E", "Н": "N", "Г": "G", "Ш": "SH", "Щ": "SCH", "З": "Z", "Х": "H", "Ъ": "'", "ё": "yo", "й": "i", "ц": "ts", "у": "u", "к": "k", "е": "e", "н": "n", "г": "g", "ш": "sh", "щ": "sch", "з": "z", "х": "h", "ъ": "'", "Ф": "F", "Ы": "I", "В": "V", "А": "a", "П": "P", "Р": "R", "О": "O", "Л": "L", "Д": "D", "Ж": "ZH", "Э": "E", "ф": "f", "ы": "i", "в": "v", "а": "a", "п": "p", "р": "r", "о": "o", "л": "l", "д": "d", "ж": "zh", "э": "e", "Я": "Ya", "Ч": "CH", "С": "S", "М": "M", "И": "yi", "Т": "T", "Ь": "'", "Б": "B", "Ю": "YU", "я": "ya", "ч": "ch", "с": "s", "м": "m", "и": "yi", "т": "t", "ь": "'", "б": "b", "ю": "yu" };
return word.split('').map(function(char) {
return a[char] || char;
}).join("");
}
var sayWin = (text) => {
text = /[а-яА-ЯЁё]/.test(text) ? transliterate(text) : text;
var shell = new Shell({
inputEncoding: 'binary'
});
shell.addCommand('Add-Type -AssemblyName System.speech');
shell.addCommand('$speak = New-Object System.Speech.Synthesis.SpeechSynthesizer');
shell.addCommand('$speak.Speak("' + text + '")');
shell.on('output', data => {
console.log("data", data);
});
shell.on('err', err => {
console.log("err", err);
});
shell.on('end', code => {
console.log("code", code);
});
return shell.invoke().then(output => {
shell.dispose()
});
}
A: I may be answering too late, but let it stay here for the future.
I solved this problem for myself by first calling the command:
$OutputEncoding = [console]::InputEncoding = [console]::OutputEncoding = New-Object System.Text.UTF8Encoding;
In your case, it will be something like
shell.addCommand('$OutputEncoding = [console]::InputEncoding = [console]::OutputEncoding = New-Object System.Text.UTF8Encoding'); | unknown | |
d19732 | test | Maybe you could bind drag-content directive to a scope variable (boolean) and then change its value when mouse is over the calendar component:
<ion-side-menu-content drag-content="drag">
So register the listeners for mouseover/mouseleave events on calendar:
<flex-calendar on-touch="mouseoverCalendar()" on-release="mouseleaveCalendar()" drag-content="toggledrag" options="options" events="events"></flex-calendar>
and insert in your controller:
$scope.drag = true;
$scope.mouseoverCalendar = function() {
$scope.drag = false;
};
$scope.mouseleaveCalendar = function() {
$scope.drag = true;
};
Here is an example using Flex Calendar: http://codepen.io/beaver71/pen/bEmaJZ
A: Put this into the controller of your calendar-view and it will the menu as you enter the calendar and re-enable it as you leave the view:
$scope.$on('$ionicView.enter', function(){
$ionicSideMenuDelegate.canDragContent(false);
});
$scope.$on('$ionicView.leave', function(){
$ionicSideMenuDelegate.canDragContent(true);
});
Answer from this post | unknown | |
d19733 | test | It should simply look like a comma separated values ["aaaaa","bbbb","ccccc"]
That is Set[String], but what you have is Set[Type]. Jackson is doing exactly what it's supposed to do. You need to change your class signature to:
case class Genre(name: String, types: Set[String])
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
object TestObject {
def main(args: Array[String]): Unit = {
val mapper = new ObjectMapper()
mapper.registerModule(DefaultScalaModule)
val genre = Genre("xxxxxx", Set(new Type("aaaaa"), new Type("bbbb"), new Type("ccccc")))
println("Genre: " + mapper.writeValueAsString(genre))
val anotherGenre = AnotherGenre("xxxxxx", Set("aaaaa", "bbbb", "ccccc"))
println("AnotherGenre: " + mapper.writeValueAsString(anotherGenre))
}
}
class Type(val value: String) extends AnyVal
case class Genre(name: String, types: Set[Type])
case class AnotherGenre(name: String, types: Set[String])
Output:
Genre: {"name":"xxxxxx","types":[{"value":"aaaaa"},{"value":"bbbb"},{"value":"ccccc"}]}
AnotherGenre: {"name":"xxxxxx","types":["aaaaa","bbbb","ccccc"]} | unknown | |
d19734 | test | The lines that set your circle centre are wrong. They should read:
myCircle.setAttributeNS(null,"cx", svgX);
myCircle.setAttributeNS(null,"cy", svgY);
Ie. remove the quotes on the variables. | unknown | |
d19735 | test | The method has_object_permission() returns True or False depending in the evaluation of obj.owner == request.user | unknown | |
d19736 | test | Not necessarily.
One way of doing this is to set SelectedItem property in the datagrid xaml to a property on your view model which implements INotifyPropertyChanged.
Then set the xaml binding mode to two way.
Then if you click on a selected item it will trigger a change from the xaml binding to update the value in the view model | unknown | |
d19737 | test | Why don't you use order by clause:
SELECT * FROM table ORDER BY column;
Order By Reference
A: You can modified your query as below for sorting:
sql > select * from <table name> order by <column name>;
default sorting is ascending order else for descending you can do like
sql > select * from <table name> order by <column name> desc;
A: If you could use JQuery, it's very simple, you have just to add the following javascript code:
$( document ).ready(function() {
$("#responsive_table").DataTable({
ordering: true,
searching: true
});
});
for a complete example see the following code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css">
<script>
$( document ).ready(function() {
$("#responsive_table").DataTable({
ordering: true,
searching: true
});
});
</script>
</head>
<body>
<form method='post' action=''>
<div style="height: auto">
<table id='responsive_table'>
<thead>
<tr>
<th scope="col">name</th>
<th scope="col">sex</th>
<th scope="col">user group</th>
<th scope="col">date register</th>
</tr>
</thead>
<tbody>
<tr>
<td scope="row" data-label='name'>HERE</td>
<td data-label='sex'>Your</td>
<td data-label='user group'>data</td>
<td data-label='date register'>loaded</td>
</tr>
<tr>
<td scope="row" data-label='name'>via</td>
<td data-label='sex'>PHP</td>
<td data-label='user group'>loop</td>
<td data-label='date register'>bye</td>
</tr>
</tbody>
</table>
</div>
</form>
</body>
</html> | unknown | |
d19738 | test | As you gave no possibility to test, this is kind of a guessing game. What you do is the following:
$('[id^=matrix-box]').on({ mouseenter: function(){});
This adds a new event listener on each element with an id starting with matrix-box. Not the worst idea, but it can be slow if you have a lof of these items.
Here is demo to validate this: http://jsfiddle.net/k3mjmdzp/3/
A good idea to overcome performance issues is to use a delegated event listener.
Try to rewrite your code like this:
$(function () {
$('#matrix').on('mouseenter mouseleave click', '[id^=matrix-box]', function (event) {
console.log(event);
});
});
Here you have the demo: http://jsfiddle.net/k3mjmdzp/2/
This will leave your code with having only event listeners on $('#matrix') and not on each child node. This is also nice if you append new items via ajax later on.
You can check for event listeners on the event Listeners tab in chrome developer tools. | unknown | |
d19739 | test | You can change the class .input-field, and add more specific selector, for example:
.input-field input
or to email type of input
.input-field input[type=email]
or to focused field:
.input-field input[type=text]:focus
And set the border style:
.input-field input[type=text]:focus{
border-bottom: 1px solid #aaa;
}
You can read more in Materialize documentation: http://materializecss.com/forms.html
EDIT: edited as suggested by @Toby1Kenobi
A: According to the docs you can change the underline colour in CSS by modifying the colour of border-bottom and box-shadow of the element containing the input element (that is the one with the class input-field)
so maybe it would be something like this:
.input-field input[type=email] {
border-bottom: 1px solid red;
box-shadow: 0 1px 0 0 red;
} | unknown | |
d19740 | test | As an example of a use case where a constructor could want access to static members is when a static field contains a counter of instances for a class. You may want a class member to get, retain (in a non-static field), and increment this counter which would be static. Any time in the future that instance will have its own unique identifier.
Example:
public class Employee {
static int NextEmployeeId; // a counter across all employees
public int EmployeeId; // this instance's employee id
public string Name; // this instance's name.
static Employee() {
Employee.NextEmployeeId = 1; // first employee gets 1.
}
public Employee(string Name) {
this.Name = Name;
this.EmployeeId = Employee.NextEmployeeId++; // take an id and increment for the next employee
}
}
A: Static fields are accessible from everywhere, even from constructor, or even from Main/other class. The purpose is that you will have only one static property/ field singleton for the whole app.
public class AClass()
{
public static float staticField;
public float field;
public AClass()
{
staticField = 5;
field = 6;
}
static AClass()
{
staticField = 7;
}
}
public int Main()
{
float initially = AClass.staticField; // initially this staticField is 7.
AClass aclass = new AClass(); // instantiating AClass
float localfield = aclass.field; // this field does not affect anyone. It is 6
float newStaticField = AClass.staticField; // Due to previous instantiation, the value is now 5.
}
And I agree with you that in your example it is bad. Why? Because why would you change the value of Pi, since it is already determined and fixed, there is no reason to change the value of Pi in the constructor.
You probably need to know how to design class and get to know why you want to have the static field in the first place. Here is an example of a class which does it correctly having a static field (sort of... for example, because the Key should be hidden supposedly. This is just to show you how static field is useful and ok.):
public class NewEncryptionClass()
{
public static string Key;
public NewEncryptionClass()
{
}
public NewEncryptionClass(string newKey)
{
Key = newKey; // store the key and keep it forever
}
static NewEncryptionClass()
{
Key = "key1"; // initially key is "key1"
}
public string Encrypt(string str)
{
string result = string.Empty;
result = "adlasdjalskd" + Key + "ajlajfalkjfa" + str; // do the Encryption, I just made up
return result
}
}
Here, the purpose is that if you instantiate a NewEncryptionClass, you would want to save the key, so that the next time you do the encryption, you would always use the latest key without having to specify it everytime. For ex:
public int Main()
{
string initialkey = NewEncryptionClass.Key;
string result1 = new EncryptionClass().Encrypt("encryptThis"); // using key1
// let's change the key
string result2 = new EncryptionClass("key2").Encrypt("encryptThat"); // using key2
string result3 = new EncryptionClass().Encrypt("encryptOther"); // still using key2
}
This is of course if I want to keep the latest key forever, if not, then this class design is wrong and you need to rewrite it for your purpose. | unknown | |
d19741 | test | You can use a regular expression like this:
function replaceLetter(str) {
return str.replace(/a/g, 'o');
}
var st = replaceLetter('hahaha');
console.log(st);
Or use another string to accumulate the result like this:
function replaceLetter(str) {
var res = ''; // the accumulator (because string litterals are immutable). It should be initialized to empty string
for(var i = 0; i < str.length; i++) {
var c = str.charAt(i); // get the current character c at index i
if(c == 'a') res += 'o'; // if the character is 'a' then replace it in res with 'o'
else res += c; // otherwise (if it is not 'a') leave c as it is
}
return res;
}
var st = replaceLetter('hahaha');
console.log(st);
A: I always like using split() and join()
var string = "assassination";
var newString = string.split("a").join("o");
A: Strings in Javascript are immutable, and thus any changes to them aren't going to be reflected as you might expect.
Consider just using the string.replace() function instead:
function replaceLetter(string){
// This uses a regular expression to replace all 'a' characters with 'o'
// characters (the /g flag indicates that all should be matched)
return string.replace(/a/g,'o');
}
A: Assuming you want to use a for loop:
function replaceLetter(string){
var result = '';
for (var i = 0; i < string.length; i++) {
result += string[i] === 'a' ? 'o' : string[i];
}
return result;
}
You have to build a new string like this, because as mentioned in a comment, strings are immutable. You can write string[4] = 'b' and it won't cause an error, but it won't do anything either.
It's probably overkill, but you could use reduce, which does the looping internally and maintains the result variable:
const replaceLetter = string =>
[...string].reduce((result, chr) =>
result += (chr === 'a' ? 'o' : chr), '');
However, for this particular case, the regexp solution shown in other answers is probably preferable. | unknown | |
d19742 | test | The JsonPath operator [?(<expression>)] selects all elements matching the given expression. Therefore, the result is a json array.
In the example [?(@.Wert == '')] matches all json nodes with the field Wert having an empty value. Your json sample has only single item matching the predicate, but in general there could be multiple. To fix you have either to define a more specific expression matching only a single element or to adjust the matcher to work on a collection.
Matching collection:
.andExpect(jsonPath("$..[?(@.Wert == '')].Anzahl", everyItem(greaterThan(400)))) | unknown | |
d19743 | test | Looks like this is a known issue/intended. See below:
After further investigation and discussion with the S3 team, I have found that this is expected behavior due to the design of the service. The GET Service call in S3 (s3api list-buckets or s3 ls with no further arguments in the CLI) works differently when being run against different regions. All bucket creations are mastered in us-east-1, then replicated on a global scale - the resulting difference is that there are no "replication" events to the us-east-1 region. The Date Created field displayed in the web console is according to the actual creation date registered in us-east-1, while the AWS CLI and SDKs will display the creation date depending on the specified region (or the default region set in your configuration).
When using an endpoint other than us-east-1, the CreationDate you receive is actually the last modified time according to the bucket's last replication time in this region. This date can change when making changes to your bucket, such as editing its bucket policy. This experienced behavior is result of how S3's architecture has been designed and implemented, making it difficult to change without affecting customers that already expect this behavior.
S3 does intend to change this behavior so that the actual bucket creation date is shown regardless of the region in which the GET Service call is issued, however to answer your question we do not yet have an ETA for the implementation of this change. This change would most likely be announced in the AWS Forums for S3 if you'd like to know when it takes place.
Source | unknown | |
d19744 | test | yes, you can use CSS3 Media Queries without using JavaScript.
@media screen and (max-width: 450px) {
img {
width: 30%;
}
}
http://webdesignerwall.com/tutorials/responsive-design-with-css3-media-queries
A: Try this:
@media screen and (orientation:portrait) {
//your css code goes here
}
@media screen and (orientation:landscape) {
//your css code goes here
} | unknown | |
d19745 | test | If directive can be used to provide a condition for the handler to be added only for files matching the pattern in the current folder.
The following example will add the handler for only files in the document root, such as /sitemap.xml and /opensearch.xml but not for /folder/sitemap.xml and /folder/opensearch.xml
<FilesMatch ^(opensearch|sitemap)\.xml$>
<If "%{REQUEST_URI} =~ m#^\/(opensearch|sitemap)\.xml$#">
AddHandler application/x-httpd-php .xml
</If>
</FilesMatch>
In the above example, the condition is checking that the REQUEST_URI matches the regex pattern delimited in m# #.
The ~= comparison operator checks that a string match a regular expression.
The pattern ^\/(opensearch|sitemap)\.xml$ matches REQUEST_URI variable (the path component of the requested URI) such as /opensearch.xml or /sitemap.xml
^ # startwith
\/ # escaped forward-slash
(opensearch|sitemap) # "opensearch" or "sitemap"
\. # .
xml # xml
$ # endwith
A: Have you tried H= in a RewriteRule?
RewriteEngine On
RewriteRule ^(opensearch|sitemap)\.xml$ . [H=application/x-httpd-php5]
Rewrite in htaccess has the built-in property that those filenames in any subdir will have the subdir present in the string the regex tests against so the anchored regex will not match in subdirs. | unknown | |
d19746 | test | Use __FILE__ or __DIR__ or dirname(__FILE__)
http://www.php.net/manual/en/language.constants.predefined.php
A: $argv[0] will always contain the name of the script: http://www.php.net/manual/en/reserved.variables.argv.php | unknown | |
d19747 | test | I would try to add mindist (less than 1) to graph:
graph [..., overlap=scale, mindist=.6];
[edit]
maybe the renderer version make a difference: here is the outcome on my machine
A: Try varying -Gsize (units of inches) and -Gdpi. You'll find that if you change them both together, you get different outputs with the same pixel size, but with different spacing between the nodes relative to the size of the nodes themselves. -Gnodesep and -Nfontsize might also be useful to tweak. You might also have better luck by rendering to EPS or PDF or SVG and then converting that to PNG, instead of using Graphviz's PNG renderer. Getting pleasing output from Graphviz is, in my experience, a very inexact science. | unknown | |
d19748 | test | [0] is the index and the data is "user_id"
A: The array key 0 contains a string called 'user_id' but there is no key named 'user_id', hence why you're getting the error.
I suggest you take a look at how you're compiling this data (query results perhaps?).
A: You are mistaken. The structure of the array is like this:
array:
[0] => array:
[0] => "user_id"
[1] => array:
[0] => "user_id"
You need to access it like this: $var[0][0] and you will get user_id. Most likely you did something wrong when setting up the array.
A: the index is [0]. I don't think you have this structured correctly. The index is the left side of the declaration, the value is the right. You have assigned all values to "user_id" with incremental index.
A: user_id is not an array key (that can be accessed by []), it is an value.
But you can use array_search()
$index = array_search('user_id', $your_array);
var_dump( $your_array[$index] );
A: error because the user_id is not an index it's a value having index 0 | unknown | |
d19749 | test | Seeing the error i assume that ShowList.fromJson requires a list but the code written is passing a map.. you can try like this
List jsonResponse = json.decode(response.body);
return ShowList.fromJson(jsonResponse);
You havecreated a method to convert the data
showListFromJson(String str)
This can be used directly to set the data like
ShowList _showList = showListFromJson(response.body);
A: json.decode returns either dynamic or List<dynamic>
If your response.body is List of items do it as follows
final jsonResponse = json.decode(response.body) as List<dynamic>;
return jsonResponse.map((e) => ShowList.fromJson(e as Map<String, dynamic>)).toList();
A: The error means the api is returning a map instead of the list your are expecting, so the first thing you have to do is to print your response.body to be sure of whats coming from the api
I have tested the api it seems the message it's returning is this:
{
"result": "Unauthorized, Access Denied",
"status": 401
}
which means the api is missing an authorization token
so try this:
static Future getShowList() async {
try {
String baseURL = 'https://westmarket.herokuapp.com/api/v1';
String userId = '62f4ecf82b6e81e77059b332';
String url = baseURL + '/user/:$userId/products';
final response = await http.get(
Uri.parse(url),
headers: {
'Authorization': '<your token>'
},
);
if(response.statusCode == HttpStatus.ok) {
List jsonResponse = json.decode(response.body);
return jsonResponse.map((item) =>
ShowList.fromJson(item)).toList();
} else {
//throw/return an error here
}
} catch(e) {
// throw/return an error here
}
} | unknown | |
d19750 | test | Use sum:
sum(
for $b in doc ("courses.xml") //Course_Catalog/Department/Course
where count($b/Instructors/Lecturer)=0
return count($b)
)
A: You actually need the count of all such elements.
Use:
count(doc ("courses.xml")//Course_Catalog/Department/Course[not(Instructors/Lecturer)]) | unknown | |
d19751 | test | Here is the short version of what I've done to make it work. It uses the jade Public API.
var directory = __dirname+'/views/bla/'
, files
, renderedHTML = '';
if( !fs.existsSync(directory) ) {
// directory doesn't exist, in my case I want a 404
return res.status(404).send('404 Not found');
}
// get files in the directory
files = fs.readdirSync(directory);
files.forEach(function(file) {
var template = jade.compile(fs.readFileSync(directory+file, 'utf8'));
// some templating
renderedHTML += '<section><a id="'+file+'" name="'+file+'" class="anchor"> </a>'+template()+'</section>';
});
// render the actual view and pass it the pre rendered views
res.render('view', {
title: 'View',
files: files,
html: renderedHTML
})
And the view just renders the html variable unescaped:
div(class="component-doc-wrap")
!{html}
A: As @user1737909 say, that's not possible using just jade.
The best way to do this (tho) is building a little Express Dynamic (view) Helpers
DEPECATED IN EXPRESS 3.XX
Check these: Jade - way to add dynamic includes
A: in addition to kalemas answer you can also write your includes to a file which is included in jade.
in this example I write my includes to include_all.jade. This file is included in a jade file.
If it does not work, check the path ;-)
e.g.
in your app.js
var includes = "path/to/include1\n";
includes += "path/to/include2";
...
incPath = "path/to/include_all.jade";
fs.open(incPath,'w',function(err,fd){
if(err){
throw 'error open file: ' + incPath +" "+ err;
}
var buffer = new Buffer(includes);
fs.write(fd,buffer,0,buffer.length,null,function(err){
if (err)
throw 'error writing file: ' +err;
fs.close(fd,function(){
console.log('file written ' + incPath);
});
});
});
in your jade file
include path/to/include_all.jade | unknown | |
d19752 | test | Both innerText and innerHTML set the HTML of the element. The difference is that innerText—by the way, you might want to use textContent instead—will escape the string so that you can't embed HTML content in it.
So for example, if you did this:
var div = document.createElement('DIV');
div.innerText = '<span>Hello</span>';
document.body.appendChild(div);
Then you'd actually see the string "<span>Hello</span>" on the screen, as opposed to "Hello" (inside a span).
There are some other subtleties to innerText as well, which are covered in the MDN article referenced above. | unknown | |
d19753 | test | find_all has been explained. However, your selector is going to produce duplicates as it will pull the same urls from title and price. Instead, I would use a child combinator and a different class for parent and add a child a tag to get the unique list. I prefer select over find_all. select applies css selectors in order to match on elements. All these a tags have an href so no need to add a test.
from bs4 import BeautifulSoup as bs
import requests
r = requests.get('https://autos.mercadolibre.com.ar/volkswagen/vento/_DisplayType_LF')
soup = bs(r.content, 'lxml')
links = [item['href'] for item in soup.select('.list-view-item-title > a')]
Child combinator:
The child combinator (>) is placed between two CSS selectors. It
matches only those elements matched by the second selector that are
the children of elements matched by the first.
Ref:
*
*https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.html?highlight=select_one#css-selectors
A: Since you are using Beautiful Soup, it is important to understand that the find_all method will return a list of tags that match your requirements. Your issue is that you want the href attribute of those tags. To do that, you can use the notation tag['attr'] on each tag. To do that we will iterate through the returned tags.
from bs4 import BeautifulSoup
import requests
busqueda = requests.get('https://autos.mercadolibre.com.ar/vento/_DisplayType_LF')
auto_cont = BeautifulSoup(busqueda.content)
print([tag['href'] for tag in auto_cont.find_all('a',{'class':'item__info-title'}, href = True)])
A: Try this:
>>> import requests
>>> s = requests.Session()
>>> resp = s.get("https://autos.mercadolibre.com.ar/vento/_DisplayType_LF")
>>> from lxml import html
>>> doc = html.fromstring(resp.text)
>>> doc.xpath("//a[@class='item__info-title']")
[<Element a at 0x11c005688>, <Element a at 0x11c0059a8>, <Element a at 0x11c007e58>, <Element a at 0x11c007ea8>, <Element a at 0x11c007ef8>, <Element a at 0x11c007c78>, <Element a at 0x11c007db8>, <Element a at 0x11c007e08>, <Element a at 0x11c007d68>, <Element a at 0x11c007cc8>, <Element a at 0x11c007d18>, <Element a at 0x11c007bd8>, <Element a at 0x11c007c28>, <Element a at 0x11c007228>, <Element a at 0x11c003318>, <Element a at 0x11c003408>, <Element a at 0x11c0034f8>, <Element a at 0x11c003688>, <Element a at 0x11c0035e8>, <Element a at 0x11c003228>, <Element a at 0x11c003598>, <Element a at 0x11c003458>, <Element a at 0x11c003278>, <Element a at 0x11c003548>, <Element a at 0x11c0034a8>, <Element a at 0x11c003368>, <Element a at 0x11c0033b8>, <Element a at 0x11c0032c8>, <Element a at 0x11c0031d8>, <Element a at 0x11c003188>, <Element a at 0x11c003098>, <Element a at 0x11c003138>, <Element a at 0x11c0030e8>, <Element a at 0x11c003048>, <Element a at 0x11c0036d8>, <Element a at 0x11c003728>, <Element a at 0x11c003778>, <Element a at 0x11c0037c8>, <Element a at 0x11c003818>, <Element a at 0x11c003868>, <Element a at 0x11c0038b8>, <Element a at 0x11c003908>, <Element a at 0x11c003958>, <Element a at 0x11c0039a8>, <Element a at 0x11c0039f8>, <Element a at 0x11c003a48>, <Element a at 0x11c003a98>, <Element a at 0x11c003ae8>, <Element a at 0x11c003b38>, <Element a at 0x11c003b88>, <Element a at 0x11c003bd8>, <Element a at 0x11c003c28>, <Element a at 0x11c003c78>, <Element a at 0x11c003cc8>, <Element a at 0x11c003d18>, <Element a at 0x11c003d68>, <Element a at 0x11c003db8>, <Element a at 0x11c003e08>, <Element a at 0x11c003e58>, <Element a at 0x11c003ea8>, <Element a at 0x11c003ef8>, <Element a at 0x11c003f48>, <Element a at 0x11c003f98>, <Element a at 0x11c006048>, <Element a at 0x11c006098>, <Element a at 0x11c0060e8>, <Element a at 0x11c006138>, <Element a at 0x11c006188>, <Element a at 0x11c0061d8>, <Element a at 0x11c006228>, <Element a at 0x11c006278>, <Element a at 0x11c0062c8>, <Element a at 0x11c006318>, <Element a at 0x11c006368>, <Element a at 0x11c0063b8>, <Element a at 0x11c006408>, <Element a at 0x11c006458>, <Element a at 0x11c0064a8>, <Element a at 0x11c0064f8>, <Element a at 0x11c006548>, <Element a at 0x11c006598>, <Element a at 0x11c0065e8>, <Element a at 0x11c006638>, <Element a at 0x11c006688>, <Element a at 0x11c0066d8>, <Element a at 0x11c006728>, <Element a at 0x11c006778>, <Element a at 0x11c0067c8>, <Element a at 0x11c006818>, <Element a at 0x11c006868>, <Element a at 0x11c0068b8>, <Element a at 0x11c006908>, <Element a at 0x11c006958>, <Element a at 0x11c0069a8>, <Element a at 0x11c0069f8>, <Element a at 0x11c006a48>, <Element a at 0x11c006a98>, <Element a at 0x11c006ae8>, <Element a at 0x11c006b38>, <Element a at 0x11c006b88>]
>>> doc.xpath("//a[@class='item__info-title']/@href")
['https://auto.mercadolibre.com.ar/MLA-793135798-volkswagen-vento-20t-sportline-2007-4p-dh-aa-san-blas-auto-_JM', 'https://auto.mercadolibre.com.ar/MLA-793135798-volkswagen-vento-20t-sportline-2007-4p-dh-aa-san-blas-auto-_JM', 'https://auto.mercadolibre.com.ar/MLA-788603493-volkswagen-vento-25-advance-plus-manual-2015-rpm-moviles-_JM', 'https://auto.mercadolibre.com.ar/MLA-788603493-volkswagen-vento-25-advance-plus-manual-2015-rpm-moviles-_JM', 'https://auto.mercadolibre.com.ar/MLA-774423219-vento-comfortline-0km-2019-volkswagen-linea-nueva-vw-2018-_JM', 'https://auto.mercadolibre.com.ar/MLA-774423219-vento-comfortline-0km-2019-volkswagen-linea-nueva-vw-2018-_JM', 'https://auto.mercadolibre.com.ar/MLA-795714156-volksvagen-vento-advance-plus-25-anticipo-290000-y-ctas-_JM', 'https://auto.mercadolibre.com.ar/MLA-795714156-volksvagen-vento-advance-plus-25-anticipo-290000-y-ctas-_JM', 'https://auto.mercadolibre.com.ar/MLA-792330462-volkswagen-vento-25-luxury-wood-tiptronic-2009-imolaautos--_JM', 'https://auto.mercadolibre.com.ar/MLA-792330462-volkswagen-vento-25-luxury-wood-tiptronic-2009-imolaautos--_JM', 'https://auto.mercadolibre.com.ar/MLA-763941297-vento-highline-0km-automatico-auto-nuevos-volkswagen-vw-2019-_JM', 'https://auto.mercadolibre.com.ar/MLA-763941297-vento-highline-0km-automatico-auto-nuevos-volkswagen-vw-2019-_JM', 'https://auto.mercadolibre.com.ar/MLA-791000164-volkswagen-vento-20-advance-115cv-2015-_JM', 'https://auto.mercadolibre.com.ar/MLA-791000164-volkswagen-vento-20-advance-115cv-2015-_JM', 'https://auto.mercadolibre.com.ar/MLA-788125558-volkswagen-vento-14-tsi-highline-150cv-at-2017-rpm-moviles-_JM', 'https://auto.mercadolibre.com.ar/MLA-788125558-volkswagen-vento-14-tsi-highline-150cv-at-2017-rpm-moviles-_JM', 'https://auto.mercadolibre.com.ar/MLA-777140113-volkswagen-vento-gli-dsg-nav-my-18-_JM', 'https://auto.mercadolibre.com.ar/MLA-777140113-volkswagen-vento-gli-dsg-nav-my-18-_JM', 'https://auto.mercadolibre.com.ar/MLA-795016462-volkswagen-vento-25-luxury-tiptronic-2011-imolaautos--_JM', 'https://auto.mercadolibre.com.ar/MLA-795016462-volkswagen-vento-25-luxury-tiptronic-2011-imolaautos--_JM', 'https://auto.mercadolibre.com.ar/MLA-792487602-volkswagen-25-luxury-170cv-tiptronic-2015-rpm-moviles-_JM', 'https://auto.mercadolibre.com.ar/MLA-792487602-volkswagen-25-luxury-170cv-tiptronic-2015-rpm-moviles-_JM', 'https://auto.mercadolibre.com.ar/MLA-789645020-volkswagen-vento-20-advance-115cv-summer-package-371-_JM', 'https://auto.mercadolibre.com.ar/MLA-789645020-volkswagen-vento-20-advance-115cv-summer-package-371-_JM', 'https://auto.mercadolibre.com.ar/MLA-775185003-vw-0km-volkswagen-vento-14-comfortline-highline-financiado-_JM', 'https://auto.mercadolibre.com.ar/MLA-775185003-vw-0km-volkswagen-vento-14-comfortline-highline-financiado-_JM', 'https://auto.mercadolibre.com.ar/MLA-774502893-volkswagen-vento-14-comfortline-150cv-at-dsg-0km-2019-vw-_JM', 'https://auto.mercadolibre.com.ar/MLA-774502893-volkswagen-vento-14-comfortline-150cv-at-dsg-0km-2019-vw-_JM', 'https://auto.mercadolibre.com.ar/MLA-795734858-volkswagen-vento-25-luxury-tiptronic-2009-_JM', 'https://auto.mercadolibre.com.ar/MLA-795734858-volkswagen-vento-25-luxury-tiptronic-2009-_JM', 'https://auto.mercadolibre.com.ar/MLA-795501655-volkswagen-vento-25-luxury-170cv-_JM', 'https://auto.mercadolibre.com.ar/MLA-795501655-volkswagen-vento-25-luxury-170cv-_JM', 'https://auto.mercadolibre.com.ar/MLA-792476554-volkswagen-vento-14-comfortline-150cv-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-792476554-volkswagen-vento-14-comfortline-150cv-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-790622152-volkswagen-vento-14-tsi-comfortline-dsg-como-nuevo-_JM', 'https://auto.mercadolibre.com.ar/MLA-790622152-volkswagen-vento-14-tsi-comfortline-dsg-como-nuevo-_JM', 'https://auto.mercadolibre.com.ar/MLA-741867064-volkswagen-vento-14-comfortline-150cv-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-741867064-volkswagen-vento-14-comfortline-150cv-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-770677950-volkswagen-vento-20-sportline-tsi-200cv-dgs-_JM', 'https://auto.mercadolibre.com.ar/MLA-770677950-volkswagen-vento-20-sportline-tsi-200cv-dgs-_JM', 'https://auto.mercadolibre.com.ar/MLA-756888148-volkswagen-vento-14-highline-150cv-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-756888148-volkswagen-vento-14-highline-150cv-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-792470321-volkswagen-vento-highline-14-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-792470321-volkswagen-vento-highline-14-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-780443475-volkswagen-vento-20-sportline-tsi-200cv-bi-xenon-_JM', 'https://auto.mercadolibre.com.ar/MLA-780443475-volkswagen-vento-20-sportline-tsi-200cv-bi-xenon-_JM', 'https://auto.mercadolibre.com.ar/MLA-775185107-vw-0km-volkswagen-vento-14-comfortline-highline-financio-ya-_JM', 'https://auto.mercadolibre.com.ar/MLA-775185107-vw-0km-volkswagen-vento-14-comfortline-highline-financio-ya-_JM', 'https://auto.mercadolibre.com.ar/MLA-763006237-volkswagen-nuevo-vento-comfortline-14-tsi-150cv-autotag-a7-_JM', 'https://auto.mercadolibre.com.ar/MLA-763006237-volkswagen-nuevo-vento-comfortline-14-tsi-150cv-autotag-a7-_JM', 'https://auto.mercadolibre.com.ar/MLA-792344363-volkswagen-vento-14-comfortline-150cv-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-792344363-volkswagen-vento-14-comfortline-150cv-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-789195021-volkswagen-vento-comfortline-motor-14-at-tiptronic-_JM', 'https://auto.mercadolibre.com.ar/MLA-789195021-volkswagen-vento-comfortline-motor-14-at-tiptronic-_JM', 'https://auto.mercadolibre.com.ar/MLA-787103884-volkswagen-vento-comfortline-14-150-cv-dsg-_JM', 'https://auto.mercadolibre.com.ar/MLA-787103884-volkswagen-vento-comfortline-14-150-cv-dsg-_JM', 'https://auto.mercadolibre.com.ar/MLA-795438039-volkswagen-vento-14-highline-150cv-at-financio-leasing-0km-_JM', 'https://auto.mercadolibre.com.ar/MLA-795438039-volkswagen-vento-14-highline-150cv-at-financio-leasing-0km-_JM', 'https://auto.mercadolibre.com.ar/MLA-785080712-vento-25-advance-manual-permutofinancio-_JM', 'https://auto.mercadolibre.com.ar/MLA-785080712-vento-25-advance-manual-permutofinancio-_JM', 'https://auto.mercadolibre.com.ar/MLA-739533930-volkswagen-vento-20-tsi-i-2017-i-permuto-i-financio-_JM', 'https://auto.mercadolibre.com.ar/MLA-739533930-volkswagen-vento-20-tsi-i-2017-i-permuto-i-financio-_JM', 'https://auto.mercadolibre.com.ar/MLA-787212749-volkswagen-vento-14-comfortline-150cv-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-787212749-volkswagen-vento-14-comfortline-150cv-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-785738851-volkswagen-vento-advance-summer-package-20-unico-dueno--_JM', 'https://auto.mercadolibre.com.ar/MLA-785738851-volkswagen-vento-advance-summer-package-20-unico-dueno--_JM', 'https://auto.mercadolibre.com.ar/MLA-788508924-volkswagen-vento-25-advance-tiptronic-2007-_JM', 'https://auto.mercadolibre.com.ar/MLA-788508924-volkswagen-vento-25-advance-tiptronic-2007-_JM', 'https://auto.mercadolibre.com.ar/MLA-790696083-volkswagen-vento-14-highline-150cv-at-0km-tiptronic-nuevo-1-_JM', 'https://auto.mercadolibre.com.ar/MLA-790696083-volkswagen-vento-14-highline-150cv-at-0km-tiptronic-nuevo-1-_JM', 'https://auto.mercadolibre.com.ar/MLA-788446116-volkswagen-vento-20-sportline-tsi-200-2013-luxury-tdi-bora-_JM', 'https://auto.mercadolibre.com.ar/MLA-788446116-volkswagen-vento-20-sportline-tsi-200-2013-luxury-tdi-bora-_JM', 'https://auto.mercadolibre.com.ar/MLA-752087027-volkswagen-nuevo-vento-14-highline-0-km-2019-autotag-cb-a7-_JM', 'https://auto.mercadolibre.com.ar/MLA-752087027-volkswagen-nuevo-vento-14-highline-0-km-2019-autotag-cb-a7-_JM', 'https://auto.mercadolibre.com.ar/MLA-781505508-nuevo-vento-entrega-inmediata-tomo-usado-moto-auto-18-_JM', 'https://auto.mercadolibre.com.ar/MLA-781505508-nuevo-vento-entrega-inmediata-tomo-usado-moto-auto-18-_JM', 'https://auto.mercadolibre.com.ar/MLA-742485511-volkswagen-vento-14-highline-150cv-0km-_JM', 'https://auto.mercadolibre.com.ar/MLA-742485511-volkswagen-vento-14-highline-150cv-0km-_JM', 'https://auto.mercadolibre.com.ar/MLA-769182377-vw-volkswagen-vento-gli-230-cv-preventa-2019-0-km-_JM', 'https://auto.mercadolibre.com.ar/MLA-769182377-vw-volkswagen-vento-gli-230-cv-preventa-2019-0-km-_JM', 'https://auto.mercadolibre.com.ar/MLA-790609996-volkswagen-vento-20-luxury-i-140cv-dsg-automatico-diesel-_JM', 'https://auto.mercadolibre.com.ar/MLA-790609996-volkswagen-vento-20-luxury-i-140cv-dsg-automatico-diesel-_JM', 'https://auto.mercadolibre.com.ar/MLA-790664862-volkswagen-vento-25-luxury-170cv-_JM', 'https://auto.mercadolibre.com.ar/MLA-790664862-volkswagen-vento-25-luxury-170cv-_JM', 'https://auto.mercadolibre.com.ar/MLA-784454164-volkswagen-vento-25-luxury-170cv-_JM', 'https://auto.mercadolibre.com.ar/MLA-784454164-volkswagen-vento-25-luxury-170cv-_JM', 'https://auto.mercadolibre.com.ar/MLA-769868579-0km-volkswagen-vento-14-highline-150cv-at-2019-tasa-159-d-_JM', 'https://auto.mercadolibre.com.ar/MLA-769868579-0km-volkswagen-vento-14-highline-150cv-at-2019-tasa-159-d-_JM', 'https://auto.mercadolibre.com.ar/MLA-787564006-volkswagen-vento-20t-sportline-automatico-dsg-2013-_JM', 'https://auto.mercadolibre.com.ar/MLA-787564006-volkswagen-vento-20t-sportline-automatico-dsg-2013-_JM', 'https://auto.mercadolibre.com.ar/MLA-788080154-volkswagen-vento-20-sportline-tsi-200cv-dgs-2013-_JM', 'https://auto.mercadolibre.com.ar/MLA-788080154-volkswagen-vento-20-sportline-tsi-200cv-dgs-2013-_JM', 'https://auto.mercadolibre.com.ar/MLA-771885864-volkswagen-vento-14-comfortline-150cv-aut-sf-_JM', 'https://auto.mercadolibre.com.ar/MLA-771885864-volkswagen-vento-14-comfortline-150cv-aut-sf-_JM', 'https://auto.mercadolibre.com.ar/MLA-795273990-vento-25-manual-unico-dueno-80000-km-motor-cadenero-_JM', 'https://auto.mercadolibre.com.ar/MLA-795273990-vento-25-manual-unico-dueno-80000-km-motor-cadenero-_JM', 'https://auto.mercadolibre.com.ar/MLA-769870550-0km-volkswagen-vento-14-highline-150cv-at-2019-tasa-159-f-_JM', 'https://auto.mercadolibre.com.ar/MLA-769870550-0km-volkswagen-vento-14-highline-150cv-at-2019-tasa-159-f-_JM', 'https://auto.mercadolibre.com.ar/MLA-790653682-volkswagen-vento-25-triptronic-170-cv-cuero-carhaus-_JM', 'https://auto.mercadolibre.com.ar/MLA-790653682-volkswagen-vento-25-triptronic-170-cv-cuero-carhaus-_JM'] | unknown | |
d19754 | test | Absolute paths should not be hardcoded. They should be read e.g. from a config file or user input.
Then you can use the NIO.2 File API to create your file paths: Paths.get(...) (java.io.File is a legacy API).
In your case it could be:
Path filePath = Paths.get("dir", "fileName");
A:
I used: File f = new File("./dir/fileName") which works fine in Ubuntu but it gives error in Windows, bcz the directory pattern of both os are different.
It is presumably failing because that file doesn't exist at that path. Note that it is a relative path, so the problem could have been that the the path could not be resolved from the current directory ... because the current directory was not what the application was expecting.
In fact, it is perfectly fine to use forward slashes in pathnames in Java on Window. That's because at the OS level, Windows accepts both / and \ as path separators. (It doesn't work in the other direction though. UNIX, Linux and MacOS do not accept backslash as a pathname separator.)
However Puce's advice is mostly sound:
*
*It is inadvisable to hard-code paths into your application. Put them into a config file.
*Use the NIO2 Path and Paths APIs in preference to File. If you need to assemble paths from their component parts, these APIs offer clean ways to do it while hiding the details of path separators. The APIs are also more consistent than File, and give better diagnostics.
But: if you do need to get the pathname separator, File.separator is an acceptable way to get it. Calling FileSystem.getSeparator() may be better, but you will only see a difference if your application is using different FileSystem objects for different file systems with different separators.
A: You can use File.separator as you can see in api docs:
https://docs.oracle.com/javase/8/docs/api/java/io/File.html | unknown | |
d19755 | test | This should work, assuming config-app.properties exists in the class path (in the root). You should not get the error "Can't find resource for bundle java.util.PropertyResourceBundle".
However, what you're trying to do, by substituting ${smtp.host.name.env}, will NOT work with ResourceBundle. You would need another library to do something more complicated like that.
UPDATED
It's not clear what you're trying to do, but assuming you want to have profile for developement and another one for production, you could try to do something like this:
Properties defaultProperties = new Properties();
defaultProperties.load(new FileInputStream("config-app.properties"));
Properties properties = new Properties(defaultProperties);
if (isDev()) {
properties.load(new FileInputStream("config-dev.properties"));
} else {
properties.load(new FileInputStream("whatever.properties"));
}
properties.getProperty("smtp.host.name");
This will have default settings in config-app.properties, which can be overwritten in config-dev.properties or whatever.properties as needed. In this case the keep must be the same.
config-app.properties:
smtp.host.name =localhost
config-dev.properties:
smtp.host.name =smtp.gmail.com
One last note, the previous code is loading the files from the filesystem, if you have them in the classpath, use something like :
defaultProperties.load(Classname.class.getClassLoader().getResourceAsStream("config-app.properties")); | unknown | |
d19756 | test | During the first phase of two phase lookup, when the template is defined, unqualified lookup looks for dependent and non-dependent names in the immediate enclosing namespace of the template and finds only those to_string overloads which appear before the template definition.
During the second phase of two phase lookup, when the template is instantiated, argument-dependent lookup looks for dependent names in the namespaces associated with any class types passed as arguments to the named functions. But because your to_string(const User::Service&) overload is in the PrettyPrint namespace, it will not be found by argument-dependent lookup.
Move your to_string(const User::Service&) overload into the User namespace to make use of argument-dependent lookup, which will find any overloads declared at the point of template instantiation, including any declared after the point of template definition.
See also http://clang.llvm.org/compatibility.html#dep_lookup
A: What the compiler does when instantiating a template is essentially expanding it (more or less like a macro), and compiling the result on the fly. To do that, any functions (or other stuff) mentioned must be visible at that point. So make sure any declarations used are mentioned beforehand (in the same header file, most probably).
A: I don't entirely understand what's going on here, but it appears that if you want the later defined methods to be used, then they need to be template specializations. The compiler won't see function overrides later in the program.
First off, we reproduce the problem. I do so with this program in gcc-4.8.2:
// INCLUDE FILE 1
template <class T> void to_string (T const * a) {
to_string (*a);
}
// INCLUDE FILE 1 END
// INCLUDE FILE 2
// How do we make this program work when this is necessarily declared after to_string(T const * A)?
void to_string(int const & a) {
return;
}
// INCLUDE FILE 2 END
int main (void) {
int i = 5;
int * p = &i;
to_string(i);
to_string(p);
to_string(&i);
return 0;
}
In order to get it working, we need to do this...
// INCLUDE FILE 1
// The pointer version needs something to call...
template <class T> void to_string (T const & a);
// This can't be T const * a. Try it. So weird...
template <class T> void to_string (T * a) {
foo (*a);
}
// INCLUDE FILE 1 END
// INCLUDE FILE 2
// This has to specialize template<> void to_string. If we just override, we get a linking error.
template<> void to_string <int> (int const & a) {
return;
}
// INCLUDE FILE 2 END
int main (void) {
int i = 5;
int * p = &i;
to_string(i);
to_string(p);
to_string(&i);
return 0;
} | unknown | |
d19757 | test | Essentially, you'd want to go over the first list, and for each item go over the second list and check if any interval overlaps it. Streams make this a tad more elegant:
List<Interval> list1 = // some intervals...
List<Interval> list2 = // some more internvals...
List<Interval> result =
list1.stream()
.filter(i1 -> list2.stream().allMatch(i2 -> i1.overlap(i2) == null))
.collect(Collectors.toList()); | unknown | |
d19758 | test | I believe there already is a solution for your problem here on SO, try looking at THIS question. You will just need to define (a bit complicated) function and use it as in example.
A: This is really a SQL query issue that has little to do with ASP. Since you're using MDB you may find it easier to model your queries using MS Access, then paste the generated SQL statement back into your ASP code.
The following question can help:
SQL Group with Order by
A: Serious fails in the HTML.
Anyway, here's a quick solution by making a few mods to the logic for looping through the result set and displaying it.
<%
Set DataConn = Server.CreateObject("ADODB.Connection")
Set RS = Server.CreateObject("ADODB.RecordSet")
DataConn.Open "DBQ=" & Server.Mappath("/path/to/mydb") & ";Driver={Microsoft Access Driver (*.mdb)};Uid=user;Pwd=pass;"
Set rsDsp = DataConn.Execute("SELECT SignUpLog.PatientFileNumber, SignUpLog.ArrivalDateTime, Notes.Note, SignUpLog.Called, SignUpLog.DrName FROM SignUpLog, Notes WHERE (((Notes.NoteKey)=[SignUpLog].[FirstNoteAddr])) ORDER BY SignUpLog.ArrivalDateTime DESC;")
If rsDsp.EOF Then
Response.Write "Sorry, no entries in the database!"
Else
%>
<div align="center">
<table BORDER="0" width="700">
<tr>
<th width="105">Name</th>
<th width="105">Arrival Time</th>
<th width="105">Doctor</th>
<th width="105">Notes</th>
</tr>
<%
Dim LastPatient;
Dim Notes = "";
Dim x = 0;
While Not rsDsp.EOF
If LastPatient = rsDsp.Field.Item("PatientFileNumber").Value Then
Response.Write "<br />" & rsDsp("Note").Value
Else
If LastPatient <> NULL Then
Response.Write "</td></tr>"
If x Mod 2 = 0 Then
Response.Write "<tr><td>" & rsDsp.Fields.Item("PatientFileNumber").Value & "</td>"
Response.Write "<td>" & rsDsp("ArrivalDateTime").Value & "</td>"
Response.Write "<td>" & rsDsp("DrName").Value & "</td>"
Response.Write "<td>" & rsDsp("Note").Value
Else
Response.Write "<tr><td bgcolor=""E4E4E4"">" & rsDsp.Fields.Item("PatientFileNumber").Value & "</td>"
Response.Write "<td bgcolor=""E4E4E4"">" & rsDsp("ArrivalDateTime").Value & "</td>"
Response.Write "<td bgcolor=""E4E4E4"">" & rsDsp("DrName").Value & "</td"
Response.Write "<td bgcolor=""E4E4E4"">" & rsDsp("Note").Value
End If
x = x + 1
End If
LastPatient = rsDsp.Fields.Item("PatientFileNumber").Value
rsDsp.MoveNext
Wend
Response.Write "</td></tr>"
DataConn.Close
End If
%>
</table>
</div> | unknown | |
d19759 | test | No. wsa:To is a SOAP header block, not an HTTP header. | unknown | |
d19760 | test | it's way too much code to post here
Not really.
Try this:
#include <GL/glew.h>
#include <GL/freeglut.h>
#include <vector>
#include <iostream>
struct Program
{
static GLuint Load( const char* vert, const char* geom, const char* frag )
{
GLuint prog = glCreateProgram();
if( vert ) AttachShader( prog, GL_VERTEX_SHADER, vert );
if( geom ) AttachShader( prog, GL_GEOMETRY_SHADER, geom );
if( frag ) AttachShader( prog, GL_FRAGMENT_SHADER, frag );
glLinkProgram( prog );
CheckStatus( prog );
return prog;
}
private:
static void CheckStatus( GLuint obj )
{
GLint status = GL_FALSE, len = 10;
if( glIsShader(obj) ) glGetShaderiv( obj, GL_COMPILE_STATUS, &status );
if( glIsProgram(obj) ) glGetProgramiv( obj, GL_LINK_STATUS, &status );
if( status == GL_TRUE ) return;
if( glIsShader(obj) ) glGetShaderiv( obj, GL_INFO_LOG_LENGTH, &len );
if( glIsProgram(obj) ) glGetProgramiv( obj, GL_INFO_LOG_LENGTH, &len );
std::vector< char > log( len, 'X' );
if( glIsShader(obj) ) glGetShaderInfoLog( obj, len, NULL, &log[0] );
if( glIsProgram(obj) ) glGetProgramInfoLog( obj, len, NULL, &log[0] );
std::cerr << &log[0] << std::endl;
exit( -1 );
}
static void AttachShader( GLuint program, GLenum type, const char* src )
{
GLuint shader = glCreateShader( type );
glShaderSource( shader, 1, &src, NULL );
glCompileShader( shader );
CheckStatus( shader );
glAttachShader( program, shader );
glDeleteShader( shader );
}
};
#define GLSL(version, shader) "#version " #version "\n" #shader
const char* vert = GLSL
(
400 core,
layout( location = 0 ) in vec4 vPosition;
void main()
{
gl_Position = vPosition;
}
);
const char* frag = GLSL
(
400 core,
out vec4 fColor;
void main()
{
fColor = vec4( 0.0, 0.0, 1.0, 1.0 );
}
);
enum VAO_IDs { Triangles, NumVAOs };
enum Buffer_IDs { ArrayBuffer, NumBuffers };
enum Attrib_IDs { vPosition = 0 };
GLuint VAOs[NumVAOs];
GLuint Buffers[NumBuffers];
const GLuint NumVertices = 6;
void init(void)
{
glGenVertexArrays(NumVAOs, VAOs);
glBindVertexArray(VAOs[Triangles]);
GLfloat vertices[NumVertices][2] = {
{ -0.90, -0.90 }, // Triangle 1
{ 0.85, -0.90 },
{ -0.90, 0.85 },
{ 0.90, -0.85 }, // Triangle 2
{ 0.90, 0.90 },
{ -0.85, 0.90 }
};
glGenBuffers(NumBuffers, Buffers);
glBindBuffer(GL_ARRAY_BUFFER, Buffers[ArrayBuffer]);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
GLuint program = Program::Load( vert, NULL, frag );
glUseProgram(program);
glVertexAttribPointer(vPosition, 2, GL_FLOAT, GL_FALSE, 0, (void*)(0) );
glEnableVertexAttribArray(vPosition);
}
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glBindVertexArray(VAOs[Triangles]);
glDrawArrays(GL_TRIANGLES, 0, NumVertices);
glutSwapBuffers();
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE );
glutInitWindowSize(512, 512);
glutInitContextVersion(4, 0);
glutInitContextProfile(GLUT_CORE_PROFILE);
glutCreateWindow(argv[0]);
glewExperimental = GL_TRUE;
if( GLEW_OK != glewInit() )
exit(EXIT_FAILURE);
init();
glutDisplayFunc(display);
glutMainLoop();
}
No reason to request a 4.3 context if you're using #version 400 core. | unknown | |
d19761 | test | D'oh! Resolved.
GD Library wasn't installed. When I installed it, all was well! | unknown | |
d19762 | test | Newlines as \n work in Swift string literals too.
Check out the docs: Special Unicode Characters in String Literals
A: Here is an example replacing a unicode character in a string with a comma (to give you a sense of using escaped unicodes).
address = address.stringByReplacingOccurrencesOfString("\u{0000200e}", withString: ",", options: nil, range: nil) | unknown | |
d19763 | test | Try to use:
animalQuestion.append((orderlist: orderlist, questionid: questionid, question: question, description: description))
And do not forgot:
let orderlist = row[4] as Int
Your code incorrect because of:
1) For appending new objects to array you must to use array-method
animalQuestion.append(<Array object>)
2) In your case Array object is a tuple. So first you need to create a tuple, something like:
let orderTuple = (orderlist, questionid, question, description)
and after that appaned orderTuple to animalQuestion array like:
animalQuestion.append(orderTuple) | unknown | |
d19764 | test | Try it like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences pvtPref = getPreferences(MODE_PRIVATE);
boolean isFirstLaunch = pvtPref.getBoolean("isFirstLaunch", false);
if (isFirstLaunch) { // <<<< Syntax Error ?
// Do Something
}
}
A: Try this...
*
*First see that you have declared isFirstLaunch as boolean, if you have it should work.
*No need to use isFirstLaunch == true
if(isFirstLaunch)
A: You are getting a Boolean instead of a boolean. So you should use either :
Boolean isFirstLaunch = pvtPref.getBoolean("isFirstLaunch", false);
if (isFirstLaunch.booleanValue()) {
}
or :
boolean isFirstLaunch = pvtPref.getBoolean("isFirstLaunch", false);
if (isFirstLaunch) {
}
And try to click on the error icon on the left, and choose "Clear all lint marker" (if it's there). | unknown | |
d19765 | test | You can just create controller for root route.
class RoutesController < ActionController::Base
before_filter :authenticate_user!
def root
root_p = case current_user.role
when 'admin'
SOME_ADMIN_PATH
when 'manager'
SOME_MANAGER_PATH
else
SOME_DEFAULT_PATH
end
redirect_to root_p
end
end
In your routes.rb:
root 'routes#root'
P.S. example expects using Devise, but you can customize it for your needs.
A: There are a few different options:
1. lambda in the routes file(not very railsy)
previously explained
2. redirection in application controller based on a before filter(this is optimal but your admin route will not be at the root)
source rails guides - routing
you would have two routes, and two controllers. for example you might have a HomeController and then an AdminController. Each of those would have an index action.
your config/routes.rb file would have
namespace :admin do
root to: "admin#index"
end
root to: "home#index"
The namespace method gives you a route at /admin and the regular root would be accessible at '/'
Then to be safe; in your admin controller add a before_filter to redirect any non admins, and in your home controller you could redirect any admin users.
3. dynamically changing the layout based on user role.
In the same controller that your root is going to, add a helper method that changes the layout.
layout :admin_layout_filter
private
def admin_layout_filter
if admin_user?
"admin"
else
"application"
end
end
def admin_user?
current_user.present? && current_user.admin?
end
Then in your layouts folder, add a file called admin.html.erb
source: rails guides - layouts and routing
A: You can't truly change the root dynamically, but there's a couple of ways you can fake it.
The solution you want needs to take place in either your application controller or the "default" root controller. The cleanest/easiest solution is simply to have your application controller redirect to the appropriate action in a before filter that only runs for that page. This will cause the users' url to change, however, and they won't really be at the root anymore.
Your second option is to have the method you've specified as root render a different view under whatever conditions you're looking for. If this requires any major changes in logic beyond simply loading a separate view, however, you're better off redirecting. | unknown | |
d19766 | test | You should use exclude=('user',) in class Meta: of your form. @Daniel Roseman is also right. | unknown | |
d19767 | test | Apparently GMAIL was blocking my email address from using less secure devices. You can turn off the blocking at: https://www.google.com/settings/security/lesssecureapps.
A: Perhaps UseDefaultCredentials = false, instead?
Edit: This seems similar to an older StackOverflow question: SmtpClient with Gmail | unknown | |
d19768 | test | Your for loop in the reduce function is probably not doing what you think it is. For example, it might be throwing an exception that you did not expect.
You are expecting an array of 2-tuples:
// Expectation
values = [ [value1, total1]
, [value2, total2]
, [value3, total3]
];
During a re-reduce, the function will get old results from itself before.
// Re-reduce values
values = [ avg1
, avg2
, avg3
]
Therefore I would begin by examining how your code works if and when rereduce is true. Perhaps something simple will fix it (although often I have to log() things until I find the problem.)
function(keys, values, rereduce) {
if(rereduce)
return sum(values);
// ... then the same code as before.
}
A: I will elaborate on my count/sum comment, just in case you are curious.
This code is not tested, but hopefully you will get the idea. The end result is always a simple object {"count":C, "sum":S} and you know the average by computing S / C.
function (key, values, rereduce) {
// Reduce function
var count = 0;
var sum = 0;
var i;
if(!rereduce) {
// `values` stores actual map output
for(i = 0; i < values.length; i++) {
count += Number(values[i][1]);
sum += Number(values[i][0]);
}
return {"count":count, "sum":sum};
}
else {
// `values` stores count/sum objects returned previously.
for(i = 0; i < values.length; i++) {
count += values[i].count;
sum += values[i].sum;
}
return {"count":count, "sum":sum};
}
}
A: I use the following code to do average. Hope it helps.
function (key, values) {
return sum(values)/values.length;
} | unknown | |
d19769 | test | I dont' think this is possible with pure CSS. The only think I could think of is using position: absolute for <img> to take it out of the flow in combination with max-height; then adjusting the margin of the text with javascript.
https://jsfiddle.net/zphb0fLd/
Hope it's useful.
A: Well as far as my knowledge, the image size can be increased with relative to text size, but its opposite case is not possible.
Here is my code. I use the flexbox to increase the height of the image as per text size. Let me know if it meets your requirements.
<div class="flex">
<div class="image-container">
<img src="https://via.placeholder.com/300x300" alt="">
</div>
<div class="text-container">
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis facilisis nisi elit, vitae interdum nisi porttitor a. Maecenas porta mollis venenatis. Proin suscipit, est et malesuada ultricies, nisi elit aliquam arcu, et luctus felis dolor euismod ante. Praesent nec malesuada arcu. Nunc rutrum erat risus, id elementum leo dignissim eu. Fusce feugiat, massa vestibulum venenatis ullamcorper, nisl justo aliquam purus, nec pellentesque tellus magna non quam. Pellentesque luctus quam in justo congue tempor. Cras placerat sit amet nulla id pretium. Nulla facilisi. Phasellus dictum neque sed lacus congue, vel dapibus enim efficitur.
</p>
</div>
</div>
.flex{
display:flex;
flex-wrap:wrap;
}
.image-container{
flex:1;
}
.text-container{
flex:3;
}
.text-container p{
font-size:2em;
padding:10px;
}
.image-container img{
width:100%;
height:100%;
object-fit:cover;
}
Live example link: https://codepen.io/pranaysharma995/pen/JjdQWyQ | unknown | |
d19770 | test | @jezrael's answer is perfect, if the Pid is not a duplicate, then you need the sum I was thinking of combining them as an index.
df['Pid'] = df.sum(axis=1)
df['Pid'] = df['Pid'].astype(int)
df = pd.merge(df, df2, on='Pid', how='inner')
df.drop('Pid', axis=1, inplace=True)
df
a b c d e f ind
0 0 0 2106 0.0 0 0 n
1 0 2103 0 0.0 0 0 n
2 0 2104 0 0.0 0 0 y
3 0 2105 0 0.0 0 0 n
4 2100 0 0 0.0 0 0 y
5 2101 0 0 0.0 0 0 n
6 2102 0 0 0.0 0 0 y
7 0 0 2107 0.0 0 0 n
8 0 0 2108 0.0 0 0 y
9 0 0 2109 0.0 0 0 y
10 0 0 2110 0.0 0 0 n
11 0 0 2111 0.0 0 0 y
12 0 0 0 2112.0 0 0 y
13 0 0 0 2113.0 0 0 y
14 0 0 0 2114.0 0 0 n
15 0 0 0 0.0 2115 0 n
16 0 0 0 0.0 2116 0 y
17 0 0 0 0.0 0 2117 y
18 0 0 0 0.0 0 2118 n
19 0 0 0 0.0 0 2119 y
20 0 0 0 0.0 2120 0 n
A: Use:
df1['ind'] = df1.mask(df1.eq(0)).ffill(axis=1).iloc[:, -1].map(df2.set_index('Pid')['ind'])
print (df1)
a b c d e f ind
0 0 0 2106 0.0 0 0 n
1 0 2103 0 0.0 0 0 n
2 0 2104 0 0.0 0 0 y
3 0 2105 0 0.0 0 0 n
4 2100 0 0 0.0 0 0 y
5 2101 0 0 0.0 0 0 n
6 2102 0 0 0.0 0 0 y
7 0 0 2107 0.0 0 0 n
8 0 0 2108 0.0 0 0 y
9 0 0 2109 0.0 0 0 y
10 0 0 2110 0.0 0 0 n
11 0 0 2111 0.0 0 0 y
12 0 0 0 2112.0 0 0 y
13 0 0 0 2113.0 0 0 y
14 0 0 0 2114.0 0 0 n
15 0 0 0 0.0 2115 0 n
16 0 0 0 0.0 2116 0 y
17 0 0 0 0.0 0 2117 y
18 0 0 0 0.0 0 2118 n
19 0 0 0 0.0 0 2119 y
20 0 0 0 0.0 2120 0 n
Details:
First replace 0 values to missing values by DataFrame.mask:
print (df1.mask(df1.eq(0)))
a b c d e f
0 NaN NaN 2106.0 NaN NaN NaN
1 NaN 2103.0 NaN NaN NaN NaN
2 NaN 2104.0 NaN NaN NaN NaN
3 NaN 2105.0 NaN NaN NaN NaN
4 2100.0 NaN NaN NaN NaN NaN
5 2101.0 NaN NaN NaN NaN NaN
6 2102.0 NaN NaN NaN NaN NaN
7 NaN NaN 2107.0 NaN NaN NaN
8 NaN NaN 2108.0 NaN NaN NaN
9 NaN NaN 2109.0 NaN NaN NaN
10 NaN NaN 2110.0 NaN NaN NaN
11 NaN NaN 2111.0 NaN NaN NaN
12 NaN NaN NaN 2112.0 NaN NaN
13 NaN NaN NaN 2113.0 NaN NaN
14 NaN NaN NaN 2114.0 NaN NaN
15 NaN NaN NaN NaN 2115.0 NaN
16 NaN NaN NaN NaN 2116.0 NaN
17 NaN NaN NaN NaN NaN 2117.0
18 NaN NaN NaN NaN NaN 2118.0
19 NaN NaN NaN NaN NaN 2119.0
20 NaN NaN NaN NaN 2120.0 NaN
Then forward filling missing values:
print (df1.mask(df1.eq(0)).ffill(axis=1))
a b c d e f
0 NaN NaN 2106.0 2106.0 2106.0 2106.0
1 NaN 2103.0 2103.0 2103.0 2103.0 2103.0
2 NaN 2104.0 2104.0 2104.0 2104.0 2104.0
3 NaN 2105.0 2105.0 2105.0 2105.0 2105.0
4 2100.0 2100.0 2100.0 2100.0 2100.0 2100.0
5 2101.0 2101.0 2101.0 2101.0 2101.0 2101.0
6 2102.0 2102.0 2102.0 2102.0 2102.0 2102.0
7 NaN NaN 2107.0 2107.0 2107.0 2107.0
8 NaN NaN 2108.0 2108.0 2108.0 2108.0
9 NaN NaN 2109.0 2109.0 2109.0 2109.0
10 NaN NaN 2110.0 2110.0 2110.0 2110.0
11 NaN NaN 2111.0 2111.0 2111.0 2111.0
12 NaN NaN NaN 2112.0 2112.0 2112.0
13 NaN NaN NaN 2113.0 2113.0 2113.0
14 NaN NaN NaN 2114.0 2114.0 2114.0
15 NaN NaN NaN NaN 2115.0 2115.0
16 NaN NaN NaN NaN 2116.0 2116.0
17 NaN NaN NaN NaN NaN 2117.0
18 NaN NaN NaN NaN NaN 2118.0
19 NaN NaN NaN NaN NaN 2119.0
20 NaN NaN NaN NaN 2120.0 2120.0
Select last column by position with DataFrame.iloc:
print (df1.mask(df1.eq(0)).ffill(axis=1).iloc[:, -1])
0 2106.0
1 2103.0
2 2104.0
3 2105.0
4 2100.0
5 2101.0
6 2102.0
7 2107.0
8 2108.0
9 2109.0
10 2110.0
11 2111.0
12 2112.0
13 2113.0
14 2114.0
15 2115.0
16 2116.0
17 2117.0
18 2118.0
19 2119.0
20 2120.0
Name: f, dtype: float64
And last use Series.map. | unknown | |
d19771 | test | I don't think Meteor's tracker works well with ReactJS, as their mechanism of re-render is different.
You might want to use this package.
https://github.com/meteor/react-packages/tree/devel/packages/react-meteor-data
You can use it like so.
import { Meteor } from 'meteor/meteor';
import { mount } from 'react-mounter';
import { withTracker } from 'meteor/react-meteor-data';
import { IndexPage } from "./index-page";
FlowRouter.route('/', {
action: () => {
mount(IndexPageContainer, {});
}
});
export const IndexPageContainer = withTracker(() => {
Meteor.subscribe('whatever');
return {
Meteor: {
collection: {
whatever: Whatever.find().fetch()
},
user: Meteor.user(),
userId: Meteor.userId(),
status: Meteor.status(),
loggingIn: Meteor.loggingIn()
}
};
})(IndexPage);
Where IndexPage is your actual component.
You can then access the db by this.props.Meteor.collection.whatever.find() | unknown | |
d19772 | test | As the exception says you have to
*
*either call the PostAsync with an absolute url
*or set the BaseAddress of the HttpClient
If you choose the second one all you need to do is this:
var httpClient = new HttpClient(_httpMessageHandler.Object);
httpClient.BaseAddress = new Uri("http://nonexisting.domain"); //New code
mockFactory.Setup(_ => _.CreateClient(It.IsAny<string>())).Returns(httpClient);
With this modification the exception will be gone.
But your test will fail because the response.Content will be null and that's why MyMethodAsync will return with null.
To fix this let's change the Setup to this:
public static async Task MyMethodAsync_Gets_True()
{
//Arrange
MyObject resultObject = new MyObject();
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(JsonConvert.SerializeObject(resultObject))
};
var _httpMessageHandler = new Mock<HttpMessageHandler>();
_httpMessageHandler.Protected()
.Setup<Task<HttpResponseMessage>>("SendAsync",
ItExpr.Is<HttpRequestMessage>(req => req.Method == HttpMethod.Post),
ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(response);
...
//Act
var result = await service.MyMethodAsync(arg1, arg2);
//Assert
Assert.NotNull(result);
} | unknown | |
d19773 | test | There is a question mark because the encoding process recognizes that the encoding can't support the character, and substitutes a question mark instead. By "if you're really good," he means, "if you have a newer browser and proper font support," you'll get a fancier substitution character, a box.
In Joel's case, he isn't trying to display a real character, he literally included the Unicode replacement character, U+FFFD REPLACEMENT CHARACTER.
A: It’s a rather confusing paragraph, and I don’t really know what the author is trying to say. Anyway, different browsers (and other programs) have different ways of handling problems with characters. A question mark “?” may appear in place of a character for which there is no glyph in the font(s) being used, so that it effectively says “I cannot display the character.” Browsers may alternatively use a small rectangle, or some other indicator, for the same purpose.
But the “�” symbol is REPLACEMENT CHARACTER that is normally used to indicate data error, e.g. when character data has been converted from some encoding to Unicode and it has contained some character that cannot be represented in Unicode. Browsers often use “�” in display for a related purpose: to indicate that character data is malformed, containing bytes that do not constitute a character, in the character encoding being applied. This often happens when data in some encoding is being handled as if it were in some other encoding.
So “�” does not really mean “unknown character”, still less “undisplayable character”. Rather, it means “not a character”.
A: A question mark appears when a byte sequence in the raw data does not match the data's character set so it cannot be decoded properly. That happens if the data is malformed, if the data's charset is explicitally stated incorrectly in the HTTP headers or the HTML itself, the charset is guessed incorrectly by the browser when other information is missing, or the user's browser settings override the data's charset with an incompatible charset.
A box appears when a decoded character does not exist in the font that is being used to display the data.
A: Just what it says - some browsers show "a weird character" or a question mark for characters outside of the current known character set. It's their "hey, I don't know what this is" character. Get an old version of Netscape, paste some text form Microsoft Word which is using smart quotes, and you'll get question marks.
http://blog.salientdigital.com/2009/06/06/special-characters-showing-up-as-a-question-mark-inside-of-a-black-diamond/ has a decent explanation. | unknown | |
d19774 | test | You should import the mysql.connector package. I think you might find this tutorial helpful. | unknown | |
d19775 | test | You don't have a class as much as you have a dictionary of string and objects. If you do the following, you should be able to deserialize properly:
public class PeopleResponse
{
public Dictionary<string, Info> people { get; set; }
public string hede { get; set; }
public string hodo { get; set; }
}
public class Info
{
public string condition { get; set; }
public string version { get; set; }
}
From there, you should be able to do:
var results = JsonConvert.DeserializeObject<PeopleResponse>("{myJSONGoesHere}");
Edit: Based on your updated question, if you would like to get the names of all whose condition is "good," you can do the following (assuming your deserialized object is called results:
var goodStuff = from p in results.people
where p.Value.condition.ToLower() == "good"
select p.Key;
You could, of course, just get p instead of p.Key, which would return the entire key/value pair. | unknown | |
d19776 | test | You can access props like you can data properties, you don't have to do this.props.for you can just do this.for and it will work in the same way.
However, It's worth noting, you can't modify props directly in a child component, you'd have to emit an event for that.
From the Vue docs:
All props form a one-way-down binding between the child property and the parent one: when the parent property updates, it will flow down to the child, but not the other way around. This prevents child components from accidentally mutating the parent’s state, which can make your app’s data flow harder to understand.
In addition, every time the parent component is updated, all props in the child component will be refreshed with the latest value. This means you should not attempt to mutate a prop inside a child component. If you do, Vue will warn you in the console.
Read this article for more info on how to mutate props: https://www.telerik.com/blogs/how-to-emit-data-in-vue-beyond-the-vuejs-documentation | unknown | |
d19777 | test | You can do the reshape manually.
*
*Delete z.reshape(20,5). This is not going to work with an array of arrays.
*After applying the function, use this instead:
# Create a empty matrix with desired size
matrix = np.zeros(shape=(20,5))
# Iterate over z and assign each array to a row in the numpy matrix.
for i,arr in enumerate(z):
matrix[i] = arr
If you don't know the desired size for the matrix. Create the matrix as matrix = np.zeros(shape=df.shape).
All the code used:
import numpy as np
import pandas as pd
rng = np.random.default_rng(seed=22)
df = pd.DataFrame(rng.random((20,5)))
def new_vectors(current, best, worst):
#convert current to numpy array
current = current.to_numpy()
#construct a new vector to check
new = np.add(current, np.subtract((rng.random()*(np.subtract(best, np.absolute(current)))), ((rng.random()*(np.subtract(worst, np.absolute(current)))))))
#get the new sum for the new and old vectors
summed = current.sum()
newsummed = new.sum()
#return the smallest one
return np.add(((newsummed < summed)*(new)), ((newsummed > summed)*(current))).flatten()
z = np.array(df.apply(new_vectors, args=(df.iloc[0].to_numpy(), df.iloc[11].to_numpy()), axis=1))
matrix = np.zeros(shape=df.shape)
for i,arr in enumerate(z):
matrix[i] = arr
A: Your original dataframe - with reduced length for display purposes:
In [628]: df = pd.DataFrame(rng.random((4,5)))
In [629]: df
Out[629]:
0 1 2 3 4
0 0.891169 0.134904 0.515261 0.975586 0.150426
1 0.834185 0.671914 0.072134 0.170696 0.923737
2 0.065445 0.356001 0.034787 0.257711 0.213964
3 0.790341 0.080620 0.111369 0.542423 0.199517
The next frame:
In [631]: df1=df.apply(new_vectors, args=(df.iloc[0].to_numpy(), df.iloc[3].to_numpy()), axis=1)
In [632]: df1
Out[632]:
0 [0.891168725430691, 0.13490384333565053, 0.515...
1 [0.834184861872087, 0.6719141503303373, 0.0721...
2 [0.065444520313796, 0.35600115939269394, 0.034...
3 [0.7903408924058509, 0.08061955595765169, 0.11...
dtype: object
Note that it has 1 column, that contains arrays. Make an array from it:
In [633]: df1.to_numpy()
Out[633]:
array([array([0.89116873, 0.13490384, 0.51526113, 0.97558562, 0.15042584]),
array([0.83418486, 0.67191415, 0.07213404, 0.17069617, 0.92373724]),
array([0.06544452, 0.35600116, 0.03478695, 0.25771129, 0.21396367]),
array([0.79034089, 0.08061956, 0.1113691 , 0.54242262, 0.19951741])],
dtype=object)
That is (4,) object dtype. That dtype is important. Even though the elements all have 5 elements themselves, reshape does not work across that "object" boundary. We can't reshape it to (4,5).
But we can concatenate those arrays:
In [636]: np.vstack(df1.to_numpy())
Out[636]:
array([[0.89116873, 0.13490384, 0.51526113, 0.97558562, 0.15042584],
[0.83418486, 0.67191415, 0.07213404, 0.17069617, 0.92373724],
[0.06544452, 0.35600116, 0.03478695, 0.25771129, 0.21396367],
[0.79034089, 0.08061956, 0.1113691 , 0.54242262, 0.19951741]]) | unknown | |
d19778 | test | You can try this:
*
*Wrap them inside a common div which you set position:relative; on
*Then set position:absolute; for both the canvas elements inside that div element
*Use left:0;top:0; (unit not needed when 0) to adjust the position for the canvases if necessary
Using relative on parent element makes the absolute positioned elements inside it relative to it. If you use relative on both you would need to adjust the position for one of them (as you already discovered). | unknown | |
d19779 | test | Artisan::call('migrate', array('--path' => 'app/migrations'));
will work in Laravel 5, but you'll likely need to make a couple tweaks.
First, you need a use Artisan; line at the top of your file (where use Illuminate\Support\ServiceProvider... is), because of Laravel 5's namespacing. (You can alternatively do \Artisan::call - the \ is important).
You likely also need to do this:
Artisan::call('migrate', array('--path' => 'app/migrations', '--force' => true));
The --force is necessary because Laravel will, by default, prompt you for a yes/no in production, as it's a potentially destructive command. Without --force, your code will just sit there spinning its wheels (Laravel's waiting for a response from the CLI, but you're not in the CLI).
I'd encourage you to do this stuff somewhere other than the boot method of a service provider. These can be heavy calls (relying on both filesystem and database calls you don't want to make on every pageview). Consider an explicit installation console command or route instead.
A: After publishing the package:
php artisan vendor:publish --provider="Packages\Namespace\ServiceProvider"
You can execute the migration using:
php artisan migrate
Laravel automatically keeps track of which migrations have been executed and runs new ones accordingly.
If you want to execute the migration from outside of the CLI, for example in a route, you can do so using the Artisan facade:
Artisan::call('migrate')
You can pass optional parameters such as force and path as an array to the second argument in Artisan::call.
Further reading:
*
*https://laravel.com/docs/5.1/artisan
*https://laravel.com/docs/5.2/migrations#running-migrations
A: For the Laravel 7(and probably 6):
use Illuminate\Support\Facades\Artisan;
Artisan::call('migrate');
will greatly work. | unknown | |
d19780 | test | Mark's pattern for dialogs looks like a pretty ugly and poorly thought out solution to me, despite the lengthy article he has written.
You are getting a sort of deadlock on the UI thread and need to wrap the showing of the new window in Dispatcher.BeginInvoke so that it is executed asynchronously and allows the dispatcher thread to continue processing.
Something like this:
Dispatcher.BeginInvoke(new Action(() => new CustomDialogWindow {DataContext = parent.DataContext}.ShowDialog()); | unknown | |
d19781 | test | I finally solve the problem. I don't know why W3 Total Cache create problems with the jquerys. This was the error on some parts of the web:
Uncaught TypeError: $ is not a function
So I fix it adding this: jQuery(function($)...) instead of function() and now is ok.
I don't know why this happened, all the other pages are working ok, and as I said the only thing that was diferent with this was that plugin. | unknown | |
d19782 | test | Use an array instead:
bool[] abc;
// ...
if (abc[counter] == true) {
{
// some code.
} | unknown | |
d19783 | test | This works for me but I am not sure if it's the creator's intention.
from google.cloud import monitoring_v3
from google.cloud.monitoring_v3 import query
project = "..."
client = monitoring_v3.MetricServiceClient()
result = query.Query(
client,
project,
'pubsub.googleapis.com/subscription/num_undelivered_messages',
minutes=1).as_dataframe()
A: You might need to run your code this way for a specific subscription:
from google.cloud import monitoring_v3
from google.cloud.monitoring_v3 import query
project = "my-project"
client = monitoring_v3.MetricServiceClient()
result = query.Query(client,project,'pubsub.googleapis.com/subscription/num_undelivered_messages', minutes=60).as_dataframe()
print(result['pubsub_subscription'][project]['subscription_name'][0]) | unknown | |
d19784 | test | Just put the ORDER BY at the end of your chain of SELECT ... FROM ... UNION ALL statements:
SELECT [StationID],
[LastDistribution]
FROM [DB1].[dbo].[ProcessingStations]
UNION ALL
SELECT [StationID],
[LastDistribution]
FROM [DB2].[dbo].[ProcessingStations]
UNION ALL
SELECT [StationID],
[LastDistribution]
FROM [DB3].[dbo].[ProcessingStations]
UNION ALL
SELECT [StationID],
[LastDistribution]
FROM [DB4].[dbo].[ProcessingStations]
UNION ALL
SELECT [StationID],
[LastDistribution]
FROM [DB5].[dbo].[ProcessingStations]
ORDER BY [StationID]
UNION ALL
SELECT [StationID],
[LastDistribution]
FROM [DB6].[dbo].[ProcessingStations]
UNION ALL
SELECT [StationID],
[LastDistribution]
FROM [DB7].[dbo].[ProcessingStations]
UNION ALL
SELECT [StationID],
[LastDistribution]
FROM [DB8].[dbo].[ProcessingStations]
ORDER BY StationID
Here's a quick example I did in SSMS:
DECLARE @a table (x int)
DECLARE @b table (x int)
DECLARE @c table (x int)
insert into @a values (5)
insert into @a values (4)
insert into @a values (3)
insert into @b values (0)
insert into @b values (1)
insert into @b values (2)
insert into @c values (0)
insert into @c values (1)
insert into @c values (2)
select * from @a
union all
select * from @b
union all
select * from @c
order by x
And here's the output:
x
-----
0
0
1
1
2
2
3
4
5
As you can see, even though the SELECT * FROM @a came first, it still placed those last in the result set
A: Why can't you use a CTE?. Anyway, you still can do the same using a derived table:
SELECT *
FROM ( SELECT [StationID],
[LastDistribution]
FROM [DB1].[dbo].[ProcessingStations]
UNION ALL
SELECT [StationID],
[LastDistribution]
FROM [DB2].[dbo].[ProcessingStations]
UNION ALL
SELECT [StationID],
[LastDistribution]
FROM [DB3].[dbo].[ProcessingStations]
UNION ALL
SELECT [StationID],
[LastDistribution]
FROM [DB4].[dbo].[ProcessingStations]
UNION ALL
SELECT [StationID],
[LastDistribution]
FROM [DB5].[dbo].[ProcessingStations]
UNION ALL
SELECT [StationID],
[LastDistribution]
FROM [DB6].[dbo].[ProcessingStations]
UNION ALL
SELECT [StationID],
[LastDistribution]
FROM [DB7].[dbo].[ProcessingStations]
UNION ALL
SELECT [StationID],
[LastDistribution]
FROM [DB8].[dbo].[ProcessingStations]) A
ORDER BY StationID
A: See the fiddle, just put the ORDER BY on the last set to be "unioned". It achieves the same result without the overhead of the CTE.
The order will effect the entire unified set.
SELECT
[StationID],
[LastDistribution]
FROM
[dbo].[ProcessingStations]
UNION ALL
SELECT
[StationID],
[LastDistribution]
FROM
[dbo].[ProcessingStations]
UNION ALL
SELECT
[StationID],
[LastDistribution]
FROM
[dbo].[ProcessingStations]
ORDER BY
[StationID] | unknown | |
d19785 | test | Please never run a networking operation on the main (UI) thread .
Main thread is used to:
*
*interact with user.
*render UI components.
any long operation on it may risk your app to be closed with ANR message.
Take a look at the following :
*
*Keeping your application Responsive
*NetworkOnMainThreadException
you can easily use an AsyncTask or a Thread to perform your network operations.
Here is a great tutorial about threads and background work in android: Link
A: Works for me:
Manifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
.java:
private static boolean DEVELOPER_MODE = true;
...
protected void onCreate(Bundle savedInstanceState) {
if (DEVELOPER_MODE) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork() // or .detectAll() for all detectable problems
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects()
.penaltyLog()
.penaltyDeath()
.build());
}
...
hope it helps.
see also : http://developer.android.com/reference/android/os/StrictMode.html | unknown | |
d19786 | test | The error you saw is usually caused by not upgrading the database workload standard to match the version of your worklight pattern.
Can you please check following things?
a) Have you installed the database workload standard shipped with 6.1?
http://pic.dhe.ibm.com/infocenter/wrklight/v6r1m0/topic/com.ibm.worklight.deploy.doc/pureapp/t_pureapp_installing_DB_workload_standards.html
b) Did you explicitly re-selected the workload standard in virtual application builder after importing the sample pattern? There is an issue with DB2 component that database workload standard is not selected correctly when importing the pattern zip. So to workaround this, you need to make sure the imported pattern has selected correct database workload standard
http://pic.dhe.ibm.com/infocenter/wrklight/v6r1m0/topic/com.ibm.worklight.deploy.doc/pureapp/t_pureapp_importing_sample_wl_application_pattern.html | unknown | |
d19787 | test | i tested your file :
with $row['user_name']
C:\Apps\PHP>php c:\temp\test.php
PHP Notice: Undefined index: user_name in C:\temp\test.php on line 25
Notice: Undefined index: user_name in C:\temp\test.php on line 25
<?xml version="1.0" encoding="UTF-8"?>
<EMPLOYEES>Root<EMPLOYEE id="">emp</EMPLOYEE></EMPLOYEES>
with $row['USER_NAME']
C:\Apps\PHP>php c:\temp\test.php
<?xml version="1.0" encoding="UTF-8"?>
<EMPLOYEES>Root<EMPLOYEE id="007144">emp</EMPLOYEE></EMPLOYEES>
does that solve your problem?
edit:
for solution 1 (PLSQL side)
$s = oci_parse($c, $q);
oci_execute($s, OCI_DEFAULT);
$r = oci_fetch_array($s, OCI_RETURN_NULLS+OCI_RETURN_LOBS);
echo "<pre>";
echo htmlentities($r["XML"]);
echo "</pre>";
or to give more control over the names of elements
$q = "select xmlelement(
\"EMPLOYEES\",
xmlagg(
xmlelement(
\"EMPLOYEE\",
xmlforest(user_name as \"EmpName\",
id as \"EmpID\",
email as \"email\"
)
)
)
).getclobval() xml
from fnd_user";
$s = oci_parse($c, $q);
oci_execute($s, OCI_DEFAULT);
$r = oci_fetch_array($s, OCI_RETURN_NULLS+OCI_RETURN_LOBS);
echo "<pre>";
echo htmlentities($r["XML"]);
echo "</pre>";
example output with xmlforest version is:
C:\Apps\PHP>php c:\temp\test3.php
<pre><EMPLOYEES><EMPLOYEE><EmpName>John Doe</EmpName><EmpID>1</EmpID><email>[email protected]</email></EMPLOYEE><EMPLOYEE><
EmpName>Alan Smith</EmpName><EmpID>2</EmpID><email>[email protected]</email></EMPLOYEE></EMPLOYEES></pre>
C:\Apps\PHP>
ie:
<EMPLOYEES>
<EMPLOYEE>
<EmpName>John Doe</EmpName>
<EmpID>1</EmpID>
<email>[email protected]</email>
</EMPLOYEE>
<EMPLOYEE>
<EmpName>Alan Smith</EmpName>
<EmpID>2</EmpID>
<email>[email protected]</email>
</EMPLOYEE>
</EMPLOYEES>
A: Finally, I get this XML
<?php
//File: DOM.php
$db="(DESCRIPTION=
(ADDRESS_LIST=
(ADDRESS=(PROTOCOL=TCP)
(HOST=xxx)(PORT=1530)
)
)
(CONNECT_DATA=(SID=DEV))
)";
$conn = OCILogon("uname","pass",$db);
if ($conn) {
//echo "Successfully connected to Oracle.";
} else {
$err = oci_error();
echo "Oracle Connect Error " . $err['text'];
}
//$dept_id = 007144;
$query = "SELECT user_name from fnd_user where user_name = '007144'";
$stmt = oci_parse($conn,$query);
//oci_bind_by_name($stmt, ':deptid', $dept_id);
if (!oci_execute($stmt, OCI_DEFAULT)) {
$err = oci_error($stmt);
trigger_error('Query failed: ' . $err['message'], E_USER_ERROR);
}
$dom = new DOMDocument('1.0', 'UTF-8');
$root = $dom->createElement('EMPLOYEES', '');
$dom->appendChild($root);//$root = $dom->appendChild($root);
while ($row = oci_fetch_array($stmt, OCI_RETURN_NULLS))
{
//var_dump($row);
//$emp = $dom->createElement('EMPLOYEE', 'emp');
//$emp = $root->appendChild($emp);
//$emp->setAttribute('id', $row['EMPLOYEE_NUMBER']);
$emp = $dom->createElement('EMPLOYEE', '');
$emp = $root->appendChild($emp);
//$emp->setAttribute('id', $row['FULL_NAME']);
$EmpName = $dom->createElement('EmpName', $row['FULL_NAME']);
$EmpName = $emp->appendChild($EmpName);
$empid = $dom->createElement('EmpID', $row['EMPLOYEE_NUMBER']);
$empid = $emp->appendChild($empid);
$email = $dom->createElement('email', $row['EMAIL_ADDRESS']);
$email = $emp->appendChild($email);
}
echo $dom->saveXML();
$dom->save("employees.xml");
oci_close($conn);
?>
And the result here:
http://filedb.experts-exchange.com/incoming/2012/11_w47/617768/XMLinPHP4.jpg
Now, I will start parsing this XML and I hope it will work out in the end, otherwise i will come back and disturb you again, Sorry :(
I will let you know tomorrow, Wait for me :) | unknown | |
d19788 | test | In mysql you can't use same table in query during update,this can be done by giving the new alias to your subquery
UPDATE tombaldi_2bj3de9ad.catalog_product_option_type_value
SET catalog_product_option_type_value.option_id = '72'
WHERE catalog_product_option_type_value.option_id
IN (SELECT t.option_id
FROM (
SELECT catalog_product_option_type_value.option_id
FROM tombaldi_2bj3de9ad.catalog_product_option_type_title
INNER JOIN tombaldi_2bj3de9ad.catalog_product_option_type_value
ON catalog_product_option_type_title.option_type_id = catalog_product_option_type_value.option_type_id
WHERE ( CONVERT( title USING utf8 ) LIKE '%initials%' )
) t
)
Or even better to use join in your update query
UPDATE
tombaldi_2bj3de9ad.catalog_product_option_type_value cv
JOIN tombaldi_2bj3de9ad.catalog_product_option_type_title ct
ON(ct.option_type_id = cv.option_type_id )
SET
cv.option_id = '72'
WHERE CONVERT(ct.title USING utf8) LIKE '%initials%' | unknown | |
d19789 | test | This doesn't answer the question as it was asked, but I'll risk my reputation and suggest a different solution.
PLEASE, do yourself a favor and never use MessageBox() or other modal UI to display debug information. If you do want to interrupt program execution at that point, use the breakpoint; it also allows you to attach the condition, so that you don't need to examine the value manually.
If you do not want the interruption, just print the value to a debug output window using ::OutputDebugString(). That can be seen in the debugger if it is attached, or via DebugView tool.
Another small suggestion (for Visual Studio users): if you prepend your output with a source file name and the code line number, double-clicking on that line in the output window will take you straight to that line. Just use __FILE__ and __LINE__ in your formatted string.
A: You can't. The preprocessor doesn't know anything about variables or their values, because it doesn't do anything run-time only at compile-time.
A: You can use variable argument list
#include <stdio.h>
void message(const char* format, ...)
{
int len;
char *buf;
va_list args;
va_start(args, format);
len = _vscprintf(format, args) + 1; //add room for terminating '\0'
buf = (char*)malloc(len * sizeof(char));
vsprintf_s(buf, len, format, args);
MessageBoxA(0,buf,"debug",0);
//OutputDebugStringA(buf);
free(buf);
}
message("test %s %d %d %d", "str", 1, 2, 3);
You might also want to change to unicode version.
A: You need to "print" the variable to a buffer (array of char) using something like sprintf (or snprintf in VS 2015) and pass the resulting output to MessageBox as the string to be displayed. | unknown | |
d19790 | test | Just get the instance of the Room and call the method.
The hard-coding method will be like this:
Room toBook = null;
for (Room r : rooms) {
if (r.getRoomId().equals(roomId))
toBook = r;
}
if (toBook != null) {
if (toBook.bookRoom(customerID, nightsRequired)) {
// room booked succesfully
} else {
// can't book the room
}
} else {
// room does not exists
}
But, as long as this will be a bigger app I recommend you to code your own equals method then Arrays.contains() will find the Room.
Room toBook = new Room(roomid);
if (rooms.contains(toBook) && toBook.bookRoom(customerID, nightsRequired)){
// room booked succesfully
} else if (rooms.contains(toBook)) {
// can't book the room
} else {
// room does not exists
}
A: Add the code at the end of the main() method in Test class
Room r=null;
boolean val=false;
for(int i=0;i<rooms.length;i++){
if(rooms[i].getRoomId().equals(roomId)){
r=new Room(rooms[i].getRoomId(), rooms[i].getDescription(), rooms[i].getDailyRate());
r.bookRoom(customerID, nightsRequired);
val=true;
break;
}
}
if(val){
r.print();
} | unknown | |
d19791 | test | It is really simple.
After you create your Intent variable, before starting activity add a flag to it like below
Intent launch = new Intent(this, MyActivity.class);
launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(launch);
With this above code you can call activity from service | unknown | |
d19792 | test | Yes, the cell will release the accessory view and you do not have a leak in the example.
A: The property accessoryView of a UITableViewCell is a retain type, in common with many view properties in the kit. Check the Apple documentation for UITableViewCell to convince yourself of this. Therefore there will be no leak in your example - the retain count has been correctly managed. You've also correctly released after setting the accessory view, on account of your alloc call. | unknown | |
d19793 | test | The reason you can't do this is that we don't yet expose any app-only permissions to access OneDrive files. This is something we are working on and hope to expose very soon. Please stay tuned to our blog posts where we'll let folks know when this capability is added.
Hope this helps,
A: I am using AAD v2, registered the app in Microsoft App registration portal. Once the admin gives consent to the app via the app consent url that contains tenant id and client id, the app can access to all users drives and files with App Mod permissions. So your scenario is possible now, just wanted to add that information since the accepted answer seems outdated. | unknown | |
d19794 | test | <?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>
<xsl:variable name="num1" select="substring(catalog/cd/year,string-length(catalog/cd/year) - 3)" />
I want last 4 characters, so I did a minus 3. If its last n characters, do minus n-1
<xsl:variable name="num2" select="2" />
<xsl:value-of select="$num1 - $num2" />
</body>
</html>
</xsl:template>
</xsl:stylesheet> | unknown | |
d19795 | test | Getting the line number with grep so you can pass it to sed is an antipattern. You want to do all the processing in sed.
sed -e '/happy/i\\' -e '/sad/i\\' file
If indeed the action is the same in both cases, you can conflate it to a single regular expression.
sed '/\(happy\|sad\)/i\\' file
(The precise syntax will vary between sed dialects but you get the idea. If your sed has -r or -E you can avoid the backslashes.)
A: Your first problem is that "$gi" is looking for the variable $gi, which doesn't exist. To avoid that, you have to either put curly braces around the variable name, as in "${g}i", or put a space between the variable name and the sed command, as in "$g i".
Then, because your tests that work use single quotes, the double backslash is interpreted literally. In double quotes, backslashes have to be escaped, resulting in
sed "${h}i\\\\" test
And finally, it seems this is overly complicated. To insert a blank line before a line containing a pattern, you can use this (for the example happy):
sed '/happy/s/^/\n/' test
This "replaces" the beginning of the line with a newline if the line matches happy.
Notice that inserting a newline like this doesn't work with every sed; for macOS sed, you could probably use something like
sed 'happy/s/^/'$'\n''/' test
A: This should work perfectly. I tested it on Ubuntu with no issues.
number=3
sed $number'i\\' test.txt
Regards! | unknown | |
d19796 | test | The simple answer to this is to cast the item that you pass to array_keys() to an explicit (array) - that way, arrays are unaffected but objects become the correct type:
$this->columns = empty($this->rows) ? array() : array_keys((array) $this->rows[0]);
A: getColumnMeta can retrieve the name of a column, it returns an associative array containing amongst others the obvious "name" key.
so
$meta = $this->result->getColumnMeta(0); // 0 indexed so 0 would be first column
$name = $meta['name']; | unknown | |
d19797 | test | Since its a daterange picker you choose a range.
I guess from the moment you choose the starting date, the ending date cannot be older than the starting one. | unknown | |
d19798 | test | When you call $runspace.PowerShell.Dispose(), the PowerShell instance is disposed, but the runspace that it's tied to is not automatically disposed, you'll need to do that first yourself in the cleanup task:
$runspace.powershell.EndInvoke($runspace.Runspace) | Out-Null
$runspace.powershell.Runspace.Dispose() # remember to clean up the runspace!
$runspace.powershell.dispose() | unknown | |
d19799 | test | substr() is the key to your answer here.
You will want to loop through the input string 10 characters at a time to create each line.
<?php
$input = 'hola como estas 0001 hola 02hola como estas';
$output = '';
$stringLength = strlen($input) / 10; // 10 is for number of characters per line
$linesProcessed = 0;
while ($linesProcessed < $stringLength) {
$output .= substr($input, ($linesProcessed * 10), 10) . PHP_EOL;
$linesProcessed++;
}
echo $output;
The output is:
hola como
estas 0001
hola 02ho
la como es
tas
(Note: Use nl2br() or use the CSS style whitespace: pre if you're displaying this in HTML). | unknown | |
d19800 | test | One of the primary benefits of offloading the base component to the App component (your 2nd example, with the render function) is to clearly separate the processes of app instantiation / entry from the details of the base component.
For smaller projects, or when using the CDN, this might not seem necessary. But in larger projects with Vue CLI, main.js can become lengthy and it becomes increasingly difficult to combine both the app instantiation and the root component into one file.
Without that separation, main.js would serve a double purpose of both loading the app and creating a component.
Generally speaking, it's good practice to separate unrelated functionality in projects into separate files for easier maintenance and collaboration, and better clarity.
A: If neither render function nor template option is present, the in-DOM HTML of the mounting DOM element will be extracted as the template. In this case, Runtime + Compiler build of Vue should be used.
---- https://v2.vuejs.org/v2/api/index.html#el
Your 1nd example needs a Compiler to compile html in runtime. | unknown |