In my opinion one of the worst chosen word's to describe the process, as it is not related to anything in real-life or similar. In general the word "queue" is very bad as if pronounced, it sounds like the English character "q". See the inefficiency here?
enqueue: to place something into a queue; to add an element to the tail of a queue;
dequeue to take something out of a queue; to remove the first available element from the head of a queue
In the current documentation we can specify a build.json with the keystore:
{
"android": {
"debug": {
"keystore": "..\android.keystore",
"storePassword": "android",
"alias": "mykey1",
"password" : "password",
"keystoreType": ""
},
"release": {
"keystore": "..\android.keystore",
"storePassword": "",
"alias": "mykey2",
"password" : "password",
"keystoreType": ""
}
}
}
And then, execute the commando with --buildConfig argumente, this way:
cordova run android --buildConfig
I normally run sites on Linux, but I also develop on a local Windows machine. I've run into this problem many times and just fixed the tables when I encountered the problems. I installed an app yesterday to help someone out and of course ran into the problem again. So, I decided it was time to figure out what was going on - and found this thread. I really don't like the idea of changing the sql_mode of the server to an earlier mode (by default), so I came up with a simple (me thinks) solution.
This solution would of course require developers to wrap their table creation scripts to compensate for the MySQL issue running on Windows. You'll see similar concepts in dump files. One BIG caveat is that this could/will cause problems if partitioning is used.
// Store the current sql_mode
mysql_query("set @orig_mode = @@global.sql_mode");
// Set sql_mode to one that won't trigger errors...
mysql_query('set @@global.sql_mode = "MYSQL40"');
/**
* Do table creations here...
*/
// Change it back to original sql_mode
mysql_query('set @@global.sql_mode = @orig_mode');
That's about it.
MVC, MVP, MVVM
MVC (old one)
MVP (more modular because of its low-coupling. Presenter is a mediator between the View and Model)
MVVM (You already have two-way binding between VM and UI component, so it is more automated than MVP)
I found that place to put the redirect complent of react-router is in the method render, but if you want to redirect after some validation, by example, the best way to redirect is using the old reliable, window.location.href, i.e.:
evalSuccessResponse(data){
if(data.code===200){
window.location.href = urlOneSignHome;
}else{
//TODO Something
}
}
When you are programming React Native never will need to go outside of the app, and the mechanism to open another app is completely different.
May be using this query you don't get any result or empty result. You need to use OR
instead of AND
in your query like below.
$query = mysql_query("SELECT image_id FROM list WHERE (style_id = 24 AND style_value = 'red') OR (style_id = 25 AND style_value = 'big') OR (style_id = 27 AND style_value = 'round');
Try out this query.
This might be it:
Is there a bug with radio buttons in jQuery 1.9.1?
In short: Don't use attr() but prop() for checking radio buttons. God I hate JS...
The simplest answer in C# (if you are C# inclined).
Actions action = new Actions();
action.KeyDown(OpenQA.Selenium.Keys.Control).SendKeys("a").KeyUp(OpenQA.Selenium.Keys.Control).perform();
This answer is almost given by Hari Reddy, but I have fixed the case which he'd got wrong on some keywords, added the KeyUp or you get in a mess leaving the control key down.
I've also added the clarification on OpenQA.Selenium.Keys, because you may also be using Windows.Forms on the same class as I was an require this clarity.
Lastly, I type "a" because I found that to be the simplest way and I can see no suggestion from the OP that they don't want the simplest answer.
Many thanks to Hari Reddy though as I was a novice in Actions class usage and I was writing many different commands. Chaining them together the way he showed is quicker :-)
@adeneo answer works for Firefox and chrome... For IE the below can be used.
if (window.navigator.msSaveOrOpenBlob) {_x000D_
var blob = new Blob([decodeURIComponent(encodeURI(result.data))], {_x000D_
type: "text/csv;charset=utf-8;"_x000D_
});_x000D_
navigator.msSaveBlob(blob, 'FileName.csv');_x000D_
}
_x000D_
In C or C++ local objects are usually allocated on the stack. You are allocating a large array on the stack, more than the stack can handle, so you are getting a stackoverflow.
Don't allocate it local on stack, use some other place instead. This can be achieved by either making the object global or allocating it on the global heap. Global variables are fine, if you don't use the from any other compilation unit. To make sure this doesn't happen by accident, add a static storage specifier, otherwise just use the heap.
This will allocate in the BSS segment, which is a part of the heap:
static int c[1000000];
int main()
{
cout << "done\n";
return 0;
}
This will allocate in the DATA segment, which is a part of the heap too:
int c[1000000] = {};
int main()
{
cout << "done\n";
return 0;
}
This will allocate at some unspecified location in the heap:
int main()
{
int* c = new int[1000000];
cout << "done\n";
return 0;
}
There are obviously plenty of answers, but this one answers it very nicely (with source)
#pragma omp for
only delegates portions of the loop for different threads in the current team. A team is the group of threads executing the program. At program start, the team consists only of a single member: the master thread that runs the program.To create a new team of threads, you need to specify the parallel keyword. It can be specified in the surrounding context:
#pragma omp parallel { #pragma omp for for(int n = 0; n < 10; ++n) printf(" %d", n); }
and:
What are: parallel, for and a team
The difference between parallel, parallel for and for is as follows:
A team is the group of threads that execute currently. At the program beginning, the team consists of a single thread. A parallel construct splits the current thread into a new team of threads for the duration of the next block/statement, after which the team merges back into one. for divides the work of the for-loop among the threads of the current team.
It does not create threads, it only divides the work amongst the threads of the currently executing team. parallel for is a shorthand for two commands at once: parallel and for. Parallel creates a new team, and for splits that team to handle different portions of the loop. If your program never contains a parallel construct, there is never more than one thread; the master thread that starts the program and runs it, as in non-threading programs.
In pre-clean phase I execute with Maven Unlocker program. This program unlock all files and directory for anyone program.
I execute this with maven-antrun-plugin and only in windows systems
<profile>
<activation>
<os>
<family>windows</family>
</os>
</activation>
<build>
<plugins>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.8</version>
<executions>
<execution>
<phase>pre-clean</phase>
<configuration>
<tasks>
<exec dir="${project.build.directory}" executable="cmd" failonerror="false">
<arg value="Unlocker.exe" />
<arg value="/S" />
</exec>
</tasks>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
cellOneOutlet.hidden = true
now override the below method, check which cell status is hidden and return height 0 for those cell(s). This is one of many ways you can hide any cell in static tableView in swift.
override func tableView(tableView: UITableView, heightForRowAtIndexPathindexPath: NSIndexPath) -> CGFloat
{
let tableViewCell = super.tableView(tableView,cellForRowAtIndexPath: indexPath)
if tableViewCell.hidden == true
{
return 0
}
else{
return super.tableView(tableView, heightForRowAtIndexPath: indexPath)
}
}
E.X You can use Singleton for global information that needs to be injected.
In my case, I was keeping the Logged user detail(username, permissions etc.) in Global Static Class. And when I tried to implement the Unit Test, there was no way I could inject dependency into Controller classes. Thus I have changed my Static Class to Singleton pattern.
public class SysManager
{
private static readonly SysManager_instance = new SysManager();
static SysManager() {}
private SysManager(){}
public static SysManager Instance
{
get {return _instance;}
}
}
http://csharpindepth.com/Articles/General/Singleton.aspx#cctor
TortoiseGit has matured and I recommend it especially if you have used TortoiseSVN.
Do you want iteration? itertools.combinations. Common usage:
>>> import itertools
>>> itertools.combinations('abcd',2)
<itertools.combinations object at 0x01348F30>
>>> list(itertools.combinations('abcd',2))
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
>>> [''.join(x) for x in itertools.combinations('abcd',2)]
['ab', 'ac', 'ad', 'bc', 'bd', 'cd']
If you just need to compute the formula, use math.factorial:
import math
def nCr(n,r):
f = math.factorial
return f(n) / f(r) / f(n-r)
if __name__ == '__main__':
print nCr(4,2)
In Python 3, use the integer division //
instead of /
to avoid overflows:
return f(n) // f(r) // f(n-r)
6
You can use flex to achieve this:
.container {
display: flex;
flex-direction: column;
align-items: flex-start;
}
flex-start
will automatically adjust the width of children to their contents.
Maybe this post is too old but it may help as a suggestion for someone looking around on this : Instead of using:
print_r($this->pdo->errorInfo());
Use PHP implode() function:
echo 'Error occurred:'.implode(":",$this->pdo->errorInfo());
This should print the error code, detailed error information etc. that you would usually get if you were using some SQL User interface.
Hope it helps
Interpreted languages like Python and JavaScript benefit greatly from linting, as these languages don’t have a compiling phase to display errors before execution.
Linters are also useful for code formatting and/or adhering to language specific best practices.
Lately I have been using ESLint for JS/React and will occasionally use it with an airbnb-config file.
If you want to reload the page , you can easily go to your component then do :
location.reload();
You can do:
char str[] ="Stackoverflow Serverfault";
char piece1[20] = ""
,piece2[20] = "";
char * p;
p = strtok (str," "); // call the strtok with str as 1st arg for the 1st time.
if (p != NULL) // check if we got a token.
{
strcpy(piece1,p); // save the token.
p = strtok (NULL, " "); // subsequent call should have NULL as 1st arg.
if (p != NULL) // check if we got a token.
strcpy(piece2,p); // save the token.
}
printf("%s :: %s\n",piece1,piece2); // prints Stackoverflow :: Serverfault
If you expect more than one token its better to call the 2nd and subsequent calls to strtok
in a while loop until the return value of strtok
becomes NULL
.
With the Return statement from the proc, I needed to assign the temp variable and pass it to another stored procedure. The value was getting assigned fine but when passing it as a parameter, it lost the value. I had to create a temp table and set the variable from the table (SQL 2008)
From this:
declare @anID int
exec @anID = dbo.StoredProc_Fetch @ID, @anotherID, @finalID
exec dbo.ADifferentStoredProc @anID (no value here)
To this:
declare @t table(id int)
declare @anID int
insert into @t exec dbo.StoredProc_Fetch @ID, @anotherID, @finalID
set @anID= (select Top 1 * from @t)
If you want beautiful and responsive alert dialog then you can use flutter packages like
rflutter alert ,fancy dialog,rich alert,sweet alert dialogs,easy dialog & easy alert
These alerts are good looking and responsive. Among them rflutter alert is the best. currently I am using rflutter alert for my apps.
When your file is created. Instead of creating a file with content is empty. Replace with:
json.dump({}, file)
public static Set<Double> getMode(double[] data) {
if (data.length == 0) {
return new TreeSet<>();
}
TreeMap<Double, Integer> map = new TreeMap<>(); //Map Keys are array values and Map Values are how many times each key appears in the array
for (int index = 0; index != data.length; ++index) {
double value = data[index];
if (!map.containsKey(value)) {
map.put(value, 1); //first time, put one
}
else {
map.put(value, map.get(value) + 1); //seen it again increment count
}
}
Set<Double> modes = new TreeSet<>(); //result set of modes, min to max sorted
int maxCount = 1;
Iterator<Integer> modeApperance = map.values().iterator();
while (modeApperance.hasNext()) {
maxCount = Math.max(maxCount, modeApperance.next()); //go through all the value counts
}
for (double key : map.keySet()) {
if (map.get(key) == maxCount) { //if this key's value is max
modes.add(key); //get it
}
}
return modes;
}
//std dev function for good measure
public static double getStandardDeviation(double[] data) {
final double mean = getMean(data);
double sum = 0;
for (int index = 0; index != data.length; ++index) {
sum += Math.pow(Math.abs(mean - data[index]), 2);
}
return Math.sqrt(sum / data.length);
}
public static double getMean(double[] data) {
if (data.length == 0) {
return 0;
}
double sum = 0.0;
for (int index = 0; index != data.length; ++index) {
sum += data[index];
}
return sum / data.length;
}
//by creating a copy array and sorting it, this function can take any data.
public static double getMedian(double[] data) {
double[] copy = Arrays.copyOf(data, data.length);
Arrays.sort(copy);
return (copy.length % 2 != 0) ? copy[copy.length / 2] : (copy[copy.length / 2] + copy[(copy.length / 2) - 1]) / 2;
}
Create a file called MoveFiles.bat with the syntax
move c:\Sourcefoldernam\*.* e:\destinationFolder
then schedule a task to run that MoveFiles.bat every 10 hours.
As the title says "Best way", I think it's a good idea to consider the patience merge strategy.
From: https://git-scm.com/docs/merge-strategies
With this option, 'merge-recursive' spends a little extra time to avoid mismerges that sometimes occur due to unimportant matching lines (e.g., braces from distinct functions). Use this when the branches to be merged have diverged wildly. See also git-diff[1] --patience.
Usage:
git fetch
git merge -s recursive -X patience origin/master
I use always an alias for this, e.g. run once:
git config --global alias.pmerge 'merge -s recursive -X patience'
Now you could do:
git fetch
git pmerge origin/master
If you are not concerned about old IE browsers, you can also use HTML5 dataset API
HTML
<div id="my-div" data-info="some info here" data-other-info="more info here">My Awesome Div</div>
JS
var myDiv = document.querySelector('#my-div');
myDiv.dataset.info // "some info here"
myDiv.dataset.otherInfo // "more info here"
Demo: http://html5demos.com/dataset
Full browser support list: http://caniuse.com/#feat=dataset
Lets see, numeric (3,2). That means you have 3 places for data and two of them are to the right of the decimal leaving only one to the left of the decimal. 15 has two places to the left of the decimal. BTW if you might have 100 as a value I'd increase that to numeric (5, 2)
You have to use a custom parsing string. I also suggest to include the invariant culture to identify that this format does not relate to any culture. Plus, it will prevent a warning in some code analysis tools.
var date = DateTime.ParseExact(value, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<style type="text/css">
*{
font-family: arial;
font-size: 15px;
}
</style>
</head>
<body>
<button id="more">More</button><br/><br/>
<div>
User Name : <input type="text" class="users"/><br/><br/>
</div>
<button id="btn_data">Send Data</button>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#more').on('click',function(x){
var textMore = "User Name : <input type='text' class='users'/><br/><br/>";
$("div").append(textMore);
});
$('#btn_data').on('click',function(x){
var users=$(".users");
$(users).each(function(i, e) {
console.log($(e).val());
});
})
});
</script>
</body>
</html>
You can override the constructor for the ActiveRecord model.
Like this:
def initialize(*args)
super(*args)
self.attribute_that_needs_default_value ||= default_value
self.attribute_that_needs_another_default_value ||= another_default_value
#ad nauseum
end
In my case this exception was caused by jupiter
implementation 'org.junit.jupiter:junit-jupiter:5.6.2'
Added v4.8 support to the script:
Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -recurse |
Get-ItemProperty -name Version,Release -EA 0 |
Where { $_.PSChildName -match '^(?![SW])\p{L}'} |
Select PSChildName, Version, Release, @{
name="Product"
expression={
switch -regex ($_.Release) {
"378389" { [Version]"4.5" }
"378675|378758" { [Version]"4.5.1" }
"379893" { [Version]"4.5.2" }
"393295|393297" { [Version]"4.6" }
"394254|394271" { [Version]"4.6.1" }
"394802|394806" { [Version]"4.6.2" }
"460798|460805" { [Version]"4.7" }
"461308|461310" { [Version]"4.7.1" }
"461808|461814" { [Version]"4.7.2" }
"528040|528049" { [Version]"4.8" }
{$_ -gt 528049} { [Version]"Undocumented version (> 4.8), please update script" }
}
}
}
use JsonParser; for example:
JsonParser parser = new JsonParser();
JsonObject o = parser.parse("{\"a\": \"A\"}").getAsJsonObject();
I faced this problem today and I was able to solve it using this Gradle plugin
It's github url is this
IF you, like me, have no idea what Gradle is but need to run a backend to do your front end work, what you need to do is find the build.gradle file that is being called to start your BE server and add this to the top:
plugins {
id "ua.eshepelyuk.ManifestClasspath" version "1.0.0"
}
Another MySQL option that may look more like Oracle's DECODE
is a combination of FIELD
and ELT
. In the code that follows, FIELD()
returns the argument list position of the string that matches Age. ELT()
returns the string from ELT
s argument list at the position provided by FIELD()
. For example, if Age
is 14
, FIELD(Age, ...)
returns 2
because 14
is the 2nd argument of FIELD
(not counting Age
). Then, ELT(2, ...)
returns 'Fourteen'
, which is the 2nd argument of ELT
(not counting the FIELD()
argument). IFNULL
returns the default AgeBracket
if no match to Age
is found in the list.
Select Name, IFNULL(ELT(FIELD(Age,
13, 14, 15, 16, 17, 18, 19),'Thirteen','Fourteen','Fifteen','Sixteen',
'Seventeen','Eighteen','Nineteen'),
'Adult') AS AgeBracket
FROM Person
While I don't think this is the best solution to the question either in terms of performance or readability it is interesting as an exploration of MySQL's string functions. Keep in mind that FIELD
's output does not seem to be case sensitive. I.e., FIELD('A','A')
and FIELD('a','A')
both return 1
.
Well, at the risk of making things too easy...
for (var member in myObject) delete myObject[member];
...would seem to be pretty effective in cleaning the object in one line of code with a minimum of scary brackets. All members will be truly deleted instead of left as garbage.
Obviously if you want to delete the object itself, you'll still have to do a separate delete() for that.
It's like whisky and scotch, all web apps are web site, but not all web sites are web app.
A web application or Rich Internet Applications is a web site that does more than displaying content, it has a business logic. It’s intended for user interactions, performing actual business functions. Compared to web sites, i.e. blogs and news sites, web apps provide a richer user experience.
The use case of an application is always to DO something with it
— Christian Heilmann (Principal Developer Evangelist at Mozilla Corporation)
Personally I would use d3-dsv library to do this. Why to reinvent the wheel
?
import { csvFormat } from 'd3-dsv';
/**
* Based on input data convert it to csv formatted string
* @param (Array) columnsToBeIncluded array of column names (strings)
* which needs to be included in the formated csv
* @param {Array} input array of object which need to be transformed to string
*/
export function convertDataToCSVFormatString(input, columnsToBeIncluded = []) {
if (columnsToBeIncluded.length === 0) {
return csvFormat(input);
}
return csvFormat(input, columnsToBeIncluded);
}
With tree-shaking you can just import that particular function from d3-dsv
library
If you find yourself in a situation where the FK name of a table has been auto-generated and you aren't able to view what it exactly is (in the case of not having rights to a database for instance) you could try something like this:
DECLARE @table NVARCHAR(512), @sql NVARCHAR(MAX);
SELECT @table = N'dbo.Table';
SELECT @sql = 'ALTER TABLE ' + @table
+ ' DROP CONSTRAINT ' + NAME + ';'
FROM sys.foreign_keys
WHERE [type] = 'F'
AND [parent_object_id] = OBJECT_ID(@table);
EXEC sp_executeSQL @sql;
Build up a stored proc which drops the constraint of the specified table without specifying the actual FK name. It drops the constraint where the object [type]
is equal to F (Foreign Key constraint).
Note: if there are multiple FK's in the table it will drop them all. So this solution works best if the table you are targeting has just one FK.
If you're in charge (or have any control over the web service), get them to add a unique root element!
If you can't change that at all, then you can do a bit of regex or string-splitting to parse each and pass each element to your XML Reader.
Alternatively, you could manually add a junk root element, by prefixing an opening tag and suffixing a closing tag.
I had a similar problem with a nested dictionary with some numpy.ndarrays in it.
def jsonify(data):
json_data = dict()
for key, value in data.iteritems():
if isinstance(value, list): # for lists
value = [ jsonify(item) if isinstance(item, dict) else item for item in value ]
if isinstance(value, dict): # for nested lists
value = jsonify(value)
if isinstance(key, int): # if key is integer: > to string
key = str(key)
if type(value).__module__=='numpy': # if value is numpy.*: > to python list
value = value.tolist()
json_data[key] = value
return json_data
There's probably a another way or better. But this is how I do this in Spring Boot.
My property file contains the following lines. "," is the delimiter in each line.
mml.pots=STDEP:DETY=LI3;,STDEP:DETY=LIMA;
mml.isdn.grunntengingar=STDEP:DETY=LIBAE;,STDEP:DETY=LIBAMA;
mml.isdn.stofntengingar=STDEP:DETY=LIPRAE;,STDEP:DETY=LIPRAM;,STDEP:DETY=LIPRAGS;,STDEP:DETY=LIPRVGS;
My server config
@Configuration
public class ServerConfig {
@Inject
private Environment env;
@Bean
public MMLProperties mmlProperties() {
MMLProperties properties = new MMLProperties();
properties.setMmmlPots(env.getProperty("mml.pots"));
properties.setMmmlPots(env.getProperty("mml.isdn.grunntengingar"));
properties.setMmmlPots(env.getProperty("mml.isdn.stofntengingar"));
return properties;
}
}
MMLProperties class.
public class MMLProperties {
private String mmlPots;
private String mmlIsdnGrunntengingar;
private String mmlIsdnStofntengingar;
public MMLProperties() {
super();
}
public void setMmmlPots(String mmlPots) {
this.mmlPots = mmlPots;
}
public void setMmlIsdnGrunntengingar(String mmlIsdnGrunntengingar) {
this.mmlIsdnGrunntengingar = mmlIsdnGrunntengingar;
}
public void setMmlIsdnStofntengingar(String mmlIsdnStofntengingar) {
this.mmlIsdnStofntengingar = mmlIsdnStofntengingar;
}
// These three public getXXX functions then take care of spliting the properties into List
public List<String> getMmmlCommandForPotsAsList() {
return getPropertieAsList(mmlPots);
}
public List<String> getMmlCommandsForIsdnGrunntengingarAsList() {
return getPropertieAsList(mmlIsdnGrunntengingar);
}
public List<String> getMmlCommandsForIsdnStofntengingarAsList() {
return getPropertieAsList(mmlIsdnStofntengingar);
}
private List<String> getPropertieAsList(String propertie) {
return ((propertie != null) || (propertie.length() > 0))
? Arrays.asList(propertie.split("\\s*,\\s*"))
: Collections.emptyList();
}
}
Then in my Runner class I Autowire MMLProperties
@Component
public class Runner implements CommandLineRunner {
@Autowired
MMLProperties mmlProperties;
@Override
public void run(String... arg0) throws Exception {
// Now I can call my getXXX function to retrieve the properties as List
for (String command : mmlProperties.getMmmlCommandForPotsAsList()) {
System.out.println(command);
}
}
}
Hope this helps
It only worked with me when I "flushed" after the commands mentioned here. Here's the full list of commands I used:
Previous answers might not work for later mysql versions. Try these steps if previous answers did not work for you:
1- Click on the wamp icon > mysql > mysql console
2- write following commands, one by one
use mysql;
update user set authentication_string=password('your_password') where user='root';
FLUSH PRIVILEGES;
quit
I wouldn't bother looking for ASP.NET stuff specifically (probably won't find any anyways). Finding a good CSS theme easily can be used in ASP.NET.
Here's some sites that I love for CSS goodness:
http://www.freecsstemplates.org/
http://www.oswd.org/
http://www.openwebdesign.org/
http://www.styleshout.com/
http://www.freelayouts.com/
In my experience
document.getElementById(frmObj.id).focus();
is good on a browser running on a PC. But on mobile if you want the keyboard to show up so the user can input directly then you also need:
document.getElementById(frmObj.id).select();
Try with this piece of code.
.ui-datepicker{ z-index:1151 !important; }
will solve the problem when you are using bootstrap V3
I was having the same issue, and I found out what was wrong. I had the HTML defined as
<form action="url" method="post">
<input type="hidden" id="email" />
<form>
<script>
function onsomeevent()
{
$("#email").val("[email protected]");
}
</script>
Reading the form values on server always resulted in email as empty. After scratching my head (and numerous search), I realized the mistake was not defining the form/input correctly. On modifing the input (as shown next), it worked like a charm
<input type="hidden" id="email" name="email" />
Adding to this thread in case others have the same issue.
Slightly more condensed than gbn's:
Assuming CourseId
is non-zero
CAST (COALESCE(FC.CourseId, 0) AS Bit)
COALESCE
is like an ISNULL()
, but returns the first non-Null.
A Non-Zero CourseId
will get type-cast to a 1, while a null CourseId
will cause COALESCE to return the next value, 0
Try this to redirect cout to file.
#include <iostream>
#include <fstream>
int main()
{
/** backup cout buffer and redirect to out.txt **/
std::ofstream out("out.txt");
auto *coutbuf = std::cout.rdbuf();
std::cout.rdbuf(out.rdbuf());
std::cout << "This will be redirected to file out.txt" << std::endl;
/** reset cout buffer **/
std::cout.rdbuf(coutbuf);
std::cout << "This will be printed on console" << std::endl;
return 0;
}
Read full article Use std::rdbuf to Redirect cin and cout
I would recommend using INSERT...ON DUPLICATE KEY UPDATE
.
If you use INSERT IGNORE
, then the row won't actually be inserted if it results in a duplicate key. But the statement won't generate an error. It generates a warning instead. These cases include:
PRIMARY KEY
or UNIQUE
constraints. NOT NULL
constraint.If you use REPLACE
, MySQL actually does a DELETE
followed by an INSERT
internally, which has some unexpected side effects:
REPLACE
.DELETE
are executed unnecessarily.correction: both REPLACE
and INSERT...ON DUPLICATE KEY UPDATE
are non-standard, proprietary inventions specific to MySQL. ANSI SQL 2003 defines a MERGE
statement that can solve the same need (and more), but MySQL does not support the MERGE
statement.
A user tried to edit this post (the edit was rejected by moderators). The edit tried to add a claim that INSERT...ON DUPLICATE KEY UPDATE
causes a new auto-increment id to be allocated. It's true that the new id is generated, but it is not used in the changed row.
See demonstration below, tested with Percona Server 5.5.28. The configuration variable innodb_autoinc_lock_mode=1
(the default):
mysql> create table foo (id serial primary key, u int, unique key (u));
mysql> insert into foo (u) values (10);
mysql> select * from foo;
+----+------+
| id | u |
+----+------+
| 1 | 10 |
+----+------+
mysql> show create table foo\G
CREATE TABLE `foo` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`u` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `u` (`u`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1
mysql> insert into foo (u) values (10) on duplicate key update u = 20;
mysql> select * from foo;
+----+------+
| id | u |
+----+------+
| 1 | 20 |
+----+------+
mysql> show create table foo\G
CREATE TABLE `foo` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`u` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `u` (`u`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1
The above demonstrates that the IODKU statement detects the duplicate, and invokes the update to change the value of u
. Note the AUTO_INCREMENT=3
indicates an id was generated, but not used in the row.
Whereas REPLACE
does delete the original row and inserts a new row, generating and storing a new auto-increment id:
mysql> select * from foo;
+----+------+
| id | u |
+----+------+
| 1 | 20 |
+----+------+
mysql> replace into foo (u) values (20);
mysql> select * from foo;
+----+------+
| id | u |
+----+------+
| 3 | 20 |
+----+------+
Either call cancel()
on the Timer
if that's all it's doing, or cancel()
on the TimerTask
if the timer itself has other tasks which you wish to continue.
Use below regular expression
^[_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+)+((\.)[a-z]{2,})+$
It allows
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
Anson's answer will work fine for the simple case, but if you're going to do any more complex date calculations I'd recommend checking out Joda Time. It will make your life much easier.
FYI in Joda Time you could do
DateTime dt = new DateTime();
DateTime fiveDaysEarlier = dt.minusDays(5);
As far as I know, it's the main entry point to your node package (library) for npm. It's needed if your npm project becomes a node package (library) which can be installed via npm by others.
Let's say you have a library with a build/, dist/, or lib/ folder. In this folder, you got the following compiled file for your library:
-lib/
--bundle.js
Then in your package.json, you tell npm how to access the library (node package):
{
"name": "my-library-name",
"main": "lib/bundle.js",
...
}
After installing the node package with npm to your JS project, you can import functionalities from your bundled bundle.js file:
import { add, subtract } from 'my-library-name';
This holds also true when using Code Splitting (e.g. Webpack) for your library. For instance, this webpack.config.js makes use of code splitting the project into multiple bundles instead of one.
module.exports = {
entry: {
main: './src/index.js',
add: './src/add.js',
subtract: './src/subtract.js',
},
output: {
path: `${__dirname}/lib`,
filename: '[name].js',
library: 'my-library-name',
libraryTarget: 'umd',
},
...
}
Still, you would define one main entry point to your library in your package.json:
{
"name": "my-library-name",
"main": "lib/main.js",
...
}
Then when using the library, you can import your files from your main entry point:
import { add, subtract } from 'my-library-name';
However, you can also bypass the main entry point from the package.json and import the code splitted bundles:
import add from 'my-library-name/lib/add';
import subtract from 'my-library-name/lib/subtract';
After all, the main property in your package.json only points to your main entry point file of your library.
You can use tandem of MemoryStream
and StreamReader
classes:
void Main()
{
string myString;
using (var stream = new MemoryStream())
{
Print(stream);
stream.Position = 0;
using (var reader = new StreamReader(stream))
{
myString = reader.ReadToEnd();
}
}
}
First install "Microsoft ASP.NET Web API Client" nuget package:
PM > Install-Package Microsoft.AspNet.WebApi.Client
Then use the following function to post your data:
public static async Task<TResult> PostFormUrlEncoded<TResult>(string url, IEnumerable<KeyValuePair<string, string>> postData)
{
using (var httpClient = new HttpClient())
{
using (var content = new FormUrlEncodedContent(postData))
{
content.Headers.Clear();
content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
HttpResponseMessage response = await httpClient.PostAsync(url, content);
return await response.Content.ReadAsAsync<TResult>();
}
}
}
And this is how to use it:
TokenResponse tokenResponse =
await PostFormUrlEncoded<TokenResponse>(OAuth2Url, OAuth2PostData);
or
TokenResponse tokenResponse =
(Task.Run(async ()
=> await PostFormUrlEncoded<TokenResponse>(OAuth2Url, OAuth2PostData)))
.Result
or (not recommended)
TokenResponse tokenResponse =
PostFormUrlEncoded<TokenResponse>(OAuth2Url, OAuth2PostData).Result;
Position Relative:
If you specify position:relative, then you can use top or bottom, and left or right to move the element relative to where it would normally occur in the document.
Position Absolute:
When you specify position:absolute, the element is removed from the document and placed exactly where you tell it to go.
Here is a good tutorial http://www.barelyfitz.com/screencast/html-training/css/positioning/ with the sample usage of both position with respective to absolute and relative positioning.
If you're interested in realtime plotting, I'd recommend looking into matplotlib's animation API. In particular, using blit
to avoid redrawing the background on every frame can give you substantial speed gains (~10x):
#!/usr/bin/env python
import numpy as np
import time
import matplotlib
matplotlib.use('GTKAgg')
from matplotlib import pyplot as plt
def randomwalk(dims=(256, 256), n=20, sigma=5, alpha=0.95, seed=1):
""" A simple random walk with memory """
r, c = dims
gen = np.random.RandomState(seed)
pos = gen.rand(2, n) * ((r,), (c,))
old_delta = gen.randn(2, n) * sigma
while True:
delta = (1. - alpha) * gen.randn(2, n) * sigma + alpha * old_delta
pos += delta
for ii in xrange(n):
if not (0. <= pos[0, ii] < r):
pos[0, ii] = abs(pos[0, ii] % r)
if not (0. <= pos[1, ii] < c):
pos[1, ii] = abs(pos[1, ii] % c)
old_delta = delta
yield pos
def run(niter=1000, doblit=True):
"""
Display the simulation using matplotlib, optionally using blit for speed
"""
fig, ax = plt.subplots(1, 1)
ax.set_aspect('equal')
ax.set_xlim(0, 255)
ax.set_ylim(0, 255)
ax.hold(True)
rw = randomwalk()
x, y = rw.next()
plt.show(False)
plt.draw()
if doblit:
# cache the background
background = fig.canvas.copy_from_bbox(ax.bbox)
points = ax.plot(x, y, 'o')[0]
tic = time.time()
for ii in xrange(niter):
# update the xy data
x, y = rw.next()
points.set_data(x, y)
if doblit:
# restore background
fig.canvas.restore_region(background)
# redraw just the points
ax.draw_artist(points)
# fill in the axes rectangle
fig.canvas.blit(ax.bbox)
else:
# redraw everything
fig.canvas.draw()
plt.close(fig)
print "Blit = %s, average FPS: %.2f" % (
str(doblit), niter / (time.time() - tic))
if __name__ == '__main__':
run(doblit=False)
run(doblit=True)
Output:
Blit = False, average FPS: 54.37
Blit = True, average FPS: 438.27
There is a condition that most of these solutions do not address. I revised Patrick Honorez's solution to handle it. I felt I had to share this because I was pulling my hair out when the original function was occasionally clearing more data that I expected.
The situation happens when the table only has one column and the .SpecialCells(xlCellTypeConstants).ClearContents
attempts to clear the contents of the top row. In this situation, only one cell is selected (the top row of the table that only has one column) and the SpecialCells command applies to the entire sheet instead of the selected range. What was happening to me was other cells on the sheet that were outside of my table were also getting cleared.
I did some digging and found this advice from Mathieu Guindon: Range SpecialCells ClearContents clears whole sheet
Range({any single cell}).SpecialCells({whatever}) seems to work off the entire sheet.
Range({more than one cell}).SpecialCells({whatever}) seems to work off the specified cells.
If the list/table only has one column (in row 1), this revision will check to see if the cell has a formula and if not, it will only clear the contents of that one cell.
Public Sub ClearList(lst As ListObject)
'Clears a listObject while leaving 1 empty row + formula
' https://stackoverflow.com/a/53856079/1898524
'
'With special help from this post to handle a single column table.
' Range({any single cell}).SpecialCells({whatever}) seems to work off the entire sheet.
' Range({more than one cell}).SpecialCells({whatever}) seems to work off the specified cells.
' https://stackoverflow.com/questions/40537537/range-specialcells-clearcontents-clears-whole-sheet-instead
On Error Resume Next
With lst
'.Range.Worksheet.Activate ' Enable this if you are debugging
If .ShowAutoFilter Then .AutoFilter.ShowAllData
If .DataBodyRange.Rows.Count = 1 Then Exit Sub ' Table is already clear
.DataBodyRange.Offset(1).Rows.Clear
If .DataBodyRange.Columns.Count > 1 Then ' Check to see if SpecialCells is going to evaluate just one cell.
.DataBodyRange.Rows(1).SpecialCells(xlCellTypeConstants).ClearContents
ElseIf Not .Range.HasFormula Then
' Only one cell in range and it does not contain a formula.
.DataBodyRange.Rows(1).ClearContents
End If
.Resize .Range.Rows("1:2")
.HeaderRowRange.Offset(1).Select
' Reset used range on the sheet
Dim X
X = .Range.Worksheet.UsedRange.Rows.Count 'see J-Walkenbach tip 73
End With
End Sub
A final step I included is a tip that is attributed to John Walkenbach, sometimes noted as J-Walkenbach tip 73
Automatically Resetting The Last Cell
@RequestBody : Annotation indicating a method parameter should be bound to the body of the HTTP request.
For example:
@RequestMapping(path = "/something", method = RequestMethod.PUT)
public void handle(@RequestBody String body, Writer writer) throws IOException {
writer.write(body);
}
@ResponseBody annotation can be put on a method and indicates that the return type should be written straight to the HTTP response body (and not placed in a Model, or interpreted as a view name).
For example:
@RequestMapping(path = "/something", method = RequestMethod.PUT)
public @ResponseBody String helloWorld() {
return "Hello World";
}
Alternatively, we can use @RestController annotation in place of @Controller
annotation. This will remove the need to using @ResponseBody
.
s1.equalsIgnoreCase(s2)
: (see javadoc) s1.equals(s2)
Here is a slight improvement on the this answer above taking care of both .xlsx and .xls files in the same routine, in case it helps someone!
I also add a line to choose to save with the active sheet name instead of the workbook, which is most practical for me often:
Sub ExportAsCSV()
Dim MyFileName As String
Dim CurrentWB As Workbook, TempWB As Workbook
Set CurrentWB = ActiveWorkbook
ActiveWorkbook.ActiveSheet.UsedRange.Copy
Set TempWB = Application.Workbooks.Add(1)
With TempWB.Sheets(1).Range("A1")
.PasteSpecial xlPasteValues
.PasteSpecial xlPasteFormats
End With
MyFileName = CurrentWB.Path & "\" & Left(CurrentWB.Name, InStrRev(CurrentWB.Name, ".") - 1) & ".csv"
'Optionally, comment previous line and uncomment next one to save as the current sheet name
'MyFileName = CurrentWB.Path & "\" & CurrentWB.ActiveSheet.Name & ".csv"
Application.DisplayAlerts = False
TempWB.SaveAs Filename:=MyFileName, FileFormat:=xlCSV, CreateBackup:=False, Local:=True
TempWB.Close SaveChanges:=False
Application.DisplayAlerts = True
End Sub
Like Apache, this is a quick edit to the source and recompile. From Calomel.org:
The Server: string is the header which is sent back to the client to tell them what type of http server you are running and possibly what version. This string is used by places like Alexia and Netcraft to collect statistics about how many and of what type of web server are live on the Internet. To support the author and statistics for Nginx we recommend keeping this string as is. But, for security you may not want people to know what you are running and you can change this in the source code. Edit the source file
src/http/ngx_http_header_filter_module.c
at look at lines 48 and 49. You can change the String to anything you want.
## vi src/http/ngx_http_header_filter_module.c (lines 48 and 49)
static char ngx_http_server_string[] = "Server: MyDomain.com" CRLF;
static char ngx_http_server_full_string[] = "Server: MyDomain.com" CRLF;
March 2011 edit: Props to Flavius below for pointing out a new option, replacing Nginx's standard HttpHeadersModule with the forked HttpHeadersMoreModule. Recompiling the standard module is still the quick fix, and makes sense if you want to use the standard module and won't be changing the server string often. But if you want more than that, the HttpHeadersMoreModule is a strong project and lets you do all sorts of runtime black magic with your HTTP headers.
By default the static data, when you install the nginx, will be in /var/www/html. So you can just copy your static folder into /var/html/ and set the
root /var/www/<your static folder>
in ngix.conf (or /etc/nginx/sites-available/default)
This worked for me on ubuntu but I guess it should not be much different for other distros.
Hope it helps.
Since mysql_connect
has been deprecated, connect and query instead with mysqli:
$mysqli = new mysqli("hostname","username","password","database_name");
$sqlSelect="SELECT your_fieldname FROM your_table";
$result = $mysqli -> query ($sqlSelect);
And then, if you have more than one option list with the same values on the same page, put the values in an array:
while ($row = mysqli_fetch_array($result)) {
$rows[] = $row;
}
And then you can loop the array multiple times on the same page:
foreach ($rows as $row) {
print "<option value='" . $row['your_fieldname'] . "'>" . $row['your_fieldname'] . "</option>";
}
To find a very long list of words in big files, it can be more efficient to use egrep:
remove the last \n of A
$ tr '\n' '|' < A > A_regex
$ egrep -f A_regex B
To simple clear everything do:
$ docker system prune --all
Everything means:
- all stopped containers
- all networks not used by at least one container
- all images without at least one container associated to them
- all build cache
You need to remove the static
from your accessor methods - these methods need to be instance methods and access the instance variables
public class IDCard {
public String name, fileName;
public int id;
public IDCard(final String name, final String fileName, final int id) {
this.name = name;
this.fileName = fileName
this.id = id;
}
public String getName() {
return name;
}
}
You can the create an IDCard
and use the accessor like this:
final IDCard card = new IDCard();
card.getName();
Each time you call new
a new instance of the IDCard
will be created and it will have it's own copies of the 3 variables.
If you use the static
keyword then those variables are common across every instance of IDCard
.
A couple of things to bear in mind:
name
not Name
.subprocess.Popen
takes a cwd
argument to set the Current Working Directory; you'll also want to escape your backslashes ('d:\\test\\local'
), or use r'd:\test\local'
so that the backslashes aren't interpreted as escape sequences by Python. The way you have it written, the \t
part will be translated to a tab.
So, your new line should look like:
subprocess.Popen(r'c:\mytool\tool.exe', cwd=r'd:\test\local')
To use your Python script path as cwd, import os
and define cwd using this:
os.path.dirname(os.path.realpath(__file__))
You aren't creating any buttons, you just have an empty list.
You can forget the list and just create the buttons in the loop.
private void button1_Click(object sender, EventArgs e)
{
int top = 50;
int left = 100;
for (int i = 0; i < 10; i++)
{
Button button = new Button();
button.Left = left;
button.Top = top;
this.Controls.Add(button);
top += button.Height + 2;
}
}
Please try the below Code
You can split the controller (PageCtrl) and service (dataService)
'use strict';_x000D_
(function () {_x000D_
angular.module('myApp')_x000D_
.controller('pageContl', ['$scope', 'dataService', PageContl])_x000D_
.service('dataService', ['$q', '$http', DataService]);_x000D_
function DataService($q, $http){_x000D_
this.$q = $q;_x000D_
this.$http = $http;_x000D_
//... blob blob _x000D_
}_x000D_
DataService.prototype = {_x000D_
getSearchData: function () {_x000D_
var deferred = this.$q.defer(); //initiating promise_x000D_
this.$http({_x000D_
method: 'POST',//GET_x000D_
url: 'test.json',_x000D_
headers: { 'Content-Type': 'application/json' }_x000D_
}).then(function(result) {_x000D_
deferred.resolve(result.data);_x000D_
},function (error) {_x000D_
deferred.reject(error);_x000D_
});_x000D_
return deferred.promise;_x000D_
},_x000D_
getABCDATA: function () {_x000D_
_x000D_
}_x000D_
};_x000D_
function PageContl($scope, dataService) {_x000D_
this.$scope = $scope;_x000D_
this.dataService = dataService; //injecting service Dependency in ctrl_x000D_
this.pageData = {}; //or [];_x000D_
}_x000D_
PageContl.prototype = {_x000D_
searchData: function () {_x000D_
var self = this; //we can't access 'this' of parent fn from callback or inner function, that's why assigning in temp variable_x000D_
this.dataService.getSearchData().then(function (data) {_x000D_
self.searchData = data;_x000D_
});_x000D_
}_x000D_
}_x000D_
}());
_x000D_
object-fit: cover
will do exactly what you need.
But it might not work on IE/Edge. Follow as shown below to fix it with just CSS to work on all browsers.
The approach I took was to position the image inside the container with absolute and then place it right at the centre using the combination:
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
Once it is in the centre, I give to the image,
// For vertical blocks (i.e., where height is greater than width)
height: 100%;
width: auto;
// For Horizontal blocks (i.e., where width is greater than height)
height: auto;
width: 100%;
This makes the image get the effect of Object-fit:cover.
https://jsfiddle.net/furqan_694/s3xLe1gp/
This logic works in all browsers.
ROUND(number, decimals, operation)
number => Required. The number to be rounded
decimals => Required. The number of decimal places to round number to
operation => Optional. If 0, it rounds the result to the number of decimal. If another value than 0, it truncates the result to the number of decimals. Default value is 0
SELECT ROUND(235.415, 2, 1)
will give you 235.410
SELECT ROUND(235.415, 0, 1)
will give you 235.000
But now trimming0
you can use cast
SELECT CAST(ROUND(235.415, 0, 1) AS INT)
will give you 235
A big thank you to @Musa and here is a neat function that converts the data to a base64 string. This may come handy to you when handling a binary file (pdf, png, jpeg, docx, ...) file in a WebView that gets the binary file but you need to transfer the file's data safely into your app.
// runs a get/post on url with post variables, where:
// url ... your url
// post ... {'key1':'value1', 'key2':'value2', ...}
// set to null if you need a GET instead of POST req
// done ... function(t) called when request returns
function getFile(url, post, done)
{
var postEnc, method;
if (post == null)
{
postEnc = '';
method = 'GET';
}
else
{
method = 'POST';
postEnc = new FormData();
for(var i in post)
postEnc.append(i, post[i]);
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200)
{
var res = this.response;
var reader = new window.FileReader();
reader.readAsDataURL(res);
reader.onloadend = function() { done(reader.result.split('base64,')[1]); }
}
}
xhr.open(method, url);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send('fname=Henry&lname=Ford');
xhr.responseType = 'blob';
xhr.send(postEnc);
}
I have this version about datetimepicker https://tempusdominus.github.io/bootstrap-4/ and for any reason doesn`t work the change event with jquery but with JS vanilla it does
I figure out like this
document.getElementById('date').onchange = function(){ ...the jquery code...}
I hope work for you
you can make use of the below code for sorting in descending order and storing to a dictionary:
listname = []
for key, value in sorted(dictionaryName.iteritems(), key=lambda (k,v): (v,k),reverse=True):
diction= {"value":value, "key":key}
listname.append(diction)
Instead of setting the @JsonSerialize on each member or getter you can configure a module that use a custome serializer for a certain type:
SimpleModule module = new SimpleModule();
module.addSerializer(BigInteger.class, new ToStringSerializer());
objectMapper.registerModule(module);
In the above example, I used the to string serializer to serialize BigIntegers (since javascript can not handle such numeric values).
Was following one of training with Spring webmvc 4.2.3, while I'm using Spring webmvc 5.2.3 they suggested to create a form
<form:form modelAttribute="aNewAccount" method="get" action="/accountCreated">
that was causing the "disclose" error.
Altered as below to make it work. Looks like method above was the culprit.
<form:form modelAttribute="aNewAccount" action="accountCreated.html">
in fact, exploring further, method="post" in form annotation would work if properly declared:
@RequestMapping(value="/accountCreated", method=RequestMethod.POST)
Assuming you do not have local commits,
git diff origin/master
A bit long winded but it works for me: try this::
=SUM(IF(OR(ISBLANK(AU2), NOT(ISERR(YEAR(AU2)))),0,1)
+IF(OR(ISBLANK(AV2), NOT(ISERR(YEAR(AV2)))),0,1))
first part of if will allow cell to be blank or if there is something in the cell it tries to convert to a year, if there is an error or there is something other than a date result = 1, do the same for each cell and sum the result
Just try this code this code work with me
var posOptions = {timeout: 10000, enableHighAccuracy: false};
$cordovaGeolocation.getCurrentPosition(posOptions).then(function (position) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
//console.log(lat +" "+long);
$http.get('https://maps.googleapis.com/maps/api/geocode/json?latlng=' + lat + ',' + long + '&key=your key here').success(function (output) {
//console.log( JSON.stringify(output.results[0]));
//console.log( JSON.stringify(output.results[0].address_components[4].short_name));
var results = output.results;
if (results[0]) {
//console.log("results.length= "+results.length);
//console.log("hi "+JSON.stringify(results[0],null,4));
for (var j = 0; j < results.length; j++){
//console.log("j= "+j);
//console.log(JSON.stringify(results[j],null,4));
for (var i = 0; i < results[j].address_components.length; i++){
if(results[j].address_components[i].types[0] == "country") {
//this is the object you are looking for
country = results[j].address_components[i];
}
}
}
console.log(country.long_name);
console.log(country.short_name);
} else {
alert("No results found");
console.log("No results found");
}
});
}, function (err) {
});
Most updated:
$product->get_attribute( 'your_attr' );
You will need to define $product
if it's not on the page.
I have encountered this one too and this is my solution.
If you are encountering an invalid json object exception when parsing data, even though you know that your json string is correct, stringify the data you received in your ajax code before parsing it to JSON:
$.post(CONTEXT+"servlet/capture",{
yesTransactionId : yesTransactionId,
productOfferId : productOfferId
},
function(data){
try{
var trimData = $.trim(JSON.stringify(data));
var obj = $.parseJSON(trimData);
if(obj.success == 'true'){
//some codes ...
Using newInstance
public static MyDialogFragment newInstance(int num) {
MyDialogFragment f = new MyDialogFragment();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putInt("num", num);
f.setArguments(args);
return f;
}
And get the Args like this
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNum = getArguments().getInt("num");
...
}
See the full example here
http://developer.android.com/reference/android/app/DialogFragment.html
new[,2]
is a factor, not a numeric vector. Transform it first
new$MY_NEW_COLUMN <-as.numeric(as.character(new[,2])) * 5
If you are looking for a brand new pull from another branch like from local to master you can follow this.
git commit -m "Initial Commit"
git add .
git pull --rebase git_url
git push origin master
For anyone using Koa and koa-passport:
Know that the key for the user set in the serializeUser method (often a unique id for that user) will be stored in:
this.session.passport.user
When you set in done(null, user)
in deserializeUser where 'user' is some user object from your database:
this.req.user
OR
this.passport.user
for some reason this.user
Koa context never gets set when you call done(null, user) in your deserializeUser method.
So you can write your own middleware after the call to app.use(passport.session()) to put it in this.user like so:
app.use(function * setUserInContext (next) {
this.user = this.req.user
yield next
})
If you're unclear on how serializeUser and deserializeUser work, just hit me up on twitter. @yvanscher
jQuery code snippet to get the dynamic variables stored in the url as parameters and store them as JavaScript variables ready for use with your scripts:
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results==null) {
return null;
}
return decodeURI(results[1]) || 0;
}
example.com?param1=name¶m2=&id=6
$.urlParam('param1'); // name
$.urlParam('id'); // 6
$.urlParam('param2'); // null
example params with spaces
http://www.jquery4u.com?city=Gold Coast
console.log($.urlParam('city'));
//output: Gold%20Coast
console.log(decodeURIComponent($.urlParam('city')));
//output: Gold Coast
In my case I was migrating from 9.5 to 9.6. So to restore a database, I was doing :
sudo -u postgres psql -d databse -f dump.sql
Of course it was executing on the old postgreSQL database where there are datas! If your new instance is on port 5433, the correct way is :
sudo -u postgres psql -d databse -f dump.sql -p 5433
On Ubuntu until python-distribute is something newer than 0.7 I'd recommend:
$ wget https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py -O - | sudo python
See http://reinout.vanrees.org/weblog/2013/07/08/new-setuptools-buildout.html
$('.IsBestAnswer').removeClass('IsBestAnswer').addClass('bestanswer');
Your code has two problems:
.IsBestAnswe
does not match what you thoughtaddClass()
, not addclass()
.Also, I'm not sure whether you want to replace the class or add it. The above will replace, but remove the .removeClass('IsBestAnswer')
part to add only:
$('.IsBestAnswer').addClass('bestanswer');
You should decide whether to use camelCase or all-lowercase in your CSS classes too (e.g. bestAnswer
vs. bestanswer
).
Use this
data: '{"username":"' + username + '"}',
I try a lot of syntax to work with laravel it work for me for laravel 4.2 + ajax.
By either escaping those characters with htmlspecialchars
, or, perhaps more appropriately, using a library for building XML documents, such as DOMDocument or XMLWriter.
Another alternative would be to use CDATA sections, but then you'd have to look out for occurrences of ]]>
.
Take also into consideration that that you must respect the encoding you define for the XML document (by default UTF-8).
ssh user@machine python < script.py - arg1 arg2
Because cat |
is usually not necessary
Based on Haim's answer I created a PHP code to test and display all the differences between two databases. This will also display if a table is present in source or test databases. You have to change with your details the <> variables content.
<?php
$User = "<DatabaseUser>";
$Pass = "<DatabasePassword>";
$SourceDB = "<SourceDatabase>";
$TestDB = "<DatabaseToTest>";
$link = new mysqli( "p:". "localhost", $User, $Pass, "" );
if ( mysqli_connect_error() ) {
die('Connect Error ('. mysqli_connect_errno() .') '. mysqli_connect_error());
}
mysqli_set_charset( $link, "utf8" );
mb_language( "uni" );
mb_internal_encoding( "UTF-8" );
$sQuery = 'SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA="'. $SourceDB .'";';
$SourceDB_Content = query( $link, $sQuery );
if ( !is_array( $SourceDB_Content) ) {
echo "Table $SourceDB cannot be accessed";
exit(0);
}
$sQuery = 'SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA="'. $TestDB .'";';
$TestDB_Content = query( $link, $sQuery );
if ( !is_array( $TestDB_Content) ) {
echo "Table $TestDB cannot be accessed";
exit(0);
}
$SourceDB_Tables = array();
foreach( $SourceDB_Content as $item ) {
$SourceDB_Tables[] = $item["TABLE_NAME"];
}
$TestDB_Tables = array();
foreach( $TestDB_Content as $item ) {
$TestDB_Tables[] = $item["TABLE_NAME"];
}
//var_dump( $SourceDB_Tables, $TestDB_Tables );
$LookupTables = array_merge( $SourceDB_Tables, $TestDB_Tables );
$NoOfDiscrepancies = 0;
echo "
<table border='1' width='100%'>
<tr>
<td>Table</td>
<td>Found in $SourceDB (". count( $SourceDB_Tables ) .")</td>
<td>Found in $TestDB (". count( $TestDB_Tables ) .")</td>
<td>Test result</td>
<tr>
";
foreach( $LookupTables as $table ) {
$FoundInSourceDB = in_array( $table, $SourceDB_Tables ) ? 1 : 0;
$FoundInTestDB = in_array( $table, $TestDB_Tables ) ? 1 : 0;
echo "
<tr>
<td>$table</td>
<td><input type='checkbox' ". ($FoundInSourceDB == 1 ? "checked" : "") ."></td>
<td><input type='checkbox' ". ($FoundInTestDB == 1 ? "checked" : "") ."></td>
<td>". compareTables( $SourceDB, $TestDB, $table ) ."</td>
</tr>
";
}
echo "
</table>
<br><br>
No of discrepancies found: $NoOfDiscrepancies
";
function query( $link, $q ) {
$result = mysqli_query( $link, $q );
$errors = mysqli_error($link);
if ( $errors > "" ) {
echo $errors;
exit(0);
}
if( $result == false ) return false;
else if ( $result === true ) return true;
else {
$rset = array();
while ( $row = mysqli_fetch_assoc( $result ) ) {
$rset[] = $row;
}
return $rset;
}
}
function compareTables( $source, $test, $table ) {
global $link;
global $NoOfDiscrepancies;
$sQuery = "
SELECT column_name,ordinal_position,data_type,column_type FROM
(
SELECT
column_name,ordinal_position,
data_type,column_type,COUNT(1) rowcount
FROM information_schema.columns
WHERE
(
(table_schema='$source' AND table_name='$table') OR
(table_schema='$test' AND table_name='$table')
)
AND table_name IN ('$table')
GROUP BY
column_name,ordinal_position,
data_type,column_type
HAVING COUNT(1)=1
) A;
";
$result = query( $link, $sQuery );
$data = "";
if( is_array( $result ) && count( $result ) > 0 ) {
$NoOfDiscrepancies++;
$data = "<table><tr><td>column_name</td><td>ordinal_position</td><td>data_type</td><td>column_type</td></tr>";
foreach( $result as $item ) {
$data .= "<tr><td>". $item["column_name"] ."</td><td>". $item["ordinal_position"] ."</td><td>". $item["data_type"] ."</td><td>". $item["column_type"] ."</td></tr>";
}
$data .= "</table>";
return $data;
}
else {
return "Checked but no discrepancies found!";
}
}
?>
At this time, I would answer "no" or "with difficulty", but that could change over time as the android NFC API evolves.
There are three modes of NFC interaction:
Reader-Writer: The phone reads tags and writes to them. It's not emulating a card instead an NFC reader/writer device. Hence, you can't emulate a tag in this mode.
Peer-to-peer: the phone can read and pass back ndef messages. If the tag reader supports peer-to-peer mode, then the phone could possibly act as a tag. However, I'm not sure if android uses its own protocol on top of the LLCP protocol (NFC logical link protocol), which would then prevent most readers from treating the phone as an nfc tag.
Card-emulation mode: the phone uses a secure element to emulate a smart card or other contactless device. I am not sure if this is launched yet, but could provide promising. However, using the secure element might require the hardware vendor or some other person to verify your app / give it permissions to access the secure element. It's not as simple as creating a regular NFC android app.
More details here: http://www.mail-archive.com/[email protected]/msg152222.html
A real question would be: why are you trying to emulate a simple old nfc tag? Is there some application I'm not thinking of? Usually, you'd want to emulate something like a transit card, access key, or credit card which would require a secure element (I think, but not sure).
Don't forget to use var/let while declaring any variable.See below examples for JS compiler behaviour.
function func(){
return true;
}
isBool = func();
console.log(typeof (isBool)); // output - string
let isBool = func();
console.log(typeof (isBool)); // output - boolean
Straight from the React docs:
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
})
})
(This is posting JSON, but you could also do, for example, multipart-form.)
You do not need to create sub directory. Just create blob container and use file name like the variable filename as below code:
string filename = "document/tech/user-guide.pdf";
CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(ConnectionString);
CloudBlockBlob blob = cloudBlobContainer.GetBlockBlobReference(filename);
blob.StreamWriteSizeInBytes = 20 * 1024;
blob.UploadFromStream(fileStream); // fileStream is System.IO.Stream
I resolved it by remove lower version of Newtonsoft.json.dll in bin folder and added Newtonsoft.json.dll V6.0.0.0 and removed the following web.config elements
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed"/>
<bindingRedirect oldVersion="0.0.0.0-4.5.0.0" newVersion="5.0.8"/>
</dependentAssembly>
<div class="d-flex justify-content-center align-items-center container ">
<div class="row ">
<form action="">
<div class="form-group">
<label for="inputUserName" class="control-label">Enter UserName</label>
<input type="email" class="form-control" id="inputUserName" aria-labelledby="emailnotification">
<small id="emailnotification" class="form-text text-muted">Enter Valid Email Id</small>
</div>
<div class="form-group">
<label for="inputPassword" class="control-label">Enter Password</label>
<input type="password" class="form-control" id="inputPassword" aria-labelledby="passwordnotification">
</div>
</form>
</div>
</div>
<input type="number" step="1" ...
By adding the step
attribute, you restrict input to integers.
Of course you should always validate on the server as well. Except under carefully controlled conditions, everything received from a client needs to be treated as suspect.
To understand pid files, refer this DOC
Some times there are certain applications that require additional support of extra plugins and utilities. So it keeps track of these utilities and plugin process running ids using this pid file for reference.
That is why whenever you restart an application all necessary plugins and dependant apps must be restarted since the pid file will become stale.
Faced same issue and solved by :
remove.packages("ggplot2")
install.packages('ggplot2', dependencies = TRUE)
I also have same problem and in my case I injected reducer properly but still I couldn't type in field. It turns out if you are using immutable
you have to use redux-form/immutable
.
import {reducer as formReducer} from 'redux-form/immutable';
const reducer = combineReducers{
form: formReducer
}
import {Field, reduxForm} from 'redux-form/immutable';
/* your component */
Notice that your state should be like state->form
otherwise you have to explicitly config the library also the name for state should be form
.
see this issue
Violating the Java naming conventions (variable names and method names start with lowercase, class names start with uppercase) is contributing to your confusion.
The variable Random
is only "in scope" inside the main
method. It's not accessible to any methods called by main
. When you return from main
, the variable disappears (it's part of the stack frame).
If you want all of the methods of your class to use the same Random
instance, declare a member variable:
class MyObj {
private final Random random = new Random();
public void compTurn() {
while (true) {
int a = random.nextInt(10);
if (possibles[a] == 1)
break;
}
}
}
You can try to provide your own thread factory, which will create thread with appropriate names. Here's one example:
class YourThreadFactory implements ThreadFactory {
public Thread newThread(Runnable r) {
return new Thread(r, "Your name");
}
}
Executors.newSingleThreadExecutor(new YourThreadFactory()).submit(someRunnable);
I'd prefer using Pathname:
require 'pathname' # pathname is in stdlib
Pathname(ROOT_DIR) + project + 'App.config'
about <<
and +
from ruby docs:
+
: Returns a new String containing other_str concatenated to str
<<
: Concatenates the given object to str. If the object is a Fixnum between 0 and 255, it is converted to a character before concatenation.
so difference is in what becomes to first operand (<<
makes changes in place, +
returns new string so it is memory heavier) and what will be if first operand is Fixnum (<<
will add as if it was character with code equal to that number, +
will raise error)
Based on kynan's answer, here are the same aliases, modified so they can handle spaces and initial dashes in filenames:
accept-ours = "!f() { [ -z \"$@\" ] && set - '.'; git checkout --ours -- \"$@\"; git add -u -- \"$@\"; }; f"
accept-theirs = "!f() { [ -z \"$@\" ] && set - '.'; git checkout --theirs -- \"$@\"; git add -u -- \"$@\"; }; f"
I know this is somewhat of an old question, but I thought I'd share what worked for me. I was having problems with Eclipse -- it wouldn't kill the processes, and so I had a bunch of phantom processes hanging around after testing the code using the Eclipse runner.
My solution was to run Eclipse as administrator. That fixed it for me. Seems that Windows wasn't permitting Eclipse to close the process it spawned.
The include relationship allows one use case to include the steps of another use case.
For example, suppose you have an Amazon Account and you want to check on an order, well it is impossible to check on the order without first logging into your account. So the flow of events would like so...
The extend relationship is used to add an extra step to the flow of a use case, that is usually an optional step...
Imagine that we are still talking about your amazon account. Lets assume the base case is Order and the extension use case is Amazon Prime. The user can choose to just order the item regularly, or, the user has the option to select Amazon Prime which ensure his order will arrive faster at higher cost.
However, note that the user does not have to select Amazon Prime, this is just an option, they can choose to ignore this use case.
Minimal settings to prevent resize events
form1.FormBorderStyle = FormBorderStyle.FixedDialog;
form1.MaximizeBox = false;
Infact this worked for me
SELECT *
FROM myTable
WHERE CAST(ReadDate AS DATETIME) + ReadTime BETWEEN '2010-09-16 5:00PM' AND '2010-09-21 9:00AM'
this way is right with me:
private void textboxNumberic_KeyPress(object sender, KeyPressEventArgs e)
{
const char Delete = (char)8;
e.Handled = !Char.IsDigit(e.KeyChar) && e.KeyChar != Delete;
}
On Windows this has worked for me. From the command line, specify the path to the exe for Python: & "C:/Program Files (x86)/Python37-32/python.exe" -m pip install --upgrade pip --user
values\styles.xml
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<style name="RedAccentButton" parent="ThemeOverlay.AppCompat.Light">
<item name="colorAccent">#ff0000</item>
</style>
then:
<Button
style="@style/Widget.AppCompat.Button.Colored"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="text" />
<Button
style="@style/Widget.AppCompat.Button.Colored"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:enabled="false"
android:text="text" />
<Button
style="@style/Widget.AppCompat.Button.Colored"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="text"
android:theme="@style/RedAccentButton" />
<Button
style="@style/Widget.AppCompat.Button.Colored"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:enabled="false"
android:text="text"
android:theme="@style/RedAccentButton" />
dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Blue;
The problem with setting the modalPresentationStyle from code was that you should have set it in the init() method of the presented view controller, not the parent view controller.
From UIKit docs: "Defines the transition style that will be used for this view controller when it is presented modally. Set this property on the view controller to be presented, not the presenter. Defaults to UIModalTransitionStyleCoverVertical."
The viewDidLoad method will only be called after you already presented the view controller.
The second problem was that you should use UIModalPresentationStyle.overCurrentContext.
In the interest of completeness, it should be pointed out that there are representations of strings on various platforms in which the number of bytes per character varies depending on the character. Old-school programmers would refer to this as DBCS (Double Byte Character Set). Modern programmers more commonly encounter this in UTF-8 (as well as UTF-16 and others). There are other such encodings as well.
In any of these variable-width encoding schemes, the simple algorithms posted here (evil, non-evil or otherwise) would not work correctly at all! In fact, they could even cause the string to become illegible or even an illegal string in that encoding scheme. See Juan Pablo Califano's answer for some good examples.
std::reverse() potentially would still work in this case, as long as your platform's implementation of the Standard C++ Library (in particular, string iterators) properly took this into account.
What's wrong with the printStacktrace()
method provided by Throwable
(and thus every exception)? It shows all the info you requested, including the type, message, and stack trace of the root exception and all (nested) causes. In Java 7, it even shows you the information about "supressed" exceptions that might occur in a try-with-resources statement.
Of course you wouldn't want to write to System.err
, which the no-argument version of the method does, so instead use one of the available overloads.
In particular, if you just want to get a String:
Exception e = ...
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionDetails = sw.toString();
If you happen to use the great Guava library, it provides a utility method doing this: com.google.common.base.Throwables#getStackTraceAsString(Throwable)
.
Firstly, it will help if you set the headers of your PHP to serve JSON:
header('Content-type: application/json');
Secondly, it will help to adjust your ajax call:
$.ajax({
url: "main.php",
type: "POST",
dataType: "json",
data: {"action": "loadall", "id": id},
success: function(data){
console.log(data);
},
error: function(error){
console.log("Error:");
console.log(error);
}
});
If successful, the response you receieve should be picked up as true JSON and an object should be logged to console.
NOTE: If you want to pick up pure html, you might want to consider using another method to JSON, but I personally recommend using JSON and rendering it into html using templates (such as Handlebars js).
Object
: A data structure in which data is stored as key value pairs. In an object the key has to be a number, string, or symbol. The value can be anything so also other objects, functions etc. A object is an non ordered data structure, i.e. the sequence of insertion of key value pairs is not rememberedES6 Map
: A data structure in which data is stored as key value pairs. In which a unique key maps to a value. Both the key and the value can be in any data type. A map is a iterable data structure, this means that the sequence of insertion is remembered and that we can access the elements in e.g. a for..of
loopKey differences:
A Map
is ordered and iterable, whereas a objects is not ordered and not iterable
We can put any type of data as a Map
key, whereas objects can only have a number, string, or symbol as a key.
A Map
inherits from Map.prototype
. This offers all sorts of utility functions and properties which makes working with Map
objects a lot easier.
object:
let obj = {};_x000D_
_x000D_
// adding properties to a object_x000D_
obj.prop1 = 1;_x000D_
obj[2] = 2;_x000D_
_x000D_
// getting nr of properties of the object_x000D_
console.log(Object.keys(obj).length)_x000D_
_x000D_
// deleting a property_x000D_
delete obj[2]_x000D_
_x000D_
console.log(obj)
_x000D_
Map:
const myMap = new Map();_x000D_
_x000D_
const keyString = 'a string',_x000D_
keyObj = {},_x000D_
keyFunc = function() {};_x000D_
_x000D_
// setting the values_x000D_
myMap.set(keyString, "value associated with 'a string'");_x000D_
myMap.set(keyObj, 'value associated with keyObj');_x000D_
myMap.set(keyFunc, 'value associated with keyFunc');_x000D_
_x000D_
console.log(myMap.size); // 3_x000D_
_x000D_
// getting the values_x000D_
console.log(myMap.get(keyString)); // "value associated with 'a string'"_x000D_
console.log(myMap.get(keyObj)); // "value associated with keyObj"_x000D_
console.log(myMap.get(keyFunc)); // "value associated with keyFunc"_x000D_
_x000D_
console.log(myMap.get('a string')); // "value associated with 'a string'"_x000D_
// because keyString === 'a string'_x000D_
console.log(myMap.get({})); // undefined, because keyObj !== {}_x000D_
console.log(myMap.get(function() {})) // undefined, because keyFunc !== function () {}
_x000D_
var myCheckboxes = new Array();
$("input:checked").each(function() {
data['myCheckboxes[]'].push($(this).val());
});
You are pushing checkboxes to wrong array data['myCheckboxes[]']
instead of myCheckboxes.push
function get_time($time) {
$duration = $time / 1000;
$hours = floor($duration / 3600);
$minutes = floor(($duration / 60) % 60);
$seconds = $duration % 60;
if ($hours != 0)
echo "$hours:$minutes:$seconds";
else
echo "$minutes:$seconds";
}
get_time('1119241');
IMHO, the best explanation about its meaning gave us Stroustrup + take into account examples of Dániel Sándor and Mohan:
Stroustrup:
Now I was seriously worried. Clearly we were headed for an impasse or a mess or both. I spent the lunchtime doing an analysis to see which of the properties (of values) were independent. There were only two independent properties:
has identity
– i.e. and address, a pointer, the user can determine whether two copies are identical, etc.can be moved from
– i.e. we are allowed to leave to source of a "copy" in some indeterminate, but valid stateThis led me to the conclusion that there are exactly three kinds of values (using the regex notational trick of using a capital letter to indicate a negative – I was in a hurry):
iM
: has identity and cannot be moved fromim
: has identity and can be moved from (e.g. the result of casting an lvalue to a rvalue reference)
Im
: does not have identity and can be moved from.The fourth possibility,
IM
, (doesn’t have identity and cannot be moved) is not useful inC++
(or, I think) in any other language.In addition to these three fundamental classifications of values, we have two obvious generalizations that correspond to the two independent properties:
i
: has identitym
: can be moved fromThis led me to put this diagram on the board:
Naming
I observed that we had only limited freedom to name: The two points to the left (labeled
iM
andi
) are what people with more or less formality have calledlvalues
and the two points on the right (labeledm
andIm
) are what people with more or less formality have calledrvalues
. This must be reflected in our naming. That is, the left "leg" of theW
should have names related tolvalue
and the right "leg" of theW
should have names related torvalue.
I note that this whole discussion/problem arise from the introduction of rvalue references and move semantics. These notions simply don’t exist in Strachey’s world consisting of justrvalues
andlvalues
. Someone observed that the ideas that
- Every
value
is either anlvalue
or anrvalue
- An
lvalue
is not anrvalue
and anrvalue
is not anlvalue
are deeply embedded in our consciousness, very useful properties, and traces of this dichotomy can be found all over the draft standard. We all agreed that we ought to preserve those properties (and make them precise). This further constrained our naming choices. I observed that the standard library wording uses
rvalue
to meanm
(the generalization), so that to preserve the expectation and text of the standard library the right-hand bottom point of theW
should be namedrvalue.
This led to a focused discussion of naming. First, we needed to decide on
lvalue.
Shouldlvalue
meaniM
or the generalizationi
? Led by Doug Gregor, we listed the places in the core language wording where the wordlvalue
was qualified to mean the one or the other. A list was made and in most cases and in the most tricky/brittle textlvalue
currently meansiM
. This is the classical meaning of lvalue because "in the old days" nothing was moved;move
is a novel notion inC++0x
. Also, naming the topleft point of theW
lvalue
gives us the property that every value is anlvalue
or anrvalue
, but not both.So, the top left point of the
W
islvalue
and the bottom right point isrvalue.
What does that make the bottom left and top right points? The bottom left point is a generalization of the classical lvalue, allowing for move. So it is ageneralized lvalue.
We named itglvalue.
You can quibble about the abbreviation, but (I think) not with the logic. We assumed that in serious usegeneralized lvalue
would somehow be abbreviated anyway, so we had better do it immediately (or risk confusion). The top right point of the W is less general than the bottom right (now, as ever, calledrvalue
). That point represent the original pure notion of an object you can move from because it cannot be referred to again (except by a destructor). I liked the phrasespecialized rvalue
in contrast togeneralized lvalue
butpure rvalue
abbreviated toprvalue
won out (and probably rightly so). So, the left leg of the W islvalue
andglvalue
and the right leg isprvalue
andrvalue.
Incidentally, every value is either a glvalue or a prvalue, but not both.This leaves the top middle of the
W
:im
; that is, values that have identity and can be moved. We really don’t have anything that guides us to a good name for those esoteric beasts. They are important to people working with the (draft) standard text, but are unlikely to become a household name. We didn’t find any real constraints on the naming to guide us, so we picked ‘x’ for the center, the unknown, the strange, the xpert only, or even x-rated.
A Protocol?
I found this, it appears to be a local setting for a computer...
A Subquery in the Select clause, as in your case, is also known as a Scalar Subquery, which means that it's a form of expression. Meaning that it can only return one value.
I'm afraid you can't return multiple columns from a single Scalar Subquery, no.
Here's more about Oracle Scalar Subqueries:
http://docs.oracle.com/cd/B19306_01/server.102/b14200/expressions010.htm#i1033549
You could create your own class of type Quiz and then deserialize with strong type:
Example:
quizresult = JsonConvert.DeserializeObject<Quiz>(args.Message,
new JsonSerializerSettings
{
Error = delegate(object sender1, ErrorEventArgs args1)
{
errors.Add(args1.ErrorContext.Error.Message);
args1.ErrorContext.Handled = true;
}
});
And you could also apply a schema validation.
Go to File-> Project Structure-> Libraries and click green "+" to add the directory folder that has the JARs to CLASSPATH. Everything in that folder will be added to CLASSPATH.
Update:
It's 2018. It's a better idea to use a dependency manager like Maven and externalize your dependencies. Don't add JAR files to your project in a /lib folder anymore.
For correlations you can just use the corr function (statistics toolbox)
corr(A_1(:), A_2(:))
Note that you can also just use
corr(A_1, A_2)
But the linear indexing guarantees that your vectors don't need to be transposed.
select
distinct
e1.enddate,
e3.startdate,
DATEDIFF(DAY,e1.enddate,e3.startdate)-1 as [Datediff]
from #temp e1
join #temp e3 on e1.enddate < e3.startdate
/* Finds the next start Time */
and e3.startdate = (select min(startdate) from #temp e5
where e5.startdate > e1.enddate)
and not exists (select * /* Eliminates e1 rows if it is overlapped */
from #temp e5
where e5.startdate < e1.enddate and e5.enddate > e1.enddate);
Apply this code in your css
::-webkit-scrollbar{
-webkit-appearance: none;
width: 7px;
}
::-webkit-scrollbar-thumb {
border-radius: 4px;
background-color: rgba(0,0,0,.5);
-webkit-box-shadow: 0 0 1px rgba(255,255,255,.5);
}
You can use
shouldShowRequestPermissionRationale()
inside
onRequestPermissionsResult()
See the example below:
Check if it has permission when the user clicks the button:
@Override
public void onClick(View v) {
if (v.getId() == R.id.appCompatBtn_changeProfileCoverPhoto) {
if (Build.VERSION.SDK_INT < 23) { // API < 23 don't need to ask permission
navigateTo(MainActivity.class); // Navigate to activity to change photos
} else {
if (ContextCompat.checkSelfPermission(SettingsActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Permission is not granted yet. Ask for permission...
requestWriteExternalPermission();
} else {
// Permission is already granted, good to go :)
navigateTo(MainActivity.class);
}
}
}
}
When the user answer the permission dialog box we will go to onRequestPermissionResult:
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == WRITE_EXTERNAL_PERMISSION_REQUEST_CODE) {
// Case 1. Permission is granted.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(SettingsActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
// Before navigating, I still check one more time the permission for good practice.
navigateTo(MainActivity.class);
}
} else { // Case 2. Permission was refused
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
// Case 2.1. shouldShowRequest... returns true because the
// permission was denied before. If it is the first time the app is running we will
// end up in this part of the code. Because he need to deny at least once to get
// to onRequestPermissionsResult.
Snackbar snackbar = Snackbar.make(findViewById(R.id.relLayout_container), R.string.you_must_verify_permissions_to_send_media, Snackbar.LENGTH_LONG);
snackbar.setAction("VERIFY", new View.OnClickListener() {
@Override
public void onClick(View v) {
ActivityCompat.requestPermissions(SettingsActivity.this
, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}
, WRITE_EXTERNAL_PERMISSION_REQUEST_CODE);
}
});
snackbar.show();
} else {
// Case 2.2. Permission was already denied and the user checked "Never ask again".
// Navigate user to settings if he choose to allow this time.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.instructions_to_turn_on_storage_permission)
.setPositiveButton(getString(R.string.settings), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent settingsIntent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
settingsIntent.setData(uri);
startActivityForResult(settingsIntent, 7);
}
})
.setNegativeButton(getString(R.string.not_now), null);
Dialog dialog = builder.create();
dialog.show();
}
}
}
}
For me it worked:
df['id'].convert_dtypes()
see the documentation here:
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.convert_dtypes.html
Don't have ECMAScript 2018?
My goal was to make it work as similar as possible to what we are used to with named groups. Whereas in ECMAScript 2018 you can place ?<groupname>
inside the group to indicate a named group, in my solution for older javascript, you can place (?!=<groupname>)
inside the group to do the same thing. So it's an extra set of parenthesis and an extra !=
. Pretty close!
I wrapped all of it into a string prototype function
Features
Instructions
(?!={groupname})
inside each group you want to name()
by putting ?:
at the beginning of that group. These won't be named.arrays.js
// @@pattern - includes injections of (?!={groupname}) for each group
// @@returns - an object with a property for each group having the group's match as the value
String.prototype.matchWithGroups = function (pattern) {
var matches = this.match(pattern);
return pattern
// get the pattern as a string
.toString()
// suss out the groups
.match(/<(.+?)>/g)
// remove the braces
.map(function(group) {
return group.match(/<(.+)>/)[1];
})
// create an object with a property for each group having the group's match as the value
.reduce(function(acc, curr, index, arr) {
acc[curr] = matches[index + 1];
return acc;
}, {});
};
usage
function testRegGroups() {
var s = '123 Main St';
var pattern = /((?!=<house number>)\d+)\s((?!=<street name>)\w+)\s((?!=<street type>)\w+)/;
var o = s.matchWithGroups(pattern); // {'house number':"123", 'street name':"Main", 'street type':"St"}
var j = JSON.stringify(o);
var housenum = o['house number']; // 123
}
result of o
{
"house number": "123",
"street name": "Main",
"street type": "St"
}
Late answer, I know, but for me the following script is quite useful - and it answers the question too, hitting two flys with one flag ;-)
The following script expands SendTo in the file explorer's context menu:
@echo off
cls
if "%~dp1"=="" goto Install
REM change drive, then cd to path given and run shell there
%~d1
cd "%~dp1"
cmd /k
goto End
:Install
rem No arguments: Copies itself into SendTo folder
copy "%0" "%appdata%\Microsoft\Windows\SendTo\A - Open in CMD shell.cmd"
:End
If you run this script without any parameters by double-clicking on it, it will copy itself to the SendTo folder and renaming it to "A - Open in CMD shell.cmd". Afterwards it is available in the "SentTo" context menu.
Then, right-click on any file or folder in Windows explorer and select "SendTo > A - Open in CMD shell.cmd"
The script will change drive and path to the path containing the file or folder you have selected and open a command shell with that path - useful for Visual Studio Code, because then you can just type "code ." to run it in the context of your project.
How does it work?
%0
- full path of the batch script
%~d1
- the drive contained in the first argument (e.g. "C:")
%~dp1
- the path contained in the first argument
cmd /k
- opens a command shell which stays open
Not used here, but %~n1
is the file name of the first argument.
I hope this is helpful for someone.
Something like this would work
#!/bin/sh
if [ -fe FILE ]
then
rm FILE
fi
-f checks if it's a regular file
-e checks if the file exist
Introduction to if for more information
EDIT : -e used with -f is redundant, fo using -f alone should work too
You can refer the javadoc 8 documentation
I think what you are looking at is something like this:
javadoc -d C:\javadoc\test com.test
in addition to all the answers that other friends have , if somebody who is looking this post is looking for a way to delete a "Folder" not a "file" , should take care that Folders must delete by php rmdir() function and if u want to delete a "Folder" by unlink()
, u will encounter with a wrong Warning message that says "permission denied"
however u can make folders & files by mkdir()
but the way u delete folders (rmdir()
) is different from the way you delete files(unlink()
)
eventually as a fact:
in many programming languages, any permission related error may not directly means an actual permission issue
for example, if you want to readSync
a file that doesn't exist with node fs module
you will encounter a wrong EPERM
error
Ud_an's solution with updated API's
Note: LatLng class is part of Google Play Services.
Mandatory:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
Update: If you have target SDK 23 and above, make sure you take care of runtime permission for location.
public LatLng getLocationFromAddress(Context context,String strAddress) {
Geocoder coder = new Geocoder(context);
List<Address> address;
LatLng p1 = null;
try {
// May throw an IOException
address = coder.getFromLocationName(strAddress, 5);
if (address == null) {
return null;
}
Address location = address.get(0);
p1 = new LatLng(location.getLatitude(), location.getLongitude() );
} catch (IOException ex) {
ex.printStackTrace();
}
return p1;
}
Here is the best solution to use Gif Image. Add SDWebImage from Github in your project.
#import "UIImage+GIF.h"
_imageViewAnimatedGif.image= [UIImage sd_animatedGIFNamed:@"thumbnail"];
Swift 3.0+
Left padding String
extension similar to padding(toLength:withPad:startingAt:)
in Foundation
extension String {
func leftPadding(toLength: Int, withPad: String = " ") -> String {
guard toLength > self.characters.count else { return self }
let padding = String(repeating: withPad, count: toLength - self.characters.count)
return padding + self
}
}
Usage:
let s = String(123)
s.leftPadding(toLength: 8, withPad: "0") // "00000123"
Using a char when the variable is a string won't work. Using
switch (hello.charAt(0))
you will extract the first character of the hello variable instead of trying to use the variable as it is, in string form. You also need to get rid of your space inside
case 'a '
You can also do this to get current Month :
string monthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(DateTime.Now.Month);
I think you set the marquee width related to 5 images total width. It works fine
ex: <marquee style="width:700px"></marquee>
Change the checkboxes so that the name includes the index inside the brackets:
<input type="checkbox" class="checkbox_veh" id="checkbox_addveh<?php echo $i; ?>" <?php if ($vehicle_feature[$i]->check) echo "checked"; ?> name="feature[<?php echo $i; ?>]" value="<?php echo $vehicle_feature[$i]->id; ?>">
The checkboxes that aren't checked are never submitted. The boxes that are checked get submitted, but they get numbered consecutively from 0, and won't have the same indexes as the other corresponding input fields.
Another option, not necesarily more elegant, but does not require to refer to a specific column:
mtcars %>%
group_by(cyl, gear) %>%
do(data.frame(nrow=nrow(.)))
You use a shebang line at the start of your script:
#!/usr/bin/env python
make the file executable:
chmod +x arbitraryname
and put it in a directory on your PATH (can be a symlink):
cd ~/bin/
ln -s ~/some/path/to/myscript/arbitraryname
If you truly want to discard the commits you've made locally, i.e. never have them in the history again, you're not asking how to pull - pull means merge, and you don't need to merge. All you need do is this:
# fetch from the default remote, origin
git fetch
# reset your current branch (master) to origin's master
git reset --hard origin/master
I'd personally recommend creating a backup branch at your current HEAD first, so that if you realize this was a bad idea, you haven't lost track of it.
If on the other hand, you want to keep those commits and make it look as though you merged with origin, and cause the merge to keep the versions from origin only, you can use the ours
merge strategy:
# fetch from the default remote, origin
git fetch
# create a branch at your current master
git branch old-master
# reset to origin's master
git reset --hard origin/master
# merge your old master, keeping "our" (origin/master's) content
git merge -s ours old-master
I agree with above answer. But here is another way of CSS compression.
You can concat your CSS by using YUI compressor:
module.exports = function(grunt) {
var exec = require('child_process').exec;
grunt.registerTask('cssmin', function() {
var cmd = 'java -jar -Xss2048k '
+ __dirname + '/../yuicompressor-2.4.7.jar --type css '
+ grunt.template.process('/css/style.css') + ' -o '
+ grunt.template.process('/css/style.min.css')
exec(cmd, function(err, stdout, stderr) {
if(err) throw err;
});
});
};
mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
My code work well just as the answer above. The reason is that the json from jackson is different with the json sent from controller.
String test1= mapper.writeValueAsString(result1);
And the json is like(which can be deserialized normally):
{"code":200,"message":"god","data":[{"nics":null,"status":null,"desktopOperatorType":null,"marker":null,"user_name":null,"user_group":null,"user_email":null,"product_id":null,"image_id":null,"computer_name":"AAAA","desktop_id":null,"created":null,"ip_address":null,"security_groups":null,"root_volume":null,"data_volumes":null,"availability_zone":null,"ou_name":null,"login_status":null,"desktop_ip":null,"ad_id":null},{"nics":null,"status":null,"desktopOperatorType":null,"marker":null,"user_name":null,"user_group":null,"user_email":null,"product_id":null,"image_id":null,"computer_name":"BBBB","desktop_id":null,"created":null,"ip_address":null,"security_groups":null,"root_volume":null,"data_volumes":null,"availability_zone":null,"ou_name":null,"login_status":null,"desktop_ip":null,"ad_id":null}]}
but the json send from the another service just like:
{"code":200,"message":"????????","data":[{"nics":"","status":"","metadata":"","desktopOperatorType":"","marker":"","user_name":"csrgzbsjy","user_group":"ADMINISTRATORS","user_email":"","product_id":"","image_id":"","computer_name":"B-jiegou-all-15","desktop_id":"6360ee29-eb82-416b-aab8-18ded887e8ff","created":"2018-11-12T07:45:15.000Z","ip_address":"192.168.2.215","security_groups":"","root_volume":"","data_volumes":"","availability_zone":"","ou_name":"","login_status":"","desktop_ip":"","ad_id":""},{"nics":"","status":"","metadata":"","desktopOperatorType":"","marker":"","user_name":"glory_2147","user_group":"ADMINISTRATORS","user_email":"","product_id":"","image_id":"","computer_name":"H-pkpm-all-357","desktop_id":"709164e4-d3e6-495d-9c1e-a7b82e30bc83","created":"2018-11-09T09:54:09.000Z","ip_address":"192.168.2.235","security_groups":"","root_volume":"","data_volumes":"","availability_zone":"","ou_name":"","login_status":"","desktop_ip":"","ad_id":""}]}
You can notice the difference when dealing with the param without initiation. Be careful
IMO extremely important rule of thumb for your client side js code is to keep separated the data handling and ui building logic into different funcs, which is also valid for axios data fetching ... in this way your control flow and error handlings will be much more simple and easier to manage, as it could be seen from this ok fetch
and this NOK fetch
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
function getUrlParams (){
var url_params = new URLSearchParams();
if( window.location.toString().indexOf("?") != -1) {
var href_part = window.location.search.split('?')[1]
href_part.replace(/([^=&]+)=([^&]*)/g,
function(m, key, value) {
var attr = decodeURIComponent(key)
var val = decodeURIComponent(value)
url_params.append(attr,val);
});
}
// for(var pair of url_params.entries()) { consolas.log(pair[0]+ '->'+ pair[1]); }
return url_params ;
}
function getServerData (url, urlParams ){
if ( typeof url_params == "undefined" ) { urlParams = getUrlParams() }
return axios.get(url , { params: urlParams } )
.then(response => {
return response ;
})
.catch(function(error) {
console.error ( error )
return error.response;
})
}
// Action !!!
getServerData(url , url_params)
.then( response => {
if ( response.status === 204 ) {
var warningMsg = response.statusText
console.warn ( warningMsg )
return
} else if ( response.status === 404 || response.status === 400) {
var errorMsg = response.statusText // + ": " + response.data.msg // this is my api
console.error( errorMsg )
return ;
} else {
var data = response.data
var dataType = (typeof data)
if ( dataType === 'undefined' ) {
var msg = 'unexpected error occurred while fetching data !!!'
// pass here to the ui change method the msg aka
// showMyMsg ( msg , "error")
} else {
var items = data.dat // obs this is my api aka "dat" attribute - that is whatever happens to be your json key to get the data from
// call here the ui building method
// BuildList ( items )
}
return
}
})
</script>
NullPointerException with JSP can also happen if:
A getter returns a non-public inner class.
This code will fail if you remove Getters's access modifier or make it private or protected.
JAVA:
package com.myPackage;
public class MyClass{
//: Must be public or you will get:
//: org.apache.jasper.JasperException:
//: java.lang.NullPointerException
public class Getters{
public String
myProperty(){ return(my_property); }
};;
//: JSP EL can only access functions:
private Getters _get;
public Getters get(){ return _get; }
private String
my_property;
public MyClass(String my_property){
super();
this.my_property = my_property;
_get = new Getters();
};;
};;
JSP
<%@ taglib uri ="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page import="com.myPackage.MyClass" %>
<%
MyClass inst = new MyClass("[PROP_VALUE]");
pageContext.setAttribute("my_inst", inst );
%><html lang="en"><body>
${ my_inst.get().myProperty() }
</body></html>
As Ennui mentioned, IE 10 supports the -ms
prefixed version of Flexbox (IE 11 supports it unprefixed). The errors I can see in your code are:
display: -ms-flexbox
instead of display: -ms-flex
flex
values, like flex: 0 1 auto
to avoid ambiguitySo the final updated code is...
.flexbox form {
display: -webkit-flex;
display: -moz-flex;
display: -ms-flexbox;
display: -o-flex;
display: flex;
/* Direction defaults to 'row', so not really necessary to specify */
-webkit-flex-direction: row;
-moz-flex-direction: row;
-ms-flex-direction: row;
-o-flex-direction: row;
flex-direction: row;
}
.flexbox form input[type=submit] {
width: 31px;
}
.flexbox form input[type=text] {
width: auto;
/* Flex should have 3 values which is shorthand for
<flex-grow> <flex-shrink> <flex-basis> */
-webkit-flex: 1 1 auto;
-moz-flex: 1 1 auto;
-ms-flex: 1 1 auto;
-o-flex: 1 1 auto;
flex: 1 1 auto;
/* I don't think you need 'display: flex' on child elements * /
display: -webkit-flex;
display: -moz-flex;
display: -ms-flex;
display: -o-flex;
display: flex;
/**/
}
This solution worked for me using the android sdk v19:
//get the image button by id
ImageButton myImg = (ImageButton) findViewById(R.id.some_id);
//get drawable from image button
GradientDrawable drawable = (GradientDrawable) myImg.getDrawable();
//set color as integer
//can use Color.parseColor(color) if color is a string
drawable.setColor(color)
.video {
width: 100%;
position: relative;
padding-bottom: 56.25%; /* ratio 16/9 */
}
.video iframe {
border: none;
position: absolute;
width: 100%;
height: 100%;
}
16:9
padding-bottom = 9/16 * 100 = 56.25
This will work:
for i in range(len(a)):
a[i] -= 13
site-packages is just the location where Python installs its modules.
No need to "find it", python knows where to find it by itself, this location is always part of the PYTHONPATH (sys.path).
Programmatically you can find it this way:
import sys
site_packages = next(p for p in sys.path if 'site-packages' in p)
print site_packages
'/Users/foo/.envs/env1/lib/python2.7/site-packages'
Yes, nested loops are one way to quickly get a big O notation.
Typically (but not always) one loop nested in another will cause O(n²).
Think about it, the inner loop is executed i times, for each value of i. The outer loop is executed n times.
thus you see a pattern of execution like this: 1 + 2 + 3 + 4 + ... + n times
Therefore, we can bound the number of code executions by saying it obviously executes more than n times (lower bound), but in terms of n how many times are we executing the code?
Well, mathematically we can say that it will execute no more than n² times, giving us a worst case scenario and therefore our Big-Oh bound of O(n²). (For more information on how we can mathematically say this look at the Power Series)
Big-Oh doesn't always measure exactly how much work is being done, but usually gives a reliable approximation of worst case scenario.
4 yrs later Edit: Because this post seems to get a fair amount of traffic. I want to more fully explain how we bound the execution to O(n²) using the power series
From the website: 1+2+3+4...+n = (n² + n)/2 = n²/2 + n/2. How, then are we turning this into O(n²)? What we're (basically) saying is that n² >= n²/2 + n/2. Is this true? Let's do some simple algebra.
It should be clear that n² >= n (not strictly greater than, because of the case where n=0 or 1), assuming that n is always an integer.
Actual Big O complexity is slightly different than what I just said, but this is the gist of it. In actuality, Big O complexity asks if there is a constant we can apply to one function such that it's larger than the other, for sufficiently large input (See the wikipedia page)
You can also use psql console to execute \copy without need to send file to Postgresql server machine. The command is the same:
\copy mytable [ ( column_list ) ] FROM '/path/to/csv/file' WITH CSV HEADER
$foo = 42;
$bar = function($x = 0) use ($foo){
return $x + $foo;
};
var_dump($bar(10)); // int(52)
UPDATE: there is now support for arrow functions, but i will let for someone that used it more to create the answer
Likely, your problem is that you parsed it okay, and now you're trying to print the contents of the XML and you can't because theres some foreign Unicode characters. Try to encode your unicode string as ascii first:
unicodeData.encode('ascii', 'ignore')
the 'ignore' part will tell it to just skip those characters. From the python docs:
>>> # Python 2: u = unichr(40960) + u'abcd' + unichr(1972)
>>> u = chr(40960) + u'abcd' + chr(1972)
>>> u.encode('utf-8')
'\xea\x80\x80abcd\xde\xb4'
>>> u.encode('ascii')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
UnicodeEncodeError: 'ascii' codec can't encode character '\ua000' in position 0: ordinal not in range(128)
>>> u.encode('ascii', 'ignore')
'abcd'
>>> u.encode('ascii', 'replace')
'?abcd?'
>>> u.encode('ascii', 'xmlcharrefreplace')
'ꀀabcd޴'
You might want to read this article: http://www.joelonsoftware.com/articles/Unicode.html, which I found very useful as a basic tutorial on what's going on. After the read, you'll stop feeling like you're just guessing what commands to use (or at least that happened to me).
In my case, just using flex-shrink: 0
didn't work. But adding flex-grow: 1
to it worked.
.item {
flex-shrink: 0;
flex-grow: 1;
}
see dictionary view objects: https://docs.python.org/2/library/stdtypes.html#dict
This way you can subtract dictView2 from dictView1 and it will return a set of key/value pairs that are different in dictView2:
original = {'one':1,'two':2,'ACTION':'ADD'}
originalView=original.viewitems()
updatedDict = {'one':1,'two':2,'ACTION':'REPLACE'}
updatedDictView=updatedDict.viewitems()
delta=original | updatedDict
print delta
>>set([('ACTION', 'REPLACE')])
You can intersect, union, difference (shown above), symmetric difference these dictionary view objects.
Better? Faster? - not sure, but part of the standard library - which makes it a big plus for portability
If you are like me and don't always retrieve the axes, ax
, when plotting the figure, then a simple solution would be to do
plt.xticks([])
plt.yticks([])
var blob = new Blob([arrayBuffer])
var reader = new FileReader();
reader.onload = function(event){
var base64 = event.target.result
};
reader.readAsDataURL(blob);
If you setup your select like the following:
<select ng-model="myselect" ng-options="b for b in options track by b"></select>
you will get:
<option value="var1">var1</option>
<option value="var2">var2</option>
<option value="var3">var3</option>
working fiddle: http://jsfiddle.net/x8kCZ/15/
Always use UTC:
For example I have a schedule component that takes in one parameter DATETIME. When I call this using a GET verb I use the following format where my incoming parameter name is scheduleDate.
Example:
https://localhost/api/getScheduleForDate?scheduleDate=2003-11-21T01:11:11Z
I managed to do this with the following code:
ALTER TABLE `table_name`
CHANGE COLUMN `colum_name` `colum_name` INT(11) NOT NULL AUTO_INCREMENT FIRST;
This is the only way I could make a column auto increment.
INT(11) shows that the maximum int length is 11, you can skip it if you want.
Right click the installer and choose "Run as administrator". I suspect it needs administrator account to download and install Node JS during installation.
For Each is much faster than for I=1 to X, for some reason. Just try to go through the same dictionary,
once with for each Dkey in dDict,
and once with for Dkey = lbound(dDict.keys) to ubound(dDict.keys)
=>You will notice a huge difference, even though you are going through the same construct.
In case you can't install the procps package (don't have proper permissions) you can use /proc directory.
The first few directories (named as numbers) are PIDs of your processes. Inside directories, you can find additional information useful to decipher which process is connected to each PID. For example, you can use the cat command to view "cmdline" file to check which process is connected to PID.
$ ls /proc
1 10 11 ...
$ ls -1 /proc/22
attr
autogroup
auxv
cgroup
clear_refs
cmdline
...
$ cat /proc/22/cmdline
/bin/sh
I'm not entirely sure if I understood your question, but it seems that you're trying to set value for an input type Date.
If you want to set a value for an input type 'Date', then it has to be formatted as "yyyy-MM-dd" (Note: capital MM for Month, lower case mm for minutes). Otherwise, it will clear the value and leave the datepicker empty.
Let's say you have a button called "DateChanger" and you want to set your datepicker to "22 Dec 2012" when you click it.
<script>
$(document).ready(function () {
$('#DateChanger').click(function() {
$('#dtFrom').val("2012-12-22");
});
});
</script>
<input type="date" id="dtFrom" name="dtFrom" />
<button id="DateChanger">Click</button>
Remember to include JQuery reference.
Here is another solution which uses any/2
map(select(any(.Names[]; contains("data"))|not)|.Id)[]
with the sample data and the -r
option it produces
cb94e7a42732b598ad18a8f27454a886c1aa8bbba6167646d8f064cd86191e2b
a4b7e6f5752d8dcb906a5901f7ab82e403b9dff4eaaeebea767a04bac4aada19
just write ''
in place of '
i mean two times '
As you've noticed, you have no selectivity to your update statement so it is updating your entire table. If you want to update specific rows (ie where the IDs match) you probably want to do a coordinated subquery.
However, since you are using Oracle, it might be easier to create a materialized view for your query table and let Oracle's transaction mechanism handle the details. MVs work exactly like a table for querying semantics, are quite easy to set up, and allow you to specify the refresh interval.
A lesser known trick is that mod_php maps stderr to the Apache log. And, there is a stream for that, so file_put_contents('php://stderr', print_r($foo, TRUE))
will nicely dump the value of $foo
into the Apache error log.
NSUnderlineStyleAttributeName which takes an NSNumber (where 0 is no underline) can be added to an attribute dictionary. I don't know if this is any easier. But, it was easier for my purposes.
NSDictionary *attributes;
attributes = @{NSFontAttributeName:font, NSParagraphStyleAttributeName: style, NSUnderlineStyleAttributeName:[NSNumber numberWithInteger:1]};
[text drawInRect:CGRectMake(self.contentRect.origin.x, currentY, maximumSize.width, textRect.size.height) withAttributes:attributes];
Probably you didn't provide an argument on the command line. In that case, sys.argv
only contains one value, but it would have to have two in order to provide values for both user_name
and script
.
Unlike in PyQt5, in PySide2 the QThread.started signal is received/handled on the original thread, not the worker thread! Luckily it still receives all other signals on the worker thread.
In order to match PyQt5's behavior, you have to create the started signal yourself.
Here is an easy solution:
# Use this class instead of QThread
class QThread2(QThread):
# Use this signal instead of "started"
started2 = Signal()
def __init__(self):
QThread.__init__(self)
self.started.connect(self.onStarted)
def onStarted(self):
self.started2.emit()
Another option I like, which can be generalized once I start seeing the code not conform to DRY, is to use one controller that redirects to another controller.
public ActionResult ClientIdSearch(int cid)
{
var action = String.Format("Details/{0}", cid);
return RedirectToAction(action, "Accounts");
}
I find this allows me to apply my logic in one location and re-use it without have to sprinkle JavaScript in the views to handle this. And, as I mentioned I can then refactor for re-use as I see this getting abused.
Maybe this answer is not quite what you're looking for, but it will fomat any language with the same keyboard shortcut. The solution are language specific keyboard shortcuts.
For every language you want to format, you must find and download a plugin for that, for example a html formatter and a C# formatter. And then you map the command for every plugin to the same key, but with a differnt context (see the link).
Greets
try apt-file. It is difficult to remember the package name where the missing file resides. It is generic and useful for any package files.
For example:
root@ubuntu234:~/auto# apt-file search --regexp '/Python.h$'
pypy-dev: /usr/lib/pypy/include/Python.h
python2.7-dbg: /usr/include/python2.7_d/Python.h
python2.7-dev: /usr/include/python2.7/Python.h
python3.2-dbg: /usr/include/python3.2dmu/Python.h
python3.2-dev: /usr/include/python3.2mu/Python.h
root@ubuntu234:~/auto#
Now you can make an expert guess as to which one to choose from.
Some people might be experiencing a solid line. I got around this by adding android:layerType="software"
to the view referencing the drawable.
<context:property-placeholder ... />
is the XML equivalent to the PropertyPlaceholderConfigurer. So, prefer that. The <util:properties/>
simply factories a java.util.Properties instance that you can inject.
In Spring 3.1 (not 3.0...) you can do something like this:
@Configuration
@PropertySource("/foo/bar/services.properties")
public class ServiceConfiguration {
@Autowired Environment environment;
@Bean public javax.sql.DataSource dataSource( ){
String user = this.environment.getProperty("ds.user");
...
}
}
In Spring 3.0, you can "access" properties defined using the PropertyPlaceHolderConfigurer mechanism using the SpEl annotations:
@Value("${ds.user}") private String user;
If you want to remove the XML all together, simply register the PropertyPlaceholderConfigurer manually using Java configuration. I prefer the 3.1 approach. But, if youre using the Spring 3.0 approach (since 3.1's not GA yet...), you can now define the above XML like this:
@Configuration
public class MySpring3Configuration {
@Bean
public static PropertyPlaceholderConfigurer configurer() {
PropertyPlaceholderConfigurer ppc = ...
ppc.setLocations(...);
return ppc;
}
@Bean
public class DataSource dataSource(
@Value("${ds.user}") String user,
@Value("${ds.pw}") String pw,
...) {
DataSource ds = ...
ds.setUser(user);
ds.setPassword(pw);
...
return ds;
}
}
Note that the PPC is defined using a static
bean definition method. This is required to make sure the bean is registered early, because the PPC is a BeanFactoryPostProcessor
- it can influence the registration of the beans themselves in the context, so it necessarily has to be registered before everything else.
Consider the Switch Function as an alternative to multiple IIf()
expressions. It will return the value from the first expression/value pair where the expression evaluates as True, and ignore any remaining pairs. The concept is similar to the SELECT ... CASE
approach you referenced but which is not available in Access SQL.
If you want to display a calculated field as commission
:
SELECT
Switch(
OpeningBalance < 5001, 20,
OpeningBalance < 10001, 30,
OpeningBalance < 20001, 40,
OpeningBalance >= 20001, 50
) AS commission
FROM YourTable;
If you want to store that calculated value to a field named commission
:
UPDATE YourTable
SET commission =
Switch(
OpeningBalance < 5001, 20,
OpeningBalance < 10001, 30,
OpeningBalance < 20001, 40,
OpeningBalance >= 20001, 50
);
Either way, see whether you find Switch()
easier to understand and manage. Multiple IIf()s
can become mind-boggling as the number of conditions grows.
I had to do a lot of settings edits like the previous answers, so I don't know which made it work after a lot of modifications.
Nothing worked until I closed and openen my IDE, but the last three things I did was disable the lonefy.vscode-js-css-html-formatter
, "html.format.enable": true,
and restart Visual Studio.
{
"editor.suggestSelection": "first",
"vsintellicode.modify.editor.suggestSelection": "automaticallyOverrodeDefaultValue",
"workbench.colorTheme": "Default Light+",
"[html]": {
"editor.defaultFormatter": "vscode.html-language-features",
"editor.tabSize": 2,
"editor.detectIndentation": false,
"editor.insertSpaces": true
},
"typescript.format.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces": true,
"editor.tabSize": 2,
"typescript.format.insertSpaceAfterConstructor": true,
"files.autoSave": "afterDelay",
"html.format.indentHandlebars": true,
"html.format.indentInnerHtml": true,
"html.format.enable": true,
"editor.detectIndentation": false,
"editor.insertSpaces": true,
}
Zero and None both treated as same for if block, below code should work fine.
if number or number==0:
return True
In ViewDidLoad method of ViewController.m
UIBarButtonItem *cancel = [[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStyleBordered target:self action:@selector(back)];
[self.navigationItem setLeftBarButtonItem:cancel];
"(back)" selector is a method to dissmiss the current ViewController
If it's just once, you shouldn't alter your style sheet.
Just edit that particular td
:
<td style="text-align: center;">
Cheers
This should do the trick - setting the inline style to normal for zoom:
$('div').attr("style", "zoom:normal;");
in case your Latitude and Longitude lists are large and lazily loaded:
from itertools import izip
for lat, lon in izip(latitudes, longitudes):
process(lat, lon)
or if you want to avoid the for-loop
from itertools import izip, imap
out = imap(process, izip(latitudes, longitudes))
I wrestled with this problem and implemented the URL concatenation solution contributed by @Kushan in the accepted answer above. It worked in my local MySql instance. But when I deployed my Play/Scala app to Heroku it no longer would work. Heroku also concatenates several args to the DB URL that they provide users, and this solution, because of Heroku's use concatenation of "?" before their own set of args, will not work. However I found a different solution which seems to work equally well.
SET sql_mode = 'NO_ZERO_DATE';
I put this in my table descriptions and it solved the problem of '0000-00-00 00:00:00' can not be represented as java.sql.Timestamp
This should work for both strings and unicode objects in Python2, and both strings and bytes in Python3:
# python <3.0
def only_numerics(seq):
return filter(type(seq).isdigit, seq)
# python =3.0
def only_numerics(seq):
seq_type= type(seq)
return seq_type().join(filter(seq_type.isdigit, seq))
I found that I had to use:
npm uninstall @ionic/cli
to stop ionic from still being active.