Native Java 8 arrives on android! Finally!
remove the Retrolambda plugin and retrolambda block from each module's build.gradle file:
To disable Jack and switch to the default toolchain, simply remove the jackOptions block from your module’s build.gradle file
To start using supported Java 8 language features, update the Android plugin to 3.0.0 (or higher)
Starting with Android Studio 3.0 , Java 8 language features are now natively supported by android:
Also from min API level 24 the following Java 8 API are available:
Add these lines to your application module’s build.gradle to inform the project of the language level:
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
Disable Support for Java 8 Language Features by adding the following to your gradle.properties file:
android.enableDesugar=false
You’re done! You can now use native java8!
Below code from Python | How to Count the frequency of a word in the text file? worked for me.
import re
frequency = {}
#Open the sample text file in read mode.
document_text = open('sample.txt', 'r')
#convert the string of the document in lowercase and assign it to text_string variable.
text = document_text.read().lower()
pattern = re.findall(r'\b[a-z]{2,15}\b', text)
for word in pattern:
count = frequency.get(word,0)
frequency[word] = count + 1
frequency_list = frequency.keys()
for words in frequency_list:
print(words, frequency[words])
Instead of String you are trying to get custom POJO object details as output by calling another API/URI, try the this solution. I hope it will be clear and helpful for how to use RestTemplate also,
In Spring Boot, first we need to create Bean for RestTemplate under the @Configuration annotated class. You can even write a separate class and annotate with @Configuration like below.
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
}
Then, you have to define RestTemplate with @Autowired or @Injected under your service/Controller, whereever you are trying to use RestTemplate. Use the below code,
@Autowired
private RestTemplate restTemplate;
Now, will see the part of how to call another api from my application using above created RestTemplate. For this we can use multiple methods like execute(), getForEntity(), getForObject() and etc. Here I am placing the code with example of execute(). I have even tried other two, I faced problem of converting returned LinkedHashMap into expected POJO object. The below, execute() method solved my problem.
ResponseEntity<List<POJO>> responseEntity = restTemplate.exchange(
URL,
HttpMethod.GET,
null,
new ParameterizedTypeReference<List<POJO>>() {
});
List<POJO> pojoObjList = responseEntity.getBody();
Happy Coding :)
I've had decent success with parsing text files generated by the pdftotext utility (sudo apt-get install poppler-utils).
File convertPdf() throws Exception {
File pdf = new File("mypdf.pdf");
String outfile = "mytxt.txt";
String proc = "/usr/bin/pdftotext";
ProcessBuilder pb = new ProcessBuilder(proc,"-layout",pdf.getAbsolutePath(),outfile);
Process p = pb.start();
p.waitFor();
return new File(outfile);
}
verpatch is good, but doesn't handle unicode characters...
try ResourceLib
I just want to add what worked for me, I added height and width to both divs and used bootstrap to make it responsive
<div class="col-lg-1 mapContainer">
<div id="map"></div>
</div>
#map{
height: 100%;
width:100%;
}
.mapContainer{
height:200px;
width:100%
}
in order for col-lg-1
to work add bootstrap reference located
Here
Integer x=10;
Double y = x.doubleValue();
You can include it in the same where statement with the && operator...
x=> x.Lists.Include(l => l.Title).Where(l=>l.Title != String.Empty
&& l.InternalName != String.Empty)
You can use any of the comparison operators (think of it like doing an if statement) such as...
List<Int32> nums = new List<int>();
nums.Add(3);
nums.Add(10);
nums.Add(5);
var results = nums.Where(x => x == 3 || x == 10);
...would bring back 3 and 10.
In my case it turns out my
new server was running MySQL 5.5
,
old server was running MySQL 5.6
.
So I got this error when trying to import the .sql
file I'd exported from my old server.
MySQL 5.5 does not support utf8mb4_unicode_520_ci
, but
MySQL 5.6 does.
Updating to MySQL 5.6
on the new server solved collation the error !
If you want to retain MySQL 5.5, you can:
- make a copy of your exported .sql
file
- replace instances of utf8mb4unicode520_ci
and utf8mb4_unicode_520_ci
...with utf8mb4_unicode_ci
- import your updated .sql
file.
You use something like
from flask import send_file
@app.route('/get_image')
def get_image():
if request.args.get('type') == '1':
filename = 'ok.gif'
else:
filename = 'error.gif'
return send_file(filename, mimetype='image/gif')
to send back ok.gif
or error.gif
, depending on the type query parameter. See the documentation for the send_file
function and the request
object for more information.
Using tidyverse
df %>% tidyr::gather("id", "value", 1:4) %>%
ggplot(., aes(Xax, value))+
geom_point()+
geom_smooth(method = "lm", se=FALSE, color="black")+
facet_wrap(~id)
DATA
df<- read.table(text =c("
A B C G Xax
0.451 0.333 0.034 0.173 0.22
0.491 0.270 0.033 0.207 0.34
0.389 0.249 0.084 0.271 0.54
0.425 0.819 0.077 0.281 0.34
0.457 0.429 0.053 0.386 0.53
0.436 0.524 0.049 0.249 0.12
0.423 0.270 0.093 0.279 0.61
0.463 0.315 0.019 0.204 0.23"), header = T)
Rob's solution is very nice, only thing that in his -(void)adjustHeightOfTableview
method the calling of
[self.view needsUpdateConstraints]
does nothing, it just returns a flag, instead calling
[self.view setNeedsUpdateConstraints]
will make the desired effect.
I will add for those that get stuck trying to run PHP
(Laravel
in may case) or other unique IIS
hosting situation with the 405 error
, that you need to change the verbs
in the handler for that for that specific situation... so since I was using PHP
I went to the PHP
handler and in the Request Restrictions
, then Verbs
tab, add the verbs
you need. This was all I needed to add to the web.config
to enable CORS
in Laravel
.
<handlers>
<remove name="php-5.6.40" />
<add name="php-5.6.40" path="*.php" verb="GET,HEAD,POST,PUT,DELETE,OPTIONS" modules="FastCgiModule" scriptProcessor="C:\Program Files (x86)\PHP\v5.6\php-cgi.exe" resourceType="Either" requireAccess="Script" />
</handlers>
I'd suggest try the change event? test to see if it has a value if it does then you can continue with your code. jQuery has
.bind("change", function(){ ... });
Or
.change(function(){ ... });
which are equivalents.
for a unique selector change your name attribute to id and then jQuery("#imafile")
or a general jQuery('input[type="file"]')
for all the file inputs
let weekday = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][new Date().getDay()]
I would like to add a new pure javascript
way to do this, which in my opinion is much cleaner, by using the fetch()
API. This a modern way to implements network requests. In your case, since you already have a form element
we can simply use it to build our request.
const formInputs = oForm.getElementsByTagName("input");
let formData = new FormData();
for (let input of formInputs) {
formData.append(input.name, input.value);
}
fetch(oForm.action,
{
method: oForm.method,
body: formData
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error.message))
.finally(() => console.log("Done"));
As you can see it is very clean and much less verbose to use than XMLHttpRequest
.
public String[] concat(String[]... arrays)
{
int length = 0;
for (String[] array : arrays) {
length += array.length;
}
String[] result = new String[length];
int destPos = 0;
for (String[] array : arrays) {
System.arraycopy(array, 0, result, destPos, array.length);
destPos += array.length;
}
return result;
}
Here is some code that will return the installed .NET details:
<%@ Page Language="VB" Debug="true" %>
<%@ Import namespace="System" %>
<%@ Import namespace="System.IO" %>
<%
Dim cmnNETver, cmnNETdiv, aspNETver, aspNETdiv As Object
Dim winOSver, cmnNETfix, aspNETfil(2), aspNETtxt(2), aspNETpth(2), aspNETfix(2) As String
winOSver = Environment.OSVersion.ToString
cmnNETver = Environment.Version.ToString
cmnNETdiv = cmnNETver.Split(".")
cmnNETfix = "v" & cmnNETdiv(0) & "." & cmnNETdiv(1) & "." & cmnNETdiv(2)
For filndx As Integer = 0 To 2
aspNETfil(0) = "ngen.exe"
aspNETfil(1) = "clr.dll"
aspNETfil(2) = "KernelBase.dll"
If filndx = 2
aspNETpth(filndx) = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), aspNETfil(filndx))
Else
aspNETpth(filndx) = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Microsoft.NET\Framework64", cmnNETfix, aspNETfil(filndx))
End If
If File.Exists(aspNETpth(filndx)) Then
aspNETver = Diagnostics.FileVersionInfo.GetVersionInfo(aspNETpth(filndx))
aspNETtxt(filndx) = aspNETver.FileVersion.ToString
aspNETdiv = aspNETtxt(filndx).Split(" ")
aspNETfix(filndx) = aspNETdiv(0)
Else
aspNETfix(filndx) = "Path not found... No version found..."
End If
Next
Response.Write("Common MS.NET Version (raw): " & cmnNETver & "<br>")
Response.Write("Common MS.NET path: " & cmnNETfix & "<br>")
Response.Write("Microsoft.NET full path: " & aspNETpth(0) & "<br>")
Response.Write("Microsoft.NET Version (raw): " & aspNETtxt(0) & "<br>")
Response.Write("<b>Microsoft.NET Version: " & aspNETfix(0) & "</b><br>")
Response.Write("ASP.NET full path: " & aspNETpth(1) & "<br>")
Response.Write("ASP.NET Version (raw): " & aspNETtxt(1) & "<br>")
Response.Write("<b>ASP.NET Version: " & aspNETfix(1) & "</b><br>")
Response.Write("OS Version (system): " & winOSver & "<br>")
Response.Write("OS Version full path: " & aspNETpth(2) & "<br>")
Response.Write("OS Version (raw): " & aspNETtxt(2) & "<br>")
Response.Write("<b>OS Version: " & aspNETfix(2) & "</b><br>")
%>
Here is the new output, cleaner code, more output:
Common MS.NET Version (raw): 4.0.30319.42000
Common MS.NET path: v4.0.30319
Microsoft.NET full path: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\ngen.exe
Microsoft.NET Version (raw): 4.6.1586.0 built by: NETFXREL2
Microsoft.NET Version: 4.6.1586.0
ASP.NET full path: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\clr.dll
ASP.NET Version (raw): 4.7.2110.0 built by: NET47REL1LAST
ASP.NET Version: 4.7.2110.0
OS Version (system): Microsoft Windows NT 10.0.14393.0
OS Version full path: C:\Windows\system32\KernelBase.dll
OS Version (raw): 10.0.14393.1715 (rs1_release_inmarket.170906-1810)
OS Version: 10.0.14393.1715
Use:
window.location.replace(...)
See this Stack Overflow question for more information:
How do I redirect to another webpage?
Or perhaps it was this you remember:
var url = "http://stackoverflow.com";
$(location).attr('href',url);
The approach suggested by vizzy also works with OpenCV 2.4.8, as when building the non-free package under Ubuntu 14.04 LTS.
This dependency issue may prevent installation of the non-free package:
libopencv-nonfree2.4 depends on libopencv-ocl2.4; however:
Package libopencv-ocl2.4 is not installed.
Easily fixable because the missing package can be installed from the ones just built:
dpkg -i libopencv-ocl2.4_2.4.8+dfsg1-2ubuntu1_amd64.deb
After that the install proceeds as explained in vizzy's answer.
Maven dependency
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-security</artifactId>
</dependency>
<dependency>
<groupId>org.apache.ws.security</groupId>
<artifactId>wss4j</artifactId>
<version>1.6.19</version>
</dependency>
Configuration class
import org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor;
@Configuration
public class ConfigurationClass{
@Bean
public Wss4jSecurityInterceptor securityInterceptor() {
Wss4jSecurityInterceptor wss4jSecurityInterceptor = new Wss4jSecurityInterceptor();
wss4jSecurityInterceptor.setSecurementActions("UsernameToken");
wss4jSecurityInterceptor.setSecurementMustUnderstand(true);
wss4jSecurityInterceptor.setSecurementPasswordType("PasswordText");
wss4jSecurityInterceptor.setSecurementUsername("123456789011");
wss4jSecurityInterceptor.setSecurementPassword("TestPass123");
return wss4jSecurityInterceptor;
}
Result xml
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header>
<wsse:Security
xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
SOAP-ENV:mustUnderstand="1">
<wsse:UsernameToken wsu:Id="UsernameToken-F57F40DC89CD6998E214700450735811">
<wsse:Username>123456789011</wsse:Username>
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">TestPass123</wsse:Password>
</wsse:UsernameToken>
</wsse:Security>
</SOAP-ENV:Header>
<SOAP-ENV:Body>
...
something
...
</SOAP-ENV:Body>
Swift 5.1, Xcode 11
extension UINavigationController{
public func removePreviousController(total: Int){
let totalViewControllers = self.viewControllers.count
self.viewControllers.removeSubrange(totalViewControllers-total..<totalViewControllers - 1)
}}
Make sure to call this utility function after viewDidDisappear() of previous controller or viewDidAppear() of new controller
John Montgomery's, answer is great, but at least on Windows, it is missing the line
vc.release()
before
cv2.destroyWindow("preview")
Without it, the camera resource is locked, and can not be captured again before the python console is killed.
Have you start by reading the information on this on Wikipedia - Block cipher modes of operation? Then follow the reference link on Wikipedia to NIST: Recommendation for Block Cipher Modes of Operation.
In my case I got NAN when setting distant integer LABELs. ie:
So, not use a very distant Label.
EDIT You can see the effect in the following simple code:
from keras.models import Sequential
from keras.layers import Dense, Activation
import numpy as np
X=np.random.random(size=(20,5))
y=np.random.randint(0,high=5, size=(20,1))
model = Sequential([
Dense(10, input_dim=X.shape[1]),
Activation('relu'),
Dense(5),
Activation('softmax')
])
model.compile(optimizer = "Adam", loss = "sparse_categorical_crossentropy", metrics = ["accuracy"] )
print('fit model with labels in range 0..5')
history = model.fit(X, y, epochs= 5 )
X = np.vstack( (X, np.random.random(size=(1,5))))
y = np.vstack( ( y, [[8000]]))
print('fit model with labels in range 0..5 plus 8000')
history = model.fit(X, y, epochs= 5 )
The result shows the NANs after adding the label 8000:
fit model with labels in range 0..5
Epoch 1/5
20/20 [==============================] - 0s 25ms/step - loss: 1.8345 - acc: 0.1500
Epoch 2/5
20/20 [==============================] - 0s 150us/step - loss: 1.8312 - acc: 0.1500
Epoch 3/5
20/20 [==============================] - 0s 151us/step - loss: 1.8273 - acc: 0.1500
Epoch 4/5
20/20 [==============================] - 0s 198us/step - loss: 1.8233 - acc: 0.1500
Epoch 5/5
20/20 [==============================] - 0s 151us/step - loss: 1.8192 - acc: 0.1500
fit model with labels in range 0..5 plus 8000
Epoch 1/5
21/21 [==============================] - 0s 142us/step - loss: nan - acc: 0.1429
Epoch 2/5
21/21 [==============================] - 0s 238us/step - loss: nan - acc: 0.2381
Epoch 3/5
21/21 [==============================] - 0s 191us/step - loss: nan - acc: 0.2381
Epoch 4/5
21/21 [==============================] - 0s 191us/step - loss: nan - acc: 0.2381
Epoch 5/5
21/21 [==============================] - 0s 188us/step - loss: nan - acc: 0.2381
You just have to refer your original list to be the one that the Collectors.toList()
returns.
Here's a demo:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Reference {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
System.out.println(list);
// Just collect even numbers and start referring the new list as the original one.
list = list.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
System.out.println(list);
}
}
And here's how you can add the newly created elements to your original list in just one line.
List<Integer> list = ...;
// add even numbers from the list to the list again.
list.addAll(list.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList())
);
That's what this Functional Programming Paradigm provides.
Here is my way of doing stop() method:
Somewhere in code:
audioCh1: document.createElement("audio");
and then in stop():
this.audioCh1.pause()
this.audioCh1.src = 'data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEAVFYAAFRWAAABAAgAZGF0YQAAAAA=';
In this way we don`t produce additional request, the old one is cancelled and our audio element is in clean state (tested in Chrome and FF) :>
mysqld --initialize to initialize the data directory then mysqld &
If you had already launched mysqld& without mysqld --initialize you might have to delete all files in your data directory
You can also modify /etc/my.cnf to add a custom path to your data directory like this :
[mysqld]
...
datadir=/path/to/directory
.Net Core does not require mono in the sense of the mono framework. .Net Core is a framework that will work on multiple platforms including Linux. Reference https://dotnet.github.io/.
However the .Net core can use the mono framework. Reference https://docs.asp.net/en/1.0.0-rc1/getting-started/choosing-the-right-dotnet.html (note rc1 documentatiopn no rc2 available), however mono is not a Microsoft supported framework and would recommend using a supported framework
Now entity framework 7 is now called Entity Framework Core
and is available on multiple platforms including Linux. Reference https://github.com/aspnet/EntityFramework (review the road map)
I am currently using both of these frameworks however you must understand that it is still in release candidate stage (RC2
is the current version) and over the beta & release candidates there have been massive changes that usually end up with you scratching your head.
Here is a tutorial on how to install MVC .Net Core into Linux. https://docs.asp.net/en/1.0.0-rc1/getting-started/installing-on-linux.html
Finally you have a choice of Web Servers (where I am assuming the fast cgi
reference came from) to host your application on Linux. Here is a reference point for installing to a Linux enviroment. https://docs.asp.net/en/1.0.0-rc1/publishing/linuxproduction.html
I realise this post ends up being mostly links to documentation but at this point those are your best sources of information. .Net core is still relatively new in the .Net community and until its fully released I would be hesitant to use it in a product environment given the breaking changes between released version.
This seems to be the canonical reference point for high-level database interaction in Python: http://wiki.python.org/moin/HigherLevelDatabaseProgramming
From there, it looks like Dejavu implements Martin Fowler's DataMapper pattern fairly abstractly in Python.
From Web Application I think you can't, but you can rename all the folders in Git Client, it will move your files in the new renamed folders, than commit and push to remote repository.
I had a very similar issue: I had to rename different folders from uppercase to lowercase (like Abc -> abc), I've renamed all the folders with a dummy name (like 'abc___') and than committed to remote repository, after that I renamed all the folders to the original name with the lowercase (like abc) and it took them!
The only way I found to work with hours, through an US format in source (mm-dd-yyyy HH-MM-SS PM/AM)...
df_dataSet$time <- as.POSIXct( df_dataSet$time , format = "%m/%d/%Y %I:%M:%S %p" , tz = "GMT")
class(df_dataSet$time)
df_dataSet <- df_dataSet[do.call(order, df_dataSet), ]
To handle this situation in a portable way (ie will work on all databases because it doesn’t use MySQL label Kung fu), break the procedure up into logic parts, like this:
CREATE PROCEDURE SP_Reporting(IN tablename VARCHAR(20))
BEGIN
IF tablename IS NOT NULL THEN
CALL SP_Reporting_2(tablename);
END IF;
END;
CREATE PROCEDURE SP_Reporting_2(IN tablename VARCHAR(20))
BEGIN
#proceed with code
END;
@Grantismo provides a great explanation on the overall. If you wish to know who people are actually doing this things i suggest you to take a look at how google did for the Google IO App of 2014 (it's always worth taking a deep look at the source code of these apps that they release. There's a lot to learn from there).
Here's a blog post about it: http://android-developers.blogspot.com.br/2014/09/conference-data-sync-gcm-google-io.html
Essentially, on the application side: GCM for signalling, Sync Adapter for data fetching and talking properly with Content Provider that will make things persistent (yeah, it isolates the DB from direct access from other parts of the app).
Also, if you wish to take a look at the 2015's code: https://github.com/google/iosched
Came here searching for - "#1034 - Incorrect key file for table 'test'; try to repair it"
Seeing this caused by added a charset to an indexed Enum (might be the same with other fields) with Mysql 8.0.21.
CREATE TABLE `test` (
`enumVal` ENUM( 'val1' ) NOT NULL
) ENGINE = MYISAM;
ALTER TABLE `test` ADD INDEX ( `enumVal` );
ALTER TABLE `test` CHANGE `enumVal` `enumVal` ENUM( 'val1') CHARACTER SET utf8 COLLATE utf8_bin NOT NULL;
Solution using is to drop the index before the alter.
ALTER TABLE `test` ADD INDEX ( `enumVal` );
size_t
is an unsigned type that can hold maximum integer value for your architecture, so it is protected from integer overflows due to sign (signed int 0x7FFFFFFF
incremented by 1 will give you -1) or short size (unsigned short int 0xFFFF incremented by 1 will give you 0).
It is mainly used in array indexing/loops/address arithmetic and so on. Functions like memset()
and alike accept size_t
only, because theoretically you may have a block of memory of size 2^32-1
(on 32bit platform).
For such simple loops don't bother and use just int.
Peeskillet's lame tutorial for working with JTables in Netbeans GUI Builder
Add a button to the frame somwhere,. This button will be clicked when the user is ready to submit a row
Events -> Action -> actionPerformed
You should see code like the following auto-generated
private void jButton1ActionPerformed(java.awt.event.ActionEvent) {}
The jTable1
will have a DefaultTableModel
. You can add rows to the model with your data
private void jButton1ActionPerformed(java.awt.event.ActionEvent) {
String data1 = something1.getSomething();
String data2 = something2.getSomething();
String data3 = something3.getSomething();
String data4 = something4.getSomething();
Object[] row = { data1, data2, data3, data4 };
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.addRow(row);
// clear the entries.
}
So for every set of data like from a couple text fields, a combo box, and a check box, you can gather that data each time the button is pressed and add it as a row to the model.
I think this thread may be helpful: http://forums.macosxhints.com/archive/index.php/t-70973.html
To paraphrase, you can rename it with the .command extension or create an AppleScript to run the shell.
It depends, if you are referring to unsigned long the formatting character is "%lu"
. If you're referring to signed long the formatting character is "%ld"
.
You can use:
return (dateTocheck >= startDate && dateToCheck <= endDate);
y={'username':'admin','machine':['a','b','c']}
if 'c' in y['machine'] : del y['machine'][y['machine'].index('c')]
Why not just:
int plusIndex = s.indexOf("+");
if (plusIndex != -1) {
String before = s.substring(0, plusIndex);
// Use before
}
It's not really clear why your original version didn't work, but then you didn't say what actually happened. If you want to split not using regular expressions, I'd personally use Guava:
Iterable<String> bits = Splitter.on('+').split(s);
String firstPart = Iterables.getFirst(bits, "");
If you're going to use split
(either the built-in version or Guava) you don't need to check whether it contains +
first - if it doesn't there'll only be one result anyway. Obviously there's a question of efficiency, but it's simpler code:
// Calling split unconditionally
String[] parts = s.split("\\+");
s = parts[0];
Note that writing String[] parts
is preferred over String parts[]
- it's much more idiomatic Java code.
void reverse(char *s)
{
char *end,temp;
end = s;
while(*end != '\0'){
end++;
}
end--; //end points to last letter now
for(;s<end;s++,end--){
temp = *end;
*end = *s;
*s = temp;
}
}
You want this:
AAPL:
- shares: -75.088
date: 11/27/2015
- shares: 75.088
date: 11/26/2015
The YAML equivalent of a JSON object is a mapping, which looks like these:
# flow style
{ foo: 1, bar: 2 }
# block style
foo: 1
bar: 2
Note that the first characters of the keys in a block mapping must be in the same column. To demonstrate:
# OK
foo: 1
bar: 2
# Parse error
foo: 1
bar: 2
The equivalent of a JSON array in YAML is a sequence, which looks like either of these (which are equivalent):
# flow style
[ foo bar, baz ]
# block style
- foo bar
- baz
In a block sequence the -
s must be in the same column.
Let's turn your JSON into YAML. Here's your JSON:
{"AAPL": [
{
"shares": -75.088,
"date": "11/27/2015"
},
{
"shares": 75.088,
"date": "11/26/2015"
},
]}
As a point of trivia, YAML is a superset of JSON, so the above is already valid YAML—but let's actually use YAML's features to make this prettier.
Starting from the inside out, we have objects that look like this:
{
"shares": -75.088,
"date": "11/27/2015"
}
The equivalent YAML mapping is:
shares: -75.088
date: 11/27/2015
We have two of these in an array (sequence):
- shares: -75.088
date: 11/27/2015
- shares: 75.088
date: 11/26/2015
Note how the -
s line up and the first characters of the mapping keys line up.
Finally, this sequence is itself a value in a mapping with the key AAPL
:
AAPL:
- shares: -75.088
date: 11/27/2015
- shares: 75.088
date: 11/26/2015
Parsing this and converting it back to JSON yields the expected result:
{
"AAPL": [
{
"date": "11/27/2015",
"shares": -75.088
},
{
"date": "11/26/2015",
"shares": 75.088
}
]
}
You can see it (and edit it interactively) here.
readFileSync()
is synchronous and blocks execution until finished. These return their results as return values.
readFile()
are asynchronous and return immediately while they function in the background. You pass a callback function which gets called when they finish.
let's take an example for non-blocking.
following method read a file as a non-blocking way
var fs = require('fs');
fs.readFile(filename, "utf8", function(err, data) {
if (err) throw err;
console.log(data);
});
following is read a file as blocking or synchronous way.
var data = fs.readFileSync(filename);
LOL...If you don't want
readFileSync()
as blocking way then take reference from the following code. (Native)
var fs = require('fs');
function readFileAsSync(){
new Promise((resolve, reject)=>{
fs.readFile(filename, "utf8", function(err, data) {
if (err) throw err;
resolve(data);
});
});
}
async function callRead(){
let data = await readFileAsSync();
console.log(data);
}
callRead();
it's mean behind scenes
readFileSync()
work same as above(promise) base.
here's for SQL server, Oracle, PostgreSQL
which support window functions.
SELECT ROW_NUMBER() OVER (ORDER BY first_name, last_name) Sequence_no,
first_name,
last_name
FROM tableName
I got the same error from IIS under windows 7. To fix this error i had to add full control permissions to IUSR account for sqlite database file. You don't need to change permissions if you use sqlite under webmatrix instead of IIS.
Tell PDO your charset
initially.... something like
PDO("mysql:host=$host;dbname=$DB_name;charset=utf8;", $username, $password);
Notice the: charset=utf8;
part.
hope it helps!
If you don't mind multiple inheritance (it is not that bad, after all), you may write simple class with private copy constructor and assignment operator and additionally subclass it:
class NonAssignable {
private:
NonAssignable(NonAssignable const&);
NonAssignable& operator=(NonAssignable const&);
public:
NonAssignable() {}
};
class SymbolIndexer: public Indexer, public NonAssignable {
};
For GCC this gives the following error message:
test.h: In copy constructor ‘SymbolIndexer::SymbolIndexer(const SymbolIndexer&)’:
test.h: error: ‘NonAssignable::NonAssignable(const NonAssignable&)’ is private
I'm not very sure for this to work in every compiler, though. There is a related question, but with no answer yet.
UPD:
In C++11 you may also write NonAssignable
class as follows:
class NonAssignable {
public:
NonAssignable(NonAssignable const&) = delete;
NonAssignable& operator=(NonAssignable const&) = delete;
NonAssignable() {}
};
The delete
keyword prevents members from being default-constructed, so they cannot be used further in a derived class's default-constructed members. Trying to assign gives the following error in GCC:
test.cpp: error: use of deleted function
‘SymbolIndexer& SymbolIndexer::operator=(const SymbolIndexer&)’
test.cpp: note: ‘SymbolIndexer& SymbolIndexer::operator=(const SymbolIndexer&)’
is implicitly deleted because the default definition would
be ill-formed:
UPD:
Boost already has a class just for the same purpose, I guess it's even implemented in similar way. The class is called boost::noncopyable
and is meant to be used as in the following:
#include <boost/core/noncopyable.hpp>
class SymbolIndexer: public Indexer, private boost::noncopyable {
};
I'd recommend sticking to the Boost's solution if your project policy allows it. See also another boost::noncopyable
-related question for more information.
I would use
WHERE columnName LIKE '%[%]%'
SQL Server stores string summary statistics for use in estimating the number of rows that will match a LIKE
clause. The cardinality estimates can be better and lead to a more appropriate plan when the square bracket syntax is used.
The response to this Connect Item states
We do not have support for precise cardinality estimation in the presence of user defined escape characters. So we probably get a poor estimate and a poor plan. We'll consider addressing this issue in a future release.
An example
CREATE TABLE T
(
X VARCHAR(50),
Y CHAR(2000) NULL
)
CREATE NONCLUSTERED INDEX IX ON T(X)
INSERT INTO T (X)
SELECT TOP (5) '10% off'
FROM master..spt_values
UNION ALL
SELECT TOP (100000) 'blah'
FROM master..spt_values v1, master..spt_values v2
SET STATISTICS IO ON;
SELECT *
FROM T
WHERE X LIKE '%[%]%'
SELECT *
FROM T
WHERE X LIKE '%\%%' ESCAPE '\'
Shows 457 logical reads for the first query and 33,335 for the second.
This will resolve all permissions in folder
sudo chown -R $(whoami) ./
Try using this.
WHERE Orders.OrderStatus = 'Shipped'
AND Orders.ShipDate >= CONVERT(DATE, GETDATE())
NOTE:
pd.convert_objects
has now been deprecated. You should usepd.Series.astype(float)
orpd.to_numeric
as described in other answers.
This is available in 0.11. Forces conversion (or set's to nan)
This will work even when astype
will fail; its also series by series
so it won't convert say a complete string column
In [10]: df = DataFrame(dict(A = Series(['1.0','1']), B = Series(['1.0','foo'])))
In [11]: df
Out[11]:
A B
0 1.0 1.0
1 1 foo
In [12]: df.dtypes
Out[12]:
A object
B object
dtype: object
In [13]: df.convert_objects(convert_numeric=True)
Out[13]:
A B
0 1 1
1 1 NaN
In [14]: df.convert_objects(convert_numeric=True).dtypes
Out[14]:
A float64
B float64
dtype: object
I've fixed that problem by creating test rails project and install all gems then I've replaced my current Gemfile.lock with the test and all thing works fine.
I think that this problem from bundler
versions with hosting, so please make sure that hosting bundler is the same version with your project.
I would like to give you a background on Universal CRT this would help you in understanding as to why the system should be updated before installing vc_redist.x64.exe.
For Windows 7, 8, and 8.1 the Windows Universal Runtime must be installed via KB2999226. However it has a prerequisite update KB2919355 which contains updates that facilitate installing the KB2999226 package.
Why does KB2999226 not always install when the runtime is installed from the redistributable? What could prevent KB2999226 from installing as part of the runtime?
The UCRT MSU included in the VCRedist is installed by making a call into the Windows Update service and the KB can fail to install based upon Windows Update service activity/state:
If the Windows Update service is in a non-ready state, you can see errors reflecting that.
To identify if the prerequisite KB2919355 is installed there are 2 options:
Registry key: 64bit hive
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\Packages\Package_for_KB2919355~31bf3856ad364e35~amd64~~6.3.1.14
CurrentState = 112
32bit hive
HKLM\SOFTWARE\[WOW6432Node\]Microsoft\Windows\CurrentVersion\Component Based Servicing\Packages\Package_for_KB2919355~31bf3856ad364e35~x86~~6.3.1.14
CurrentState = 112
Or check the file version of:
C:\Windows\SysWOW64\wuaueng.dll
C:\Windows\System32\wuaueng.dll
is 7.9.9600.17031 or later
apply the below code in productRepository
@Query("update Product set prodName=:name where prodId=:id ")
@Transactional
@Modifying
int updateMyData(@Param("name")String name, @Param("id") Integer id);
while in junit test apply below code
@Test
public void updateData()
{
int i=productRepository.updateMyData("Iphone",102);
System.out.println("successfully updated ... ");
assertTrue(i!=0);
}
it is working fine for my code
Standard WCF Tracing/Diagnostics
If for some reason you are unable to get Fiddler to work, or would rather log the requests another way, another option is to use the standard WCF tracing functionality. This will produce a file that has a nice viewer.
Docs
See https://docs.microsoft.com/en-us/dotnet/framework/wcf/samples/tracing-and-message-logging
Configuration
Add the following to your config, make sure c:\logs
exists, rebuild, and make requests:
<system.serviceModel>
<diagnostics>
<!-- Enable Message Logging here. -->
<!-- log all messages received or sent at the transport or service model levels -->
<messageLogging logEntireMessage="true"
maxMessagesToLog="300"
logMessagesAtServiceLevel="true"
logMalformedMessages="true"
logMessagesAtTransportLevel="true" />
</diagnostics>
</system.serviceModel>
<system.diagnostics>
<sources>
<source name="System.ServiceModel" switchValue="Information,ActivityTracing"
propagateActivity="true">
<listeners>
<add name="xml" />
</listeners>
</source>
<source name="System.ServiceModel.MessageLogging">
<listeners>
<add name="xml" />
</listeners>
</source>
</sources>
<sharedListeners>
<add initializeData="C:\logs\TracingAndLogging-client.svclog" type="System.Diagnostics.XmlWriterTraceListener"
name="xml" />
</sharedListeners>
<trace autoflush="true" />
</system.diagnostics>
You can also use the local commandline php-cli:
* * * * * php /local/root/path/to/tasks.php > /dev/null
It is faster and decrease load for your webserver.
If spring-security
jars are added in classpath and also if it is spring-boot
application all http endpoints will be secured by default security configuration class SecurityAutoConfiguration
This causes a browser pop-up to ask for credentials.
The password changes for each application restarts and can be found in console.
Using default security password: 78fa095d-3f4c-48b1-ad50-e24c31d5cf35
To add your own layer of application security in front of the defaults,
@EnableWebSecurity
public class SecurityConfig {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
}
or if you just want to change password you could override default with,
application.xml
security.user.password=new_password
or
application.properties
spring.security.user.name=<>
spring.security.user.password=<>
Well, It's quite easy.
Open your local project.
Add a README.md
file (If you don't have anything to add yet)
Click on Publish on Github
Choose as you wish
Choose the files you want to include in firt commit.
Note: If you don't select a file or folder it will added to .gitignore
file
You are good to go. it is published.
P.S. If this was you first time. A prompt will ask for for your Github Credentials fill those and you are good to go. It is published.
This should work:
@interface MyClass
{
int _doubleDigits[10];
}
@property(readonly) int *doubleDigits;
@end
@implementation MyClass
- (int *)doubleDigits
{
return _doubleDigits;
}
@end
The iPhone/iPad simulator that comes with Xcode includes Safari. If you run Safari in the simulator, you can view your website and it should appear the same as it would on a real device. This may work for general layout testing. But since it is a simulator, it is possible that not every single bit of functionality will be exactly the same as using a real iOS device.
If you are writing a website and you need to verify that it looks proper on a given device, then you need to test your website on that actual device. Testing with real hardware is part of the price of doing business.
And yes, you need a Mac to run Xcode.
You can use from root directory:
RewriteEngine On
RewriteRule ^(?:system)\b.* /403.html
Or:
RewriteRule ^(?:system)\b.* /403.php # with header('HTTP/1.0 403 Forbidden');
I had this issue with Jenkins. The cause: I had renamed a module module
to Module
. I found out that git had gotten confused somehow and kept both module
and Module
directories, with the contents spread between both folders. The build.gradle
was kept in module
but the module's name was Module
so it was unable to find the default configuration.
I fixed it by backing up the contents of Module
, manually deleting module
folder from the repo and restoring + pushing the lost files.
I had a similar problem. I had installed JDK7 update 1 but couldn't use it (probably because I found a JRE6 that I deleted after installing JDK7). Uninstalling JDK7 was impossible. The solution was to add the JRE registry entries by hand.
[HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment]
"CurrentVersion"="1.7"
[HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.7]
"JavaHome"="C:\\Program Files\\Java\\jre7"
"RuntimeLib"="C:\\Program Files\\Java\\jre7\\bin\\client\\jvm.dll"
[HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.7.0_01]
"JavaHome"="C:\\Program Files\\Java\\jre7"
"RuntimeLib"="C:\\Program Files\\Java\\jre7\\bin\\client\\jvm.dll"
You'll have to adjust the above to your own directories and version.
If this doesn't help, there's still JavaRa http://raproducts.org/wordpress/ .
If the buckets get too full, then we have to look through
a very long linked list.
And that's kind of defeating the point.
So here's an example where I have four buckets.
I have elephant and badger in my HashSet so far.
This is a pretty good situation, right?
Each element has zero or one elements.
Now we put two more elements into our HashSet.
buckets elements
------- -------
0 elephant
1 otter
2 badger
3 cat
This isn't too bad either.
Every bucket only has one element . So if I wanna know, does this contain panda?
I can very quickly look at bucket number 1 and it's not
there and
I known it's not in our collection.
If I wanna know if it contains cat, I look at bucket
number 3,
I find cat, I very quickly know if it's in our
collection.
What if I add koala, well that's not so bad.
buckets elements
------- -------
0 elephant
1 otter -> koala
2 badger
3 cat
Maybe now instead of in bucket number 1 only looking at
one element,
I need to look at two.
But at least I don't have to look at elephant, badger and
cat.
If I'm again looking for panda, it can only be in bucket
number 1 and
I don't have to look at anything other then otter and
koala.
But now I put alligator in bucket number 1 and you can
see maybe where this is going.
That if bucket number 1 keeps getting bigger and bigger and
bigger, then I'm basically having to look through all of
those elements to find
something that should be in bucket number 1.
buckets elements
------- -------
0 elephant
1 otter -> koala ->alligator
2 badger
3 cat
If I start adding strings to other buckets,
right, the problem just gets bigger and bigger in every
single bucket.
How do we stop our buckets from getting too full?
The solution here is that
"the HashSet can automatically
resize the number of buckets."
There's the HashSet realizes that the buckets are getting
too full.
It's losing this advantage of this all of one lookup for
elements.
And it'll just create more buckets(generally twice as before) and
then place the elements into the correct bucket.
So here's our basic HashSet implementation with separate
chaining. Now I'm going to create a "self-resizing HashSet".
This HashSet is going to realize that the buckets are
getting too full and
it needs more buckets.
loadFactor is another field in our HashSet class.
loadFactor represents the average number of elements per
bucket,
above which we want to resize.
loadFactor is a balance between space and time.
If the buckets get too full then we'll resize.
That takes time, of course, but
it may save us time down the road if the buckets are a
little more empty.
Let's see an example.
Here's a HashSet, we've added four elements so far.
Elephant, dog, cat and fish.
buckets elements
------- -------
0
1 elephant
2 cat ->dog
3 fish
4
5
At this point, I've decided that the loadFactor, the
threshold,
the average number of elements per bucket that I'm okay
with, is 0.75.
The number of buckets is buckets.length, which is 6, and
at this point our HashSet has four elements, so the
current size is 4.
We'll resize our HashSet, that is we'll add more buckets,
when the average number of elements per bucket exceeds
the loadFactor.
That is when current size divided by buckets.length is
greater than loadFactor.
At this point, the average number of elements per bucket
is 4 divided by 6.
4 elements, 6 buckets, that's 0.67.
That's less than the threshold I set of 0.75 so we're
okay.
We don't need to resize.
But now let's say we add woodchuck.
buckets elements
------- -------
0
1 elephant
2 woodchuck-> cat ->dog
3 fish
4
5
Woodchuck would end up in bucket number 3.
At this point, the currentSize is 5.
And now the average number of elements per bucket
is the currentSize divided by buckets.length.
That's 5 elements divided by 6 buckets is 0.83.
And this exceeds the loadFactor which was 0.75.
In order to address this problem, in order to make the
buckets perhaps a little
more empty so that operations like determining whether a
bucket contains
an element will be a little less complex, I wanna resize
my HashSet.
Resizing the HashSet takes two steps.
First I'll double the number of buckets, I had 6 buckets,
now I'm going to have 12 buckets.
Note here that the loadFactor which I set to 0.75 stays the same.
But the number of buckets changed is 12,
the number of elements stayed the same, is 5.
5 divided by 12 is around 0.42, that's well under our
loadFactor,
so we're okay now.
But we're not done because some of these elements are in
the wrong bucket now.
For instance, elephant.
Elephant was in bucket number 2 because the number of
characters in elephant
was 8.
We have 6 buckets, 8 minus 6 is 2.
That's why it ended up in number 2.
But now that we have 12 buckets, 8 mod 12 is 8, so
elephant does not belong in bucket number 2 anymore.
Elephant belongs in bucket number 8.
What about woodchuck?
Woodchuck was the one that started this whole problem.
Woodchuck ended up in bucket number 3.
Because 9 mod 6 is 3.
But now we do 9 mod 12.
9 mod 12 is 9, woodchuck goes to bucket number 9.
And you see the advantage of all this.
Now bucket number 3 only has two elements whereas before it had 3.
So here's our code,
where we had our HashSet with separate chaining that
didn't do any resizing.
Now, here's a new implementation where we use resizing.
Most of this code is the same,
we're still going to determine whether it contains the
value already.
If it doesn't, then we'll figure it out which bucket it
should go into and
then add it to that bucket, add it to that LinkedList.
But now we increment the currentSize field.
currentSize was the field that kept track of the number
of elements in our HashSet.
We're going to increment it and then we're going to look
at the average load,
the average number of elements per bucket.
We'll do that division down here.
We have to do a little bit of casting here to make sure
that we get a double.
And then, we'll compare that average load to the field
that I've set as
0.75 when I created this HashSet, for instance, which was
the loadFactor.
If the average load is greater than the loadFactor,
that means there's too many elements per bucket on
average, and I need to reinsert.
So here's our implementation of the method to reinsert
all the elements.
First, I'll create a local variable called oldBuckets.
Which is referring to the buckets as they currently stand
before I start resizing everything.
Note I'm not creating a new array of linked lists just yet.
I'm just renaming buckets as oldBuckets.
Now remember buckets was a field in our class, I'm going
to now create a new array
of linked lists but this will have twice as many elements
as it did the first time.
Now I need to actually do the reinserting,
I'm going to iterate through all of the old buckets.
Each element in oldBuckets is a LinkedList of strings
that is a bucket.
I'll go through that bucket and get each element in that
bucket.
And now I'm gonna reinsert it into the newBuckets.
I will get its hashCode.
I will figure out which index it is.
And now I get the new bucket, the new LinkedList of
strings and
I'll add it to that new bucket.
So to recap, HashSets as we've seen are arrays of Linked
Lists, or buckets.
A self resizing HashSet can realize using some ratio or
A slight more difficult answer that uses ControlTemplate and has an animation effect (adapted from https://docs.microsoft.com/en-us/dotnet/framework/wpf/controls/customizing-the-appearance-of-an-existing-control)
In your resource dictionary define a control template for your button like this one:
<ControlTemplate TargetType="Button" x:Key="testButtonTemplate2">
<Border Name="RootElement">
<Border.Background>
<SolidColorBrush x:Name="BorderBrush" Color="Black"/>
</Border.Background>
<Grid Margin="4" >
<Grid.Background>
<SolidColorBrush x:Name="ButtonBackground" Color="Aquamarine"/>
</Grid.Background>
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" Margin="4,5,4,4"/>
</Grid>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal"/>
<VisualState x:Name="MouseOver">
<Storyboard>
<ColorAnimation Storyboard.TargetName="ButtonBackground" Storyboard.TargetProperty="Color" To="Red"/>
</Storyboard>
</VisualState>
<VisualState x:Name="Pressed">
<Storyboard>
<ColorAnimation Storyboard.TargetName="ButtonBackground" Storyboard.TargetProperty="Color" To="Red"/>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
</Border>
</ControlTemplate>
in your XAML you can use the template above for your button as below:
Define your button
<Button Template="{StaticResource testButtonTemplate2}"
HorizontalAlignment="Center" VerticalAlignment="Center"
Foreground="White">My button</Button>
Hope it helps
I see many answer reporting for zip and rar the Media Types application/zip
and application/x-rar-compressed
, respectively.
While the former matching is correct, for the latter IANA reports here https://www.iana.org/assignments/media-types/application/vnd.rar that for rar application/x-rar-compressed
is a deprecated alias name and instead application/vnd.rar
is the official one.
So, right Media Types from IANA in 2020 are:
zip
: application/zip
rar
: application/vnd.rar
Chain selectors are not limited just to classes, you can do it for both classes and ids.
Classes
.classA.classB {
/*style here*/
}
Class & Id
.classA#idB {
/*style here*/
}
Id & Id
#idA#idB {
/*style here*/
}
All good current browsers support this except IE 6, it selects based on the last selector in the list. So ".classA.classB" will select based on just ".classB".
For your case
li.left.ui-class-selector {
/*style here*/
}
or
.left.ui-class-selector {
/*style here*/
}
In general suppressing warnings is not the best solution as you may want to be warned when some unexpected input will be provided.
Solution below is wrapper for maintaining just NA during data type conversion. Doesn't require any package.
as.num = function(x, na.strings = "NA") {
stopifnot(is.character(x))
na = x %in% na.strings
x[na] = 0
x = as.numeric(x)
x[na] = NA_real_
x
}
as.num(c("1", "2", "X"), na.strings="X")
#[1] 1 2 NA
Following Pavel's advice to use a custom directive, here's a version that requires adding no payload to the routeConfig, is super declarative, and can be adapted to react to any level of the path, by simply changing which slice()
of it you're paying attention to.
app.directive('detectActiveTab', function ($location) {
return {
link: function postLink(scope, element, attrs) {
scope.$on("$routeChangeSuccess", function (event, current, previous) {
/*
Designed for full re-usability at any path, any level, by using
data from attrs. Declare like this:
<li class="nav_tab">
<a href="#/home" detect-active-tab="1">HOME</a>
</li>
*/
// This var grabs the tab-level off the attribute, or defaults to 1
var pathLevel = attrs.detectActiveTab || 1,
// This var finds what the path is at the level specified
pathToCheck = $location.path().split('/')[pathLevel] ||
"current $location.path doesn't reach this level",
// This var finds grabs the same level of the href attribute
tabLink = attrs.href.split('/')[pathLevel] ||
"href doesn't include this level";
// Above, we use the logical 'or' operator to provide a default value
// in cases where 'undefined' would otherwise be returned.
// This prevents cases where undefined===undefined,
// possibly causing multiple tabs to be 'active'.
// now compare the two:
if (pathToCheck === tabLink) {
element.addClass("active");
}
else {
element.removeClass("active");
}
});
}
};
});
We're accomplishing our goals by listening for the $routeChangeSuccess
event, rather than by placing a $watch
on the path. I labor under the belief that this means the logic should run less often, as I think watches fire on each $digest
cycle.
Invoke it by passing your path-level argument on the directive declaration. This specifies what chunk of the current $location.path() you want to match your href
attribute against.
<li class="nav_tab"><a href="#/home" detect-active-tab="1">HOME</a></li>
So, if your tabs should react to the base-level of the path, make the argument '1'. Thus, when location.path() is "/home", it will match against the "#/home" in the href
. If you have tabs that should react to the second level, or third, or 11th of the path, adjust accordingly. This slicing from 1 or greater will bypass the nefarious '#' in the href, which will live at index 0.
The only requirement is that you invoke on an <a>
, as the element is assuming the presence of an href
attribute, which it will compare to the current path. However, you could adapt fairly easily to read/write a parent or child element, if you preferred to invoke on the <li>
or something. I dig this because you can re-use it in many contexts by simply varying the pathLevel argument. If the depth to read from was assumed in the logic, you'd need multiple versions of the directive to use with multiple parts of the navigation.
EDIT 3/18/14: The solution was inadequately generalized, and would activate if you defined an arg for the value of 'activeTab' that returned undefined
against both $location.path()
, and the element's href
. Because: undefined === undefined
. Updated to fix that condition.
While working on that, I realized there should have been a version you can just declare on a parent element, with a template structure like this:
<nav id="header_tabs" find-active-tab="1">
<a href="#/home" class="nav_tab">HOME</a>
<a href="#/finance" class="nav_tab">Finance</a>
<a href="#/hr" class="nav_tab">Human Resources</a>
<a href="#/quarterly" class="nav_tab">Quarterly</a>
</nav>
Note that this version no longer remotely resembles Bootstrap-style HTML. But, it's more modern and uses fewer elements, so I'm partial to it. This version of the directive, plus the original, are now available on Github as a drop-in module you can just declare as a dependency. I'd be happy to Bower-ize them, if anybody actually uses them.
Also, if you want a bootstrap-compatible version that includes <li>
's, you can go with the angular-ui-bootstrap Tabs module, which I think came out after this original post, and which is perhaps even more declarative than this one. It's less concise for basic stuff, but provides you with some additional options, like disabled tabs and declarative events that fire on activate and deactivate.
If you want to do this purely in CSS then you'd have a class that you'd assign to each alternate list item. E.g.
<ul>
<li class="alternate"><a href="link">Link 1</a></li>
<li><a href="link">Link 2</a></li>
<li class="alternate"><a href="link">Link 3</a></li>
<li><a href="link">Link 4</a></li>
<li class="alternate"><a href="link">Link 5</a></li>
</ul>
If your list is dynamically generated, this task would be much easier.
If you don't want to have to manually update this content each time, you could use the jQuery library and apply a style alternately to each <li>
item in your list:
<ul id="myList">
<li><a href="link">Link 1</a></li>
<li><a href="link">Link 2</a></li>
<li><a href="link">Link 3</a></li>
<li><a href="link">Link 4</a></li>
<li><a href="link">Link 5</a></li>
</ul>
And your jQuery code:
$(document).ready(function(){
$('#myList li:nth-child(odd)').addClass('alternate');
});
Use:
drop table uno
drop table dos
create table uno
(
uid int,
col1 char(1),
col2 char(2)
)
create table dos
(
did int,
col1 char(1),
col2 char(2),
[sql] char(4)
)
insert into uno(uid) values (1)
insert into uno(uid) values (2)
insert into dos values (1,'a','b',null)
insert into dos values (2,'c','d','cool')
select * from uno
select * from dos
EITHER:
update uno set col1 = (select col1 from dos where uid = did and [sql]='cool'),
col2 = (select col2 from dos where uid = did and [sql]='cool')
OR:
update uno set col1=d.col1,col2=d.col2 from uno
inner join dos d on uid=did where [sql]='cool'
select * from uno
select * from dos
If the ID column name is the same in both tables then just put the table name before the table to be updated and use an alias for the selected table, i.e.:
update uno set col1 = (select col1 from dos d where uno.[id] = d.[id] and [sql]='cool'),
col2 = (select col2 from dos d where uno.[id] = d.[id] and [sql]='cool')
If you're using jQuery, use .data()
:
div.data('myval', 20);
You can store arbitrary data with .data()
, but you're restricted to just strings when using .attr()
.
//javascript function calling an jquery function
//In javascript part
function js_show_score()
{
//we use so many javascript library, So please use 'jQuery' avoid '$'
jQuery(function(){
//Call any jquery function
show_score(); //jquery function
});(jQuery);
}
//In Jquery part
jQuery(function(){
//Jq Score function
function show_score()
{
$('#score').val("10");
}
});(jQuery);
this is the only way i can think of doing it.
//positive to minus
int a = 5; // starting with 5 to become -5
int b = int a * 2; // b = 10
int c = a - b; // c = - 5;
std::cout << c << endl;
//outputs - 5
//minus to positive
int a = -5; starting with -5 to become 5
int b = a * 2;
// b = -10
int c = a + b
// c = 5
std::cout << c << endl;
//outputs 5
Function examples
int b = 0;
int c = 0;
int positiveToNegative (int a) {
int b = a * 2;
int c = a - b;
return c;
}
int negativeToPositive (int a) {
int b = a * 2;
int c = a + b;
return c;
}
Another way by using ajax method:
View:
@Html.TextBox("txtValue", null, new { placeholder = "Input value" })
<input type="button" value="Start" id="btnStart" />
<script>
$(function () {
$('#btnStart').unbind('click');
$('#btnStart').on('click', function () {
$.ajax({
url: "/yourControllerName/yourMethod",
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: JSON.stringify({
txtValue: $("#txtValue").val()
}),
async: false
});
});
});
</script>
Controller:
[HttpPost]
public EmptyResult YourMethod(string txtValue)
{
// do what you want with txtValue
...
}
Go to File > Settings > Builds,Execution,Deployment > Build Tools > Gradle >Gradle home path
Now, set Use default gradle wrapper and edit Project\gradle\wrapper\gradle-wrapper.properties files field distributionUrl like this
distributionUrl=https://services.gradle.org/distributions/gradle-2.10-all.zip
You dont have a function named assign()
, but a method with this name. PHP is not Java and in PHP you have to make clear, if you want to call a function
assign()
or a method
$object->assign()
In your case the call to the function resides inside another method. $this
always refers to the object, in which a method exists, itself.
$this->assign()
My Problem was that I was not in the correct git directory that I just cloned.
I formerly voted to close this question as off-topic but actually I changed my mind as this is quite nice visual effect which, unfortunately, is not yet part of support library. It will most likely show up in future update, but there's no time frame announced.
Luckily there are few custom implementations already available:
including Materlial themed widget sets compatible with older versions of Android:
so you can try one of these or google for other "material widgets" or so...
A short example will help you understand one of yield from
's use case: get value from another generator
def flatten(sequence):
"""flatten a multi level list or something
>>> list(flatten([1, [2], 3]))
[1, 2, 3]
>>> list(flatten([1, [2], [3, [4]]]))
[1, 2, 3, 4]
"""
for element in sequence:
if hasattr(element, '__iter__'):
yield from flatten(element)
else:
yield element
print(list(flatten([1, [2], [3, [4]]])))
The safest way to pass credentials to curl is to be prompted to insert them. This is what happens when passing the username as suggested earlier (-u USERNAME
).
But what if you can't pass the username that way? For instance the username might need to be part of the url and only the password be part of a json payload.
tl;dr: This is how to use curl safely in this case:
read -p "Username: " U; read -sp "Password: " P; curl --request POST -d "{\"password\":\"${P}\"}" https://example.com/login/${U}; unset P U
read
will prompt for both username and password from the command line, and store the submitted values in two variables that can be references in subsequent commands and finally unset.
I'm gonna elaborate on why the other solutions are not ideal.
Why are environment variables unsafe
Why is it unsafe to type it into a command on the command line directly
Because your secret then ends up being visible by any other user running ps -aux
since that lists commands submitted for each currently running process.
Also because your secrte then ends up in the bash history (once the shell terminates).
Why is it unsafe to include it in a local file Strict POSIX access restriction on the file can mitigate the risk in this scenario. However, it is still a file on your file system, unencrypted at rest.
This looks similar and uses jQuery mobile http://www.irinavelychko.com/tutorials/jquery-mobile-gallery
And, the demo of it http://demo.irinavelychko.com/tuts/jqm-dialog-gallery.html
alter table table_name
rename column old_column_name/field_name to new_column_name/field_name;
example: alter table student column name to username;
Swift 3.0
Create a ViewController with the UITableViewDelegate and UITableViewDataSource protocols. Then create a tableView inside it, declaring its style to be UITableViewStyle.grouped. This will fix the headers.
lazy var tableView: UITableView = {
let view = UITableView(frame: UIScreen.main.bounds, style: UITableViewStyle.grouped)
view.delegate = self
view.dataSource = self
view.separatorStyle = .none
return view
}()
For me, the answers above did not work with matplotlib.__version__ = 1.4.3
on Win7. So, if we are only interested in the image itself (i.e., if we don't need annotations, axis, ticks, title, ylabel etc), then it's better to simply save the numpy array as image instead of savefig
.
from pylab import *
ax = subplot(111)
ax.imshow(some_image_numpyarray)
imsave('test.tif', some_image_numpyarray)
# or, if the image came from tiff or png etc
RGBbuffer = ax.get_images()[0].get_array()
imsave('test.tif', RGBbuffer)
Also, using opencv drawing functions (cv2.line, cv2.polylines), we can do some drawings directly on the numpy array. http://docs.opencv.org/2.4/modules/core/doc/drawing_functions.html
parseInt is misfeatured like scanf:
parseInt("12 monkeys", 10) is a number with value '12' +"12 monkeys" is a number with value 'NaN' Number("12 monkeys") is a number with value 'NaN'
The command to just stream it to a new container (mp4) needed by some applications like Adobe Premiere Pro without encoding (fast) is:
ffmpeg -i input.mov -qscale 0 output.mp4
Alternative as mentioned in the comments, which re-encodes with best quaility (-qscale 0
):
ffmpeg -i input.mov -q:v 0 output.mp4
Here is a small example for those who want to peruse quickly
object ApplyExample01 extends App {
class Greeter1(var message: String) {
println("A greeter-1 is being instantiated with message " + message)
}
class Greeter2 {
def apply(message: String) = {
println("A greeter-2 is being instantiated with message " + message)
}
}
val g1: Greeter1 = new Greeter1("hello")
val g2: Greeter2 = new Greeter2()
g2("world")
}
output
A greeter-1 is being instantiated with message hello
A greeter-2 is being instantiated with message world
Got better solution:
$('#element').resizable({
stop: function( event, ui ) {
$('#element').height(ui.originalSize.height);
}
});
It can be done by:
Implement your own application class, register for ActivityLifecycleCallbacks - this way you can see what is going on with our app. On every on resume the callback assigns the current visible activity on the screen and on pause it removes the assignment. It uses method registerActivityLifecycleCallbacks()
which was added in API 14.
public class App extends Application {
private Activity activeActivity;
@Override
public void onCreate() {
super.onCreate();
setupActivityListener();
}
private void setupActivityListener() {
registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
@Override
public void onActivityStarted(Activity activity) {
}
@Override
public void onActivityResumed(Activity activity) {
activeActivity = activity;
}
@Override
public void onActivityPaused(Activity activity) {
activeActivity = null;
}
@Override
public void onActivityStopped(Activity activity) {
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
});
}
public Activity getActiveActivity(){
return activeActivity;
}
}
In your service call getApplication()
and cast it to your app class name (App in this case). Than you can call app.getActiveActivity()
- that will give you a current visible Activity (or null when no activity is visible). You can get the name of the Activity by calling activeActivity.getClass().getSimpleName()
I also faced this error but I was not working behind a proxy server at the moment so using npm config set proxy=http://address:8080
couldn't help and ~/.npmrc
didn't contain any proxy setting either. The solution in my case was just to restart my computer.
it defines the protocols address family.this determines the type of socket created. pocket pc support AF_INET.
the content in the following page is quite decent http://etutorials.org/Programming/Pocket+pc+network+programming/Chapter+1.+Winsock/Streaming+TCP+Sockets/
reed these links
http://tools.android.com/tech-docs/new-build-system/version-compatibility https://developer.android.com/studio/releases/gradle-plugin.html
in android studio version 2+, use this in gradle config
android{
..
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
incremental = false;
}
...
}
after 3 days of search and test :(, this solve "rebuild for any run"
There are valid differences between types of architects:
Enterprise architects look at solutions for the enterprise aligining tightly with the enterprise strategy. Eg in a bank, they'll look at the complete IT landscape.
Solution architects focus on a particular solution, for example a new credit card acquiring system in a bank.
Domain architects focus on specific areas, for example an application architect or network architect.
Technical architects generally play the role of solution architects with less focus on the business aspect and more on the techology aspect.
You can disable SSL certificate checking by adding one or more of these command line parameters:
-Dmaven.wagon.http.ssl.insecure=true
- enable use of relaxed SSL check for user generated certificates.-Dmaven.wagon.http.ssl.allowall=true
- enable match of the server's X.509 certificate with hostname. If disabled, a browser like check will be used.-Dmaven.wagon.http.ssl.ignore.validity.dates=true
- ignore issues with certificate dates.Official documentation: http://maven.apache.org/wagon/wagon-providers/wagon-http/
Here's the oneliner for an easy copy-and-paste:
-Dmaven.wagon.http.ssl.insecure=true -Dmaven.wagon.http.ssl.allowall=true -Dmaven.wagon.http.ssl.ignore.validity.dates=true
Ajay Gautam suggested that you could also add the above to the ~/.mavenrc
file as not to have to specify it every time at command line:
$ cat ~/.mavenrc
MAVEN_OPTS="-Dmaven.wagon.http.ssl.insecure=true -Dmaven.wagon.http.ssl.allowall=true -Dmaven.wagon.http.ssl.ignore.validity.dates=true"
Right click on your project
Properties > Configuration Properties > Linker > System
Select Console (/SUBSYSTEM:CONSOLE) in SubSystem
option or you can just type Console in the text field!
Now try it...it should work
Doing:
git checkout master
git pull origin
will fetch and merge the origin/master
branch (you may just say git pull
as origin is the default).
./gradlew
Your directory with gradlew is not included in the PATH, so you must specify path to the gradlew. .
means "current directory".
The default generator for Windows seems to be set to NMAKE. Try to use:
cmake -G "MinGW Makefiles"
Or use the GUI, and select MinGW Makefiles when prompted for a generator. Don't forget to cleanup the directory where you tried to run CMake, or delete the cache in the GUI. Otherwise, it will try again with NMAKE.
@echo off
@color 0A
echo Deleting logs
rmdir /S/Q c:\log\
ping 1.1.1.1 -n 5 -w 1000 > nul
echo Adding log folder back
md c:\log\
You was on the right track. Just add code to add the folder which is deleted back again.
It happens when you have a file with the same name as Makefile target name in the directory where the Makefile is present.
Because %
is only defined for integer types. That's the modulus operator.
5.6.2 of the standard:
The operands of * and / shall have arithmetic or enumeration type; the operands of % shall have integral or enumeration type. [...]
As Oli pointed out, you can use fmod()
. Don't forget to include math.h
.
Heres how to change all databases/tables/columns. Run these queries and they will output all of the subsequent queries necessary to convert your entire schema to utf8. Hope this helps!
-- Change DATABASE Default Collation
SELECT DISTINCT concat('ALTER DATABASE `', TABLE_SCHEMA, '` CHARACTER SET utf8 COLLATE utf8_unicode_ci;')
from information_schema.tables
where TABLE_SCHEMA like 'database_name';
-- Change TABLE Collation / Char Set
SELECT concat('ALTER TABLE `', TABLE_SCHEMA, '`.`', table_name, '` CHARACTER SET utf8 COLLATE utf8_unicode_ci;')
from information_schema.tables
where TABLE_SCHEMA like 'database_name';
-- Change COLUMN Collation / Char Set
SELECT concat('ALTER TABLE `', t1.TABLE_SCHEMA, '`.`', t1.table_name, '` MODIFY `', t1.column_name, '` ', t1.data_type , '(' , t1.CHARACTER_MAXIMUM_LENGTH , ')' , ' CHARACTER SET utf8 COLLATE utf8_unicode_ci;')
from information_schema.columns t1
where t1.TABLE_SCHEMA like 'database_name' and t1.COLLATION_NAME = 'old_charset_name';
df.columnname[1].split('.', 1)
This will split data with the first occurrence of '.' in the string or data frame column value.
You could use KEY
unique key (combination of the data) that changes with props, and that component will be rerendered with updated props.
for example:
dir1=$(find . -name \*foo\* -type d -maxdepth 1 -print | head -n1)
echo "$dir1"
or (For the better shell solution see Adrian Frühwirth's answer)
for dir1 in *
do
[[ -d "$dir1" && "$dir1" =~ foo ]] && break
dir1= #fix based on comment
done
echo "$dir1"
or
dir1=$(find . -type d -maxdepth 1 -print | grep 'foo' | head -n1)
echo "$dir1"
Edited head -n1 based on @ hek2mgl comment
Next based on @chepner's comments
dir1=$(find . -type d -maxdepth 1 -print | grep -m1 'foo')
or
dir1=$(find . -name \*foo\* -type d -maxdepth 1 -print -quit)
According to a slideshow about Facebook's Messaging system, Facebook uses the comet technology to "push" message to web browsers. Facebook's comet server is built on the open sourced Erlang web server mochiweb.
In the picture below, the phrase "channel clusters" means "comet servers".
Many other big web sites build their own comet server, because there are differences between every company's need. But build your own comet server on a open source comet server is a good approach.
You can try icomet, a C1000K C++ comet server built with libevent. icomet also provides a JavaScript library, it is easy to use as simple as:
var comet = new iComet({
sign_url: 'http://' + app_host + '/sign?obj=' + obj,
sub_url: 'http://' + icomet_host + '/sub',
callback: function(msg){
// on server push
alert(msg.content);
}
});
icomet supports a wide range of Browsers and OSes, including Safari(iOS, Mac), IEs(Windows), Firefox, Chrome, etc.
I consider Ashwin's answer to be the most correct, my old answer is below.
docker run -dti foo bash
You can then enter the container and run bash with
docker exec -ti ID_of_foo bash
No need to install sshd :)
In Java 8, it's now as simple as:
movieItems.sort(Comparator.comparing(Movie::getDate));
There is no implicit style that you have to choose, it involves writing a bit of code using the QuartzCore
framework:
//first, you
#import <QuartzCore/QuartzCore.h>
//.....
//Here I add a UITextView in code, it will work if it's added in IB too
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(50, 220, 200, 100)];
//To make the border look very close to a UITextField
[textView.layer setBorderColor:[[[UIColor grayColor] colorWithAlphaComponent:0.5] CGColor]];
[textView.layer setBorderWidth:2.0];
//The rounded corner part, where you specify your view's corner radius:
textView.layer.cornerRadius = 5;
textView.clipsToBounds = YES;
It only works on OS 3.0 and above, but I guess now it's the de facto platform anyway.
another workaround:
var myarray = [];
$("#test").click(function() {
myarray[index]=$("#drop").val();
alert(myarray);
});
i wanted to add all checked checkbox to array. so example, if .each is used:
var vpp = [];
var incr=0;
$('.prsn').each(function(idx) {
if (this.checked) {
var p=$('.pp').eq(idx).val();
vpp[incr]=(p);
incr++;
}
});
//do what ever with vpp array;
Both of these functions look equally valid in terms of reading cookie. You can shave a few bytes off though (and it really is getting into Code Golf territory here):
function readCookie(name) {
var nameEQ = name + "=", ca = document.cookie.split(';'), i = 0, c;
for(;i < ca.length;i++) {
c = ca[i];
while (c[0]==' ') c = c.substring(1);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length);
}
return null;
}
All I did with this is collapse all the variable declarations into one var statement, removed the unnecessary second arguments in calls to substring, and replace the one charAt call into an array dereference.
This still isn't as short as the second function you provided, but even that can have a few bytes taken off:
function read_cookie(key)
{
var result;
return (result = new RegExp('(^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? result[2] : null;
}
I changed the first sub-expression in the regular expression to be a capturing sub-expression, and changed the result[1] part to result[2] to coincide with this change; also removed the unnecessary parens around result[2].
Taking up @ZF007's answer, this is not answering your question as a whole, but can be the solution for the same error. I post it here since I have not found a direct solution as an answer to this error message elsewhere on Stack Overflow.
The error appears when you check whether an array was empty or not.
if np.array([1,2]): print(1)
--> ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
.
if np.array([1,2])[0]: print(1)
--> no ValueError, but: if np.array([])[0]: print(1)
--> IndexError: index 0 is out of bounds for axis 0 with size 0
.
if np.array([1]): print(1)
--> no ValueError, but again will not help at an array with many elements.
if np.array([]): print(1)
--> DeprecationWarning: The truth value of an empty array is ambiguous. Returning False, but in future this will result in an error. Use 'array.size > 0' to check that an array is not empty.
Doing so:
if np.array([]).size: print(1)
solved the error.Use MySQL's STR_TO_DATE()
function to parse the string that you're attempting to insert:
INSERT INTO tblInquiry (fldInquiryReceivedDateTime) VALUES
(STR_TO_DATE('5/15/2012 8:06:26 AM', '%c/%e/%Y %r'))
Your code doesn't get the UTF-8 into memory as you read it back into a string again, so its no longer in UTF-8, but back in UTF-16 (though ideally its best to consider strings at a higher level than any encoding, except when forced to do so).
To get the actual UTF-8 octets you could use:
var serializer = new XmlSerializer(typeof(SomeSerializableObject));
var memoryStream = new MemoryStream();
var streamWriter = new StreamWriter(memoryStream, System.Text.Encoding.UTF8);
serializer.Serialize(streamWriter, entry);
byte[] utf8EncodedXml = memoryStream.ToArray();
I've left out the same disposal you've left. I slightly favour the following (with normal disposal left in):
var serializer = new XmlSerializer(typeof(SomeSerializableObject));
using(var memStm = new MemoryStream())
using(var xw = XmlWriter.Create(memStm))
{
serializer.Serialize(xw, entry);
var utf8 = memStm.ToArray();
}
Which is much the same amount of complexity, but does show that at every stage there is a reasonable choice to do something else, the most pressing of which is to serialise to somewhere other than to memory, such as to a file, TCP/IP stream, database, etc. All in all, it's not really that verbose.
$(document).ready(function()_x000D_
{_x000D_
$("tr:odd").css({_x000D_
"background-color":"#000",_x000D_
"color":"#fff"});_x000D_
});
_x000D_
tbody td{_x000D_
padding: 30px;_x000D_
}_x000D_
_x000D_
tbody tr:nth-child(odd){_x000D_
background-color: #4C8BF5;_x000D_
color: #fff;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<table border="1">_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>1</td>_x000D_
<td>2</td>_x000D_
<td>3</td>_x000D_
<td>4</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>5</td>_x000D_
<td>6</td>_x000D_
<td>7</td>_x000D_
<td>8</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>9</td>_x000D_
<td>10</td>_x000D_
<td>11</td>_x000D_
<td>13</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
There is a CSS selector, really a pseudo-selector, called nth-child. In pure CSS you can do the following:
tr:nth-child(even) {
background-color: #000000;
}
Note: No support in IE 8.
Or, if you have jQuery:
$(document).ready(function()
{
$("tr:even").css("background-color", "#000000");
});
this would be perfect cause we are doing operation on matrix, and the answer should be a single number
sum(sum(matrix==value))
There is npm-package jsfiddle-downloader
.
You are using jQuery, right? Separate JavaScript from HTML.
You can use trigger or triggerHandler.
var $myInput = $('#changeProgramatic').on('change', ChangeValue);
var anotherFunction = function() {
$myInput.val('Another value');
$myInput.trigger('change');
};
From the Reflector'd source:
public static List<TSource> ToList<TSource>(this IEnumerable<TSource> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
return new List<TSource>(source);
}
So yes, your original list won't be updated (i.e. additions or removals) however the referenced objects will.
In short there's no way to recover the passphrase for a pair of SSH keys. Why? Because it was intended this way in the first place for security reasons. The answers the other people gave you are all correct ways to CHANGE the password of your keys, not to recover them. So if you've forgotten your passphrase, the best you can do is create a new pair of SSH keys. Here's how to generate SSH keys and add it to your GitHub account.
my example
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
</head>
<body>
<script>
function PreviewText() {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("uploadText").files[0]);
oFReader.onload = function(oFREvent) {
document.getElementById("uploadTextValue").value = oFREvent.target.result;
document.getElementById("obj").data = oFREvent.target.result;
};
};
jQuery(document).ready(function() {
$('#viewSource').click(function() {
var text = $('#uploadTextValue').val();
alert(text);
//here ajax
});
});
</script>
<object width="100%" height="400" data="" id="obj"></object>
<div>
<input type="hidden" id="uploadTextValue" name="uploadTextValue" value="" />
<input id="uploadText" style="width:120px" type="file" size="10" onchange="PreviewText();" />
</div>
<a href="#" id="viewSource">Source file</a>
</body>
</html>
I would like to add that you can extend the compatibility of :scope by just assigning a temporary attribute to the current node.
let node = [...];
let result;
node.setAttribute("foo", "");
result = window.document.querySelectorAll("[foo] > .bar");
// And, of course, you can also use other combinators.
result = window.document.querySelectorAll("[foo] + .bar");
result = window.document.querySelectorAll("[foo] ~ .bar");
node.removeAttribute("foo");
No need to use the filter or tag in template. Just use format_html() to translate variable to html and Django will automatically turn escape off for you variable.
format_html("<h1>Hello</h1>")
Check out here https://docs.djangoproject.com/en/3.0/ref/utils/#django.utils.html.format_html
The new ASP.NET Web API is a continuation of the previous WCF Web API project (although some of the concepts have changed).
WCF was originally created to enable SOAP-based services. For simpler RESTful or RPCish services (think clients like jQuery) ASP.NET Web API should be good choice.
For us, WCF is used for SOAP and Web API for REST. I wish Web API supported SOAP too. We are not using advanced features of WCF. Here is comparison from MSDN:
ASP.net Web API is all about HTTP and REST based GET,POST,PUT,DELETE with well know ASP.net MVC style of programming and JSON returnable; web API is for all the light weight process and pure HTTP based components. For one to go ahead with WCF even for simple or simplest single web service it will bring all the extra baggage. For light weight simple service for ajax or dynamic calls always WebApi just solves the need. This neatly complements or helps in parallel to the ASP.net MVC.
Check out the podcast : Hanselminutes Podcast 264 - This is not your father's WCF - All about the WebAPI with Glenn Block by Scott Hanselman for more information.
In the scenarios listed below you should go for WCF:
WEB API is a framework for developing RESTful/HTTP services.
There are so many clients that do not understand SOAP like Browsers, HTML5, in those cases WEB APIs are a good choice.
HTTP services header specifies how to secure service, how to cache the information, type of the message body and HTTP body can specify any type of content like HTML not just XML as SOAP services.
Taken from C# 3.0 Nutshell book, by Joseph Albahari
A ManualResetEvent is a variation on AutoResetEvent. It differs in that it doesn't automatically reset after a thread is let through on a WaitOne call, and so functions like a gate: calling Set opens the gate, allowing any number of threads that WaitOne at the gate through; calling Reset closes the gate, causing, potentially, a queue of waiters to accumulate until its next opened.
One could simulate this functionality with a boolean "gateOpen" field (declared with the volatile keyword) in combination with "spin-sleeping" – repeatedly checking the flag, and then sleeping for a short period of time.
ManualResetEvents are sometimes used to signal that a particular operation is complete, or that a thread's completed initialization and is ready to perform work.
remember, SSL/TLS operates at the Transport Layer, so all the crypto goo happens under the application-layer HTTP stuff.
http://en.wikipedia.org/wiki/File:IP_stack_connections.svg
that's the long way of saying, "Yes!"
The proper way to do this in VB is to use on of the VB constants for newlines. The main three are
VB by default doesn't allow for any character escape codes in strings which is different than languages like C# and C++ which do. One of the reasons for doing this is ease of use when dealing with file paths.
Lets assume your broadcastReceiver
is defined like this:
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// your code
}
};
If you are using LocalBroadcast
in an Activity, then this is how you'll unregister:
LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver);
If you are using LocalBroadcast
in a Fragment, then this is how you'll unregister:
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(broadcastReceiver);
If you are using normal broadcast in an Activity, then this is how you'll unregister:
unregisterReceiver(broadcastReceiver);
If you are using normal broadcast in a Fragment, then this is how you'll unregister:
getActivity().unregisterReceiver(broadcastReceiver);
Go into your Gradle and look for sourceCompatibility and change it from 1.6 to 7. That worked for me at least.
You can also go into your module settings and set the Source/Target Compatibility to 1.7.
That will produce the following code in your Gradle:
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
If you are using server side rending, you can use StaticRouter
. With your context
as props
and then adding <Redirect path="/somewhere" />
component in your app. The idea is everytime react-router matches a redirect component it will add something into the context you passed into the static router to let you know your path matches a redirect component. now that you know you hit a redirect you just need to check if thats the redirect you are looking for. then just redirect through the server. ctx.redirect('https://example/com')
.
Use negative lookaround: (?!
pattern
)
Positive lookarounds can be used to assert that a pattern matches. Negative lookarounds is the opposite: it's used to assert that a pattern DOES NOT match. Some flavor supports assertions; some puts limitations on lookbehind, etc.
These are attempts to come up with regex solutions to toy problems as exercises; they should be educational if you're trying to learn the various ways you can use lookarounds (nesting them, using them to capture, etc):
function printdiv(printdivname) {
var headstr = "<html><head><title>Booking Details</title></head><body>";
var footstr = "</body>";
var newstr = document.getElementById(printdivname).innerHTML;
var oldstr = document.body.innerHTML;
document.body.innerHTML = headstr+newstr+footstr;
window.print();
document.body.innerHTML = oldstr;
return false;
}
This will print the div
area you want and set the content back to as it was. printdivname
is the div
to be printed.
Depending on what you want the file to contain:
touch /path/to/file
for an empty filesomecommand > /path/to/file
for a file containing the output of some command.
eg: grep --help > randomtext.txt
echo "This is some text" > randomtext.txt
nano /path/to/file
or vi /path/to/file
(or any other editor emacs,gedit etc
)
It either opens the existing one for editing or creates & opens the empty file to enter, if it doesn't exist
Create the file using cat
$ cat > myfile.txt
Now, just type whatever you want in the file:
Hello World!
CTRL-D to save and exit
There are several possible solutions:
touch file
>file
echo -n > file
printf '' > file
The echo
version will work only if your version of echo
supports the -n
switch to suppress newlines. This is a non-standard addition. The other examples will all work in a POSIX shell.
echo '' > file
printf '\n' > file
This is a valid "text file" because it ends in a newline.
"$EDITOR" file
echo 'text' > file
cat > file <<END \
text
END
printf 'text\n' > file
These are equivalent. The $EDITOR
command assumes that you have an interactive text editor defined in the EDITOR environment variable and that you interactively enter equivalent text. The cat
version presumes a literal newline after the \
and after each other line. Other than that these will all work in a POSIX shell.
Of course there are many other methods of writing and creating files, too.
Yeah, use .match
, rather than .search
. The result from the .match
call will return the actual string that was matched itself, but it can still be used as a boolean value.
var string = "Stackoverflow is the BEST";
var result = string.match(/best/i);
// result == 'BEST';
if (result){
alert('Matched');
}
Using a regular expression like that is probably the tidiest and most obvious way to do that in JavaScript, but bear in mind it is a regular expression, and thus can contain regex metacharacters. If you want to take the string from elsewhere (eg, user input), or if you want to avoid having to escape a lot of metacharacters, then you're probably best using indexOf
like this:
matchString = 'best';
// If the match string is coming from user input you could do
// matchString = userInput.toLowerCase() here.
if (string.toLowerCase().indexOf(matchString) != -1){
alert('Matched');
}
id
is of primitive type int
and not an Object
. You cannot call methods on a primitive as you are doing here :
id.equals
Try replacing this:
if (id.equals(list[pos].getItemNumber())){ //Getting error on "equals"
with
if (id == list[pos].getItemNumber()){ //Getting error on "equals"
You're close. You can strip the whitespace by using the replace
method like this:
$answer.replace(' ','')
There needs to be no space or characters between the second set of quotes in the replace method (replacing the whitespace with nothing).
The primary advantage of linked lists over arrays is that the links provide us with the capability to rearrange the items efficiently. Sedgewick, p. 91
Here you have two links for MD5 hashing and other hash methods:
Javadoc API: https://docs.oracle.com/javase/1.5.0/docs/api/java/security/MessageDigest.html
Try this to scroll on top
<script>
$(document).ready(function(){
$(window).scrollTop(0);
});
</script>
Change your code to.
<?php
$sqlupdate1 = "UPDATE table SET commodity_quantity=".$qty."WHERE user=".$rows['user'];
?>
There was syntax error in your query.
JavaScript is a dynamic language. You could just add it to the object itself.
var marker = new google.maps.Marker(markerOptions);
marker.metadata = {type: "point", id: 1};
Also, because all v3 objects extend MVCObject()
. You can use:
marker.setValues({type: "point", id: 1});
// or
marker.set("type", "point");
marker.set("id", 1);
var val = marker.get("id");
Using Html Agility Pack as suggested by SLaks, this becomes very easy:
string html = webClient.DownloadString(url);
var doc = new HtmlDocument();
doc.LoadHtml(html);
HtmlNode specificNode = doc.GetElementById("nodeId");
HtmlNodeCollection nodesMatchingXPath = doc.DocumentNode.SelectNodes("x/path/nodes");
Umair R's answer is mostly the right move to solve the problem, as this error used to be caused by the missing links between opencv libs and the programme. so there is the need to specify the ld_libraty_path configuration. ps. the usual library path is suppose to be:
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib
I have tried this and it worked well.
You can use regex.findall()
:
import re
line = " I am having a very nice day."
count = len(re.findall(r'\w+', line))
print (count)
Here is probably the simplest way to go about it (with a reproducible example):
library(plyr)
df <- data.frame(ID=rep(1:3, 3), Obs_1=rnorm(9), Obs_2=rnorm(9), Obs_3=rnorm(9))
ddply(df, .(ID), summarize, Obs_1_mean=mean(Obs_1), Obs_1_std_dev=sd(Obs_1),
Obs_2_mean=mean(Obs_2), Obs_2_std_dev=sd(Obs_2))
ID Obs_1_mean Obs_1_std_dev Obs_2_mean Obs_2_std_dev
1 1 -0.13994642 0.8258445 -0.15186380 0.4251405
2 2 1.49982393 0.2282299 0.50816036 0.5812907
3 3 -0.09269806 0.6115075 -0.01943867 1.3348792
EDIT: The following approach saves you a lot of typing when dealing with many columns.
ddply(df, .(ID), colwise(mean))
ID Obs_1 Obs_2 Obs_3
1 1 -0.3748831 0.1787371 1.0749142
2 2 -1.0363973 0.0157575 -0.8826969
3 3 1.0721708 -1.1339571 -0.5983944
ddply(df, .(ID), colwise(sd))
ID Obs_1 Obs_2 Obs_3
1 1 0.8732498 0.4853133 0.5945867
2 2 0.2978193 1.0451626 0.5235572
3 3 0.4796820 0.7563216 1.4404602
You can use Css Selector or Xpath:
Approach 1 : CSS Selector
driver.switchTo().frame(driver.findElement(By.cssSelector("iframe[title='Fill Quote']")));
Approach 2 : Xpath
driver.switchTo().frame(driver.findElement(By.xpath("//iframe[@title='Fill Quote']")));
I prefer not messing with HTML and use as much as native infrastructure as possible. You can use Output widget with Hbox or VBox:
import ipywidgets as widgets
from IPython import display
import pandas as pd
import numpy as np
# sample data
df1 = pd.DataFrame(np.random.randn(8, 3))
df2 = pd.DataFrame(np.random.randn(8, 3))
# create output widgets
widget1 = widgets.Output()
widget2 = widgets.Output()
# render in output widgets
with widget1:
display.display(df1)
with widget2:
display.display(df2)
# create HBox
hbox = widgets.HBox([widget1, widget2])
# render hbox
hbox
This outputs:
Try like this, it worked for me
<root>
<!--<level value="ALL" />-->
<level value="ERROR" />
<level value="INFO" />
<level value="WARN" />
</root>
This logs 3 types of errors - error, info, and warning
Define "remove".
Arrays are fixed length and can not be resized once created. You can set an element to null
to remove an object reference;
for (int i = 0; i < myStringArray.length(); i++)
{
if (myStringArray[i].equals(stringToRemove))
{
myStringArray[i] = null;
break;
}
}
or
myStringArray[indexOfStringToRemove] = null;
If you want a dynamically sized array where the object is actually removed and the list (array) size is adjusted accordingly, use an ArrayList<String>
myArrayList.remove(stringToRemove);
or
myArrayList.remove(indexOfStringToRemove);
Edit in response to OP's edit to his question and comment below
String r = myArrayList.get(rgenerator.nextInt(myArrayList.size()));
In case this is of use to some newer dev's because its not specified above. Just to be very explicit:
You need two things if using onConfigurationChanged:
An onConfigurationChanged
method in your Activity Class
Specify in your manifest which configuration changes will be handled by your onConfigurationChanged
method
The manifest snippet in the above answers, while no doubt correct for the particular app that manifest belongs to, is NOT exactly what you need to add in your manifest to trigger the onConfigurationChanged method in your Activity Class. i.e. the below manifest entry may not be correct for your app.
<activity name= ".MainActivity" android:configChanges="orientation|screenSize"/>
In the above manifest entry, there are various Android actions for android:configChanges=""
which can trigger the onCreate in your Activity lifecycle.
This is very important - The ones NOT Specified in the manifest are the ones that trigger your onCreate and The ones specified in the manifest are the ones that trigger your onConfigurationChanged
method in your Activity Class.
So you need to identify which config changes you need to handle yourself. For the Android Encyclopedically Challenged like me, I used the quick hints pop-out in Android Studio and added in almost every possible configuration option. Listing all of these basically said that I would handle everything and onCreate will never be called due to configurations.
<activity name= ".MainActivity" android:configChanges="screenLayout|touchscreen|mnc|mcc|density|uiMode|fontScale|orientation|keyboard|layoutDirection|locale|navigation|smallestScreenSize|keyboardHidden|colorMode|screenSize"/>
Now obviously I don't want to handle everything, so I began eliminating the above options one at a time. Re-building and testing my app after each removal.
Another important point: If there is just one configuration option being handled automatically that triggers your onCreate (You do not have it listed in your manifest above), then it will appear like onConfigurationChanged
is not working. You must put all relevant ones into your manifest.
I ended up with 3 that were triggering onCreate originally, then I tested on an S10+ and I was still getting the onCreate, so I had to do my elimination exercise again and I also needed the |screenSize
. So test on a selection of platforms.
<activity name= ".MainActivity" android:configChanges="screenLayout|uiMode|orientation|screenSize"/>
So my suggestion, although I'm sure someone can poke holes in this:
Add your onConfigurationChanged
method in your Activity Class with a TOAST or LOG so you can see when its working.
Add all possible configuration options to your manifest.
Confirm your onConfigurationChanged
method is working by testing your app.
Remove each config option from your manifest file one at a time, testing your app after each.
Test on as large a variety of devices as possible.
Do not copy/paste my snippet above to your manifest file. Android updates change the list, so use the pop-out Android Studio hints to make sure you get them all.
I hope this saves someone some time.
My onConfigurationChanged
method just for info below. onConfigurationChanged
is called in the lifecycle after the new orientation is available, but before the UI has been recreated. Hence my first if
to check the orientation works correctly, and then the 2nd nested if
to look at the visibility of my UI ImageView also works correctly.
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
pokerCardLarge = findViewById(R.id.pokerCardLgImageView);
if(pokerCardLarge.getVisibility() == pokerCardLarge.VISIBLE){
Bitmap image = ((BitmapDrawable)pokerCardLarge.getDrawable()).getBitmap();
pokerCardLarge.setVisibility(pokerCardLarge.VISIBLE);
pokerCardLarge.setImageBitmap(image);
}
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
pokerCardLarge = findViewById(R.id.pokerCardLgImageView);
if(pokerCardLarge.getVisibility() == pokerCardLarge.VISIBLE){
Bitmap image = ((BitmapDrawable)pokerCardLarge.getDrawable()).getBitmap();
pokerCardLarge.setVisibility(pokerCardLarge.VISIBLE);
pokerCardLarge.setImageBitmap(image);
}
}
}
i solved this in a shorter fashion.
Dim marray() as variant, array2() as variant, YY ,ZZ as integer
YY=1
ZZ=1
Redim marray(1 to 1000, 1 to 10)
Do while ZZ<100 ' this is populating the first array
marray(ZZ,YY)= "something"
ZZ=ZZ+1
YY=YY+1
Loop
'this part is where you store your array in another then resize and restore to original
array2= marray
Redim marray(1 to ZZ-1, 1 to YY)
marray = array2
Just use disabled and/or hidden attributes:
<option selected disabled hidden style='display: none' value=''></option>
selected
makes this option the default one.disabled
makes this option unclickable.style='display: none'
makes this option not displayed in older browsers. See: Can I Use documentation for hidden attribute.hidden
makes this option to don't be displayed in the drop-down list. We've just released arg.js, a project aimed at solving this problem once and for all. It's traditionally been so difficult but now you can do:
var querystring = Arg.url({name: "Mat", state: "CO"});
And reading works:
var name = Arg("name");
or getting the whole lot:
var params = Arg.all();
and if you care about the difference between ?query=true
and #hash=true
then you can use the Arg.query()
and Arg.hash()
methods.
Use DecimalFormat
double answer = 5.0;
DecimalFormat df = new DecimalFormat("###.#");
System.out.println(df.format(answer));
Starting in pandas 0.24 you can simplify this with the mode
keyword argument of ExcelWriter
:
import pandas as pd
with pd.ExcelWriter('the_file.xlsx', engine='openpyxl', mode='a') as writer:
data_filtered.to_excel(writer)
I needed to know how to loop over enum values (was testing lots of permutations of several enums) and I found this to work well:
export enum Environment {
Prod = "http://asdf.com",
Stage = "http://asdf1234.com",
Test = "http://asdfasdf.example.com"
}
Object.keys(Environment).forEach((environmentKeyValue) => {
const env = Environment[environmentKeyValue as keyof typeof Environment]
// env is now equivalent to Environment.Prod, Environment.Stage, or Environment.Test
}
Source: https://blog.mikeski.net/development/javascript/typescript-enums-to-from-string/
If you are using the GET request to actually SEND data...
check: http://techhelplist.com/index.php/tech-tutorials/37-windows-troubles/60-vbscript-sending-get-request
The problem with MSXML2.XMLHTTP is that there are several versions of it, with different names depending on the windows os version and patches.
this explains it: http://support.microsoft.com/kb/269238
i have had more luck using vbscript to call
set ID = CreateObject("InternetExplorer.Application")
IE.visible = 0
IE.navigate "http://example.com/parser.php?key=" & value & "key2=" & value2
do while IE.Busy....
....and more stuff but just to let the request go thru.
I will answer this question in terms of AngularFire, Firebase's library for Angular.
Tl;dr: superpowers. :-)
AngularFire's three-way data binding. Angular binds the view and the $scope, i.e., what your users do in the view automagically updates in the local variables, and when your JavaScript updates a local variable the view automagically updates. With Firebase the cloud database also updates automagically. You don't need to write $http.get or $http.put requests, the data just updates.
Five-way data binding, and seven-way, nine-way, etc. I made a tic-tac-toe game using AngularFire. Two players can play together, with the two views updating the two $scopes and the cloud database. You could make a game with three or more players, all sharing one Firebase database.
AngularFire's OAuth2 library makes authorization easy with Facebook, GitHub, Google, Twitter, tokens, and passwords.
Double security. You can set up your Angular routes to require authorization, and set up rules in Firebase about who can read and write data.
There's no back end. You don't need to make a server with Node and Express. Running your own server can be a lot of work, require knowing about security, require that someone do something if the server goes down, etc.
Fast. If your server is in San Francisco and the client is in San Jose, fine. But for a client in Bangalore connecting to your server will be slower. Firebase is deployed around the world for fast connections everywhere.
for me i found some solutions: it is a working solution
@echo off
title a game for youtube
explorer "https://thepythoncoding.blogspot.com/2020/11/how-to-echo-with-different-colors-in.html"
SETLOCAL EnableDelayedExpansion
for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (
set "DEL=%%a"
)
echo say the name of the colors, don't read
call :ColorText 0a "blue"
call :ColorText 0C "green"
call :ColorText 0b "red"
echo(
call :ColorText 19 "yellow"
call :ColorText 2F "black"
call :ColorText 4e "white"
goto :Beginoffile
:ColorText
echo off
<nul set /p ".=%DEL%" > "%~2"
findstr /v /a:%1 /R "^$" "%~2" nul
del "%~2" > nul 2>&1
goto :eof
:Beginoffile
Disable selection everywhere
input, textarea ,*[contenteditable=true] {
-webkit-touch-callout:default;
-webkit-user-select:text;
-moz-user-select:text;
-ms-user-select:text;
user-select:text;
}
IE7
<BODY oncontextmenu="return false" onselectstart="return false" ondragstart="return false">
Old question but nowadays CSS3 makes vertical alignment really simple!
Just add to #abc
the following css:
display:flex;
align-items:center;
Original question demo updated
Simple Example:
.vertical-align-content {_x000D_
background-color:#f18c16;_x000D_
height:150px;_x000D_
display:flex;_x000D_
align-items:center;_x000D_
/* Uncomment next line to get horizontal align also */_x000D_
/* justify-content:center; */_x000D_
}
_x000D_
<div class="vertical-align-content">_x000D_
Hodor!_x000D_
</div>
_x000D_
At its simplest, the difference is one of plurality:
I used to forget which one is which and end up having to look it up many times. To fix this problem, imagine rolling back as several rotations then hopefully the fact that rollback is plural will help you (and me!) remember which one is which. Backout sounds 'less plural' than rollback to me. Imagine backing out of a single parking space.
So, the mnemonic is:
I hope this helps!
Try this way:
select * from tab
where DateCol between DateAdd(DD,-7,GETDATE() ) and GETDATE()
button {
width:1000px;
}
or even
button {
width:1000px !important
}
If thats what you mean
I struggled with this problem the past few days.
I suggest reading Scott Guthrie's blog post Recipe: Enabling Windows Authentication within an Intranet ASP.NET Web application
For me the problem was that although I had Windows Authentication enabled in IIS and I had <authentication mode="Windows" />
in the <system.web>
section of web.config, I was not preventing anonymous access. This last part was the key. You need to prevent anonymous access to ensure that the browser sends the credentials.
You can either configure IIS in Control Panel so that your site (or machine) uses Windows authentication and denies anonymous access or you can add the following to your web.config in the system.web section:
<authentication mode="Windows" />
<authorization>
<deny users="?"/>
</authorization>
Here is an example of how you can do it in Spring 4.0+
application.properties
content:some.key=yes,no,cancel
@Autowire
private Environment env;
...
String[] springRocks = env.getProperty("some.key", String[].class);
This feature has been added in dplyr v0.3. You can now pass a named character vector to the by
argument in left_join
(and other joining functions) to specify which columns to join on in each data frame. With the example given in the original question, the code would be:
left_join(test_data, kantrowitz, by = c("first_name" = "name"))
I thought I would add to this question as it is the top google search result.
As has been noted in the comments, in EF Core there is no support for using annotations (Key attribute) and it must be done with fluent.
As I was working on a large migration from EF6 to EF Core this was unsavoury and so I tried to hack it by using Reflection to look for the Key attribute and then apply it during OnModelCreating
// get all composite keys (entity decorated by more than 1 [Key] attribute
foreach (var entity in modelBuilder.Model.GetEntityTypes()
.Where(t =>
t.ClrType.GetProperties()
.Count(p => p.CustomAttributes.Any(a => a.AttributeType == typeof(KeyAttribute))) > 1))
{
// get the keys in the appropriate order
var orderedKeys = entity.ClrType
.GetProperties()
.Where(p => p.CustomAttributes.Any(a => a.AttributeType == typeof(KeyAttribute)))
.OrderBy(p =>
p.CustomAttributes.Single(x => x.AttributeType == typeof(ColumnAttribute))?
.NamedArguments?.Single(y => y.MemberName == nameof(ColumnAttribute.Order))
.TypedValue.Value ?? 0)
.Select(x => x.Name)
.ToArray();
// apply the keys to the model builder
modelBuilder.Entity(entity.ClrType).HasKey(orderedKeys);
}
I haven't fully tested this in all situations, but it works in my basic tests. Hope this helps someone
$total_ratings
is an array.
There are a lot of answers here that use a set(..)
(which is fast given the elements are hashable), or a list (which has the downside that it results in an O(n2) algorithm.
The function I propose is a hybrid one: we use a set(..)
for items that are hashable, and a list(..)
for the ones that are not. Furthermore it is implemented as a generator such that we can for instance limit the number of items, or do some additional filtering.
Finally we also can use a key
argument to specify in what way the elements should be unique. For instance we can use this if we want to filter a list of strings such that every string in the output has a different length.
def uniq(iterable, key=lambda x: x):
seens = set()
seenl = []
for item in iterable:
k = key(item)
try:
seen = k in seens
except TypeError:
seen = k in seenl
if not seen:
yield item
try:
seens.add(k)
except TypeError:
seenl.append(k)
We can now for instance use this like:
>>> list(uniq(["apple", "pear", "banana", "lemon"], len))
['apple', 'pear', 'banana']
>>> list(uniq(["apple", "pear", "lemon", "banana"], len))
['apple', 'pear', 'banana']
>>> list(uniq(["apple", "pear", {}, "lemon", [], "banana"], len))
['apple', 'pear', {}, 'banana']
>>> list(uniq(["apple", "pear", {}, "lemon", [], "banana"]))
['apple', 'pear', {}, 'lemon', [], 'banana']
>>> list(uniq(["apple", "pear", {}, "lemon", {}, "banana"]))
['apple', 'pear', {}, 'lemon', 'banana']
It is thus a uniqeness filter that can work on any iterable and filter out uniques, regardless whether these are hashable or not.
It makes one assumption: that if one object is hashable, and another one is not, the two objects are never equal. This can strictly speaking happen, although it would be very uncommon.
"Stubbing-out a function means you'll write only enough to show that the function was called, leaving the details for later when you have more time."
From: SAMS Teach yourself C++, Jesse Liberty and Bradley Jones
public class InShotApp extends Application {
@Override
public void onCreate() {
super.onCreate();
registerActivityLifecycle();
}
private void registerActivityLifecycle() {
registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {
activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE); }
@Override
public void onActivityStarted(@NonNull Activity activity) {
}
@Override
public void onActivityResumed(@NonNull Activity activity) {
}
@Override
public void onActivityPaused(@NonNull Activity activity) {
}
@Override
public void onActivityStopped(@NonNull Activity activity) {
}
@Override
public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {
}
@Override
public void onActivityDestroyed(@NonNull Activity activity) {
}
});
}
}
# needed to create data for 1000 fictitious employees for testing code
# code relating to randomly assigning forenames, surnames, and genders
# has been removed as not germaine to the question asked above but FYI
# genders were randomly assigned, forenames/surnames were web scrapped,
# there is no accounting for leap years, and the data stored in mySQL
import random
from datetime import datetime
from datetime import timedelta
for employee in range(1000):
# assign a random date of birth (employees are aged between sixteen and sixty five)
dlt = random.randint(365*16, 365*65)
dob = datetime.today() - timedelta(days=dlt)
# assign a random date of hire sometime between sixteenth birthday and yesterday
doh = datetime.today() - timedelta(days=random.randint(1, dlt-365*16))
print("born {} hired {}".format(dob.strftime("%d-%m-%y"), doh.strftime("%d-%m-%y")))
First, eq is for comparing strings; == is for comparing numbers.
Even if the "if" condition is satisfied, it doesn't evaluate the "then" block.
I think your problem is that your variables don't contain what you think they do. I think your $str1
or $str2
contains something like "taste\n" or so. Check them by printing before your if: print "str1='$str1'\n";
.
The trailing newline can be removed with the chomp($str1);
function.
I came across this question when I was trying similar things.
A very nice and simple sample is presented at w3schools website.
https://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_modal&stacked=h
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<title>Bootstrap Example</title>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="container">_x000D_
<h2>Modal Example</h2>_x000D_
<!-- Trigger the modal with a button -->_x000D_
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>_x000D_
_x000D_
<!-- Modal -->_x000D_
<div class="modal fade" id="myModal" role="dialog">_x000D_
<div class="modal-dialog">_x000D_
_x000D_
<!-- Modal content-->_x000D_
<div class="modal-content">_x000D_
<div class="modal-header">_x000D_
<button type="button" class="close" data-dismiss="modal">×</button>_x000D_
<h4 class="modal-title">Modal Header</h4>_x000D_
</div>_x000D_
<div class="modal-body">_x000D_
<p>Some text in the modal.</p>_x000D_
</div>_x000D_
<div class="modal-footer">_x000D_
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
A new method lines
has been introduced to String
class in java-11, which returns Stream<String>
Returns a stream of substrings extracted from this string partitioned by line terminators.
Line terminators recognized are line feed "\n" (U+000A), carriage return "\r" (U+000D) and a carriage return followed immediately by a line feed "\r\n" (U+000D U+000A).
Here are a few examples:
jshell> "lorem \n ipusm \n sit".lines().forEach(System.out::println)
lorem
ipusm
sit
jshell> "lorem \n ipusm \r sit".lines().forEach(System.out::println)
lorem
ipusm
sit
jshell> "lorem \n ipusm \r\n sit".lines().forEach(System.out::println)
lorem
ipusm
sit
VLC should be able to do this.
You can bundle your Button(s) within a RelativeLayout even if your Parent Layout is Linear. Make Sure the outer most parent has android:layout_height attribute set to match_parent. And in that Button tag add 'android:alignParentBottom="True" '
You don't really need a sub-select:
SELECT a, COUNT(*) AS b,
SUM( CASE WHEN c = 'const' THEN 1 ELSE 0 END ) as d,
from t group by a order by b desc
The simplest method to clear a form with a button in angular2+ is
give your form a name using #
<form #your_form_name (ngSubmit)="submitData()"> </form>
<button (click)="clearForm(Your_form_name)"> clear form </button>
in your component.ts file
clearForm(form: FormGroup) {
form.reset();
}
Swift 4.2:
@IBOutlet weak var viewLabel1: UIView!
@IBOutlet weak var viewLabel2: UIView!
override func viewDidLoad() {
super.viewDidLoad()
let myView = UITapGestureRecognizer(target: self, action: #selector(someAction(_:)))
self.viewLabel1.addGestureRecognizer(myView)
}
@objc func someAction(_ sender:UITapGestureRecognizer){
viewLabel2.isHidden = true
}
<script type="text/javascript">
var multilinestr = `
line 1
line 2
line 3
line 4
line 5
line 6`;
totallines = multilinestr.split("\n");
lines = str.split("\n");
console.log(lines.length);
</script>
thats works in my case
Update January 2017 (two years later):
You can now search for commit messages! (still only in the master branch)
February 2015: Not sure that could ever be possible, considering the current search infrastructure base on Elasticsearch (introduced in January 2013).
As an answer "drawing from credible and/or official sources", here is an interview done with the GitHub people in charge of introducing Elasticsearch at GitHub (August 2013)
Tim Pease: We have two document types in there: One is a source code file and the other one is a repository. The way that git works is you have commits and you have a branch for each commit. Repository documents keep track of the most recent commit for that particular repository that has been indexed. When a user pushes a new commit up to Github, we then pull that repository document from elasticsearch. We then see the most recently indexed commit and then we get a list of all the files that had been modified, or added, or deleted between this recent push and what we have previously indexed. Then we can go ahead and just update those documents which have been changed. We don’t have to re-index the entire source code tree every time someone pushes.
Andrew Cholakian: So, you guys only index, I’m assuming, the master branch.
Tim Pease: Correct. It’s only the head of the master branch that you’re going to get in there and still that’s a lot of data, two billion documents, 30 terabytes.
Andrew Cholakian: That is awesomely huge.
[...]
Tim Pease: With indexing source code on push, it’s a self-healing process.
We have that repository document which keeps track of the last indexed commit. If we missed, just happen to miss three commits where those jobs fail, the next commit that comes in, we’re still looking at the diff between the previous commit that we indexed and the one that we’re seeing with this new push.
You do agit diff
and you get all the files that have been updated, deleted, or added. You can just say, “Okay, we need to remove these files. We need to add these files, and all that.” It’s self-healing and that’s the approach that we have taken with pretty much all of the architecture.
That all means not all the branches of all the repo would be indexed with that approach.
A global commit message search isn't available for now.
And Tim Pease himself confirms commit messages are not indexed.
Note that it isn't impossible to get one's own elasticsearch local indexing of a local clone: see "Searching a git repository with ElasticSearch"
But for a specific repo, the easiest remains to clone it and do a:
git log --all --grep='my search'
(More options at "How to search a Git repository by commit message?")
This error can appear when the web server can't access the mail server. Make sure the web server can reach the mail server, for instance pinging it.
If you want to make address directly, the worksheet must exist.
Turning off automatic recalculation want help you :)
But... you can get value indirectly...
.FormulaR1C1 = "=INDIRECT(ADDRESS(2,7,1,0,""" & strProjectName & """),FALSE)"
At the time formula is inserted it will return #REF error, because strProjectName sheet does not exist.
But after this worksheet appear Excel will calculate formula again and proper value will be shown.
Disadvantage: there will be no tracking, so if you move the cell or change worksheet name, the formula will not adjust to the changes as in the direct addressing.
printf() doesn't directly support that. Instead you have to make your own function.
Something like:
while (n) {
if (n & 1)
printf("1");
else
printf("0");
n >>= 1;
}
printf("\n");
If it is a local file, you have to wrap it in htmlspecialchars like so:
$myfile = htmlspecialchars(file_get_contents($file_name));
Then it works
You need to do encode
on tmp[0]
, not on tmp
.
tmp
is not a string. It contains a (Unicode) string.
Try running type(tmp)
and print dir(tmp)
to see it for yourself.
Seems the SMTP as internet standard uses only reliable Transport protocol. RFC821 has TCP, NCP, NITS as examples!
I had a similar situation but the following worked best for me..
=Iif(Fields!Sales_Diff.Value)>1,Fields!Sales_Diff.Value),"")
You directly change the figure size by using
plt.set_figsize(figure=(10, 10))