Try the following :
Make sure you add M2_HOME
variable to your environment variables. It looks like you might have set M2_HOME
temporarily in a cmd
window and not as a permanent environment variable. Also append M2_HOME
to the PATH
variable.
Go to the m2
folder in your user directory.
Example: On Windows, for user bot
, the .m2
directory will be under C:\Users\bot
. Look for the settings.xml
file in this directory and look for the repository url within this file. See if you are able to hit this url from your browser. If not, you probably need to point to a different maven repository or use a proxy.
If you are able to hit the repository url from the browser, then check if the repository contains the maven-resource-plugin
version 2.6. This can be found by navigating to org.apache.maven.plugins
folder in the browser. It's possible that your pom
has hard-coded the dependency of the plugin to 2.6 but it is not available in the repository. This can be fixed by changing the depndency version to the one available in the repository.
Try this:
$('input[name=Comanda]')
.click(
function ()
{
$(this).hide();
}
);
For doing everything else you can use something like this one:
$('input[name=Comanda]')
.click(
function ()
{
$(this).hide();
$(".ClassNameOfShouldBeHiddenElements").hide();
}
);
For hidding any other elements based on their IDs, use this one:
$('input[name=Comanda]')
.click(
function ()
{
$(this).hide();
$("#FirstElement").hide();
$("#SecondElement").hide();
$("#ThirdElement").hide();
}
);
The answer to your problem is easy: replace the current Fragment
with the new Fragment
and push transaction onto the backstack. This preserves back button behaviour...
Creating a new Activity
really defeats the whole purpose to use fragments anyway...very counter productive.
@Override
public void onClick(View v) {
// Create new fragment and transaction
Fragment newFragment = new chartsFragment();
// consider using Java coding conventions (upper first char class names!!!)
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
http://developer.android.com/guide/components/fragments.html#Transactions
str.replace(/^.+?\"|^.|\".+/, '');
This is sometimes bad to use when you wanna select what else to remove between "" and you cannot use it more than twice in one string. All it does is select whatever is not in between "" and replace it with nothing.
Even for me it is a bit confusing, but ill try to explain it. ^.+?
(not anything OPTIONAL) till first "
then |
Or/stop (still researching what it really means) till/at ^.
has selected nothing until before the 2nd "
using (|
stop/at). And select all that comes after with .+.
I was also facing this issue
Error- Windows cannot find 'http://127.0.01:%HTTPPORT%/apex/f?p=4950'. Make sure you typed the name correctly, and then try again
After some research work, I found out that my HTTPPORT
ie. 8080
was occupied by Apace HTTP Server
and hence connection by OracleServiceXE
could not be established.
What I did to solve this issue was :
Apache2.4
and manually stopped it to free my 8080
port.Start Database
, and I received message : The OracleServiceXE service is starting.............. The OracleServiceXE service was started successfully.
http://127.0.0.1:8080/apex/f?p=4950
url to my browser which auto redirected me to http://127.0.0.1:8080/apex/f?p=4950:1:3763261197573303
That's it my issue got resolved.
In order to remember this new url and make sure that next time whenever I hit Get Started
I should be redirected to http://127.0.0.1:8080/apex/f?p=4950:1:3763261197573303
instead of http://127.0.0.1:8080/apex/f?p=4950
, what I did was :
Directory:\OracleDatabase\app\oracle\product\11.2.0\server
and search for Get_Started.html
.Get_Started.html
and select Properties
Apply
Hope this Helps.
The function example:
func file_is_exists(f string) bool {
_, err := os.Stat(f)
if os.IsNotExist(err) {
return false
}
return err == nil
}
Using ==
might be dangerous.
Note, that it would cast the variable to another data type if the two differs.
Examples:
echo (1 == '1') ? 'true' : 'false';
echo (1 == true) ? 'true' : 'false';
As you can see, these two are from different types, but the result is true
, which might not be what your code will expect.
Using ===
, however, is recommended as test shows that it's a bit faster than strcmp()
and its case-insensitive alternative strcasecmp()
.
Quick googling yells this speed comparison: http://snipplr.com/view/758/
Indexed fields (fields with numerical keys) are stored as a holy array inside the object. Therefore lookup time is O(1)
Same for a lookup array it's O(1)
Iterating through an array of objects and testing their ids against the provided one is a O(n) operation.
The data from the request (content, inputs, files, querystring values) is all on this object HttpContext.Current.Request
To read the posted content
StreamReader reader = new StreamReader(HttpContext.Current.Request.InputStream);
string requestFromPost = reader.ReadToEnd();
To navigate through the all inputs
foreach (string key in HttpContext.Current.Request.Form.AllKeys)
{
string value = HttpContext.Current.Request.Form[key];
}
Try this:
dt.Rows[RowNumber]["ColumnName"] = "Your value"
For example: if you want to add value 5 (number 5) to 1st row and column name "index" you would do this
dt.Rows[0]["index"] = 5;
I believe DataTable row starts with 0
git diff branch_1..branch_2
That will produce the diff between the tips of the two branches. If you'd prefer to find the diff from their common ancestor to test, you can use three dots instead of two:
git diff branch_1...branch_2
I found that only adding padding-top
pushed down the grey dropdown arrow box on the right, which was undesirable.
The method that worked for me was to go into the inspector and incrementally add padding
until the text was centered. This will also reduce the size of the dropdown icon, but it will be centered as well so it isn't as visually disturbing.
Solution Steps:
Unchecked "Automatically manage signing".
Select "Provisioning profile" in "Signing (Release)" section.
No signing certificate error will be show.
Then below the error has a "Manage Certificates" button. click the button.
What class do you have on the image tag?
Try this
<img src="/images/myimage.jpg" style="border:none;" alt="my image" />
For getting the buffer size in c/c++ program the following is the flow
int n;
unsigned int m = sizeof(n);
int fdsocket;
fdsocket = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP); // example
getsockopt(fdsocket,SOL_SOCKET,SO_RCVBUF,(void *)&n, &m);
// now the variable n will have the socket size
You check if it's null
in C# like this:
if(MyObject != null) {
//do something
}
If you want to check against default (tough to understand the question on the info given) check:
if(MyObject != default(MyObject)) {
//do something
}
I see lots of interesting ideas. But try my idea. Pipe your text into this:
rev | tr '\n' '~' | rev | tr '~' '\n'
which assumes that the character '~' is not in the file. This should work on every UNIX shell going back to 1961. Or something like that.
Download Git on Msys. Then:
git clone git://project.url.here
Just to add some more empirical info, I have been investigating the whole issue of upgradable locks, and Example for boost shared_mutex (multiple reads/one write)? is a good answer adding the important info that only one thread can have an upgrade_lock even if it is not upgraded, that is important as it means you cannot upgrade from a shared lock to a unique lock without releasing the shared lock first. (This has been discussed elsewhere but the most interesting thread is here http://thread.gmane.org/gmane.comp.lib.boost.devel/214394)
However I did find an important (undocumented) difference between a thread waiting for an upgrade to a lock (ie needs to wait for all readers to release the shared lock) and a writer lock waiting for the same thing (ie a unique_lock).
The thread that is waiting for a unique_lock on the shared_mutex blocks any new readers coming in, they have to wait for the writers request. This ensures readers do not starve writers (however I believe writers could starve readers).
The thread that is waiting for an upgradeable_lock to upgrade allows other threads to get a shared lock, so this thread could be starved if readers are very frequent.
This is an important issue to consider, and probably should be documented.
This code- (sets currency to GB(Britain/UK/England/£) then prints a line. Then sets currency to US/$ and prints a line)
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB",false);
Console.WriteLine("bbbbbbb {0:c}",4321.2);
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US",false);
Console.WriteLine("bbbbbbb {0:c}",4321.2);
Will display-
bbbbbbb £4,321.20
bbbbbbb $4,321.20
For a list of culture names e.g. en-GB en-US e.t.c.
http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo(v=vs.80).aspx
When you open a file with the name address.csv
, you are telling the open()
function that your file is in the current working directory. This is called a relative path.
To give you an idea of what that means, add this to your code:
import os
cwd = os.getcwd() # Get the current working directory (cwd)
files = os.listdir(cwd) # Get all the files in that directory
print("Files in %r: %s" % (cwd, files))
That will print the current working directory along with all the files in it.
Another way to tell the open()
function where your file is located is by using an absolute path, e.g.:
f = open("/Users/foo/address.csv")
Using
try:
with open("path", "r") as file:#or just open
may cause some troubles when file is opened by some other processes (i.e. user opened it manually). You can solve your poblem using win32com library. Below code checks if any excel files are opened and if none of them matches the name of your particular one, openes a new one.
import win32com.client as win32
xl = win32.gencache.EnsureDispatch('Excel.Application')
my_workbook = "wb_name.xls"
xlPath="my_wb_path//" + my_workbook
if xl.Workbooks.Count > 0:
# if none of opened workbooks matches the name, openes my_workbook
if not any(i.Name == my_workbook for i in xl.Workbooks):
xl.Workbooks.Open(Filename=xlPath)
xl.Visible = True
#no workbooks found, opening
else:
xl.Workbooks.Open(Filename=xlPath)
xl.Visible = True
'xl.Visible = True is not necessary, used just for convenience'
Hope this will help
For some purposes, HtmlUtils:
import org.springframework.web.util.HtmlUtils;
[...]
HtmlUtils.htmlEscapeDecimal("&"); //gives &
HtmlUtils.htmlEscape("&"); //gives &
As jQuery won't trigger native change event but only triggers its own change event. If you bind event without jQuery and then use jQuery to trigger it the callbacks you bound won't run !
The solution is then like below (100% working) :
var sortBySelect = document.querySelector("select.your-class");
sortBySelect.value = "new value";
sortBySelect.dispatchEvent(new Event("change"));
<div class="preload">
<img src="http://i.imgur.com/KUJoe.gif">
</div>
<div class="content">
I would like to display a loading bar before the entire page is loaded.
</div>
$(function() {
$(".preload").fadeOut(2000, function() {
$(".content").fadeIn(1000);
});
});?
.content {display:none;}
.preload {
width:100px;
height: 100px;
position: fixed;
top: 50%;
left: 50%;
}
?
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]
Notes: Make sure you have done the following steps
- sudo a2enmod rewrite
- sudo service apache2 restart
- Add Following in your vhost file, located at /etc/apache2/sites-available/000-default.conf
<Directory /var/www/html>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
Require all granted
</Directory>
Now your .htaccess will work and your site will redirect to http:// to https://www
In Rails you can print the result in the View by using the debug' Helper ActionView::Helpers::DebugHelper
#app/view/controllers/post_controller.rb
def index
@posts = Post.all
end
#app/view/posts/index.html.erb
<%= debug(@posts) %>
#start your server
rails -s
results (in browser)
- !ruby/object:Post
raw_attributes:
id: 2
title: My Second Post
body: Welcome! This is another example post
published_at: '2015-10-19 23:00:43.469520'
created_at: '2015-10-20 00:00:43.470739'
updated_at: '2015-10-20 00:00:43.470739'
attributes: !ruby/object:ActiveRecord::AttributeSet
attributes: !ruby/object:ActiveRecord::LazyAttributeHash
types: &5
id: &2 !ruby/object:ActiveRecord::Type::Integer
precision:
scale:
limit:
range: !ruby/range
begin: -2147483648
end: 2147483648
excl: true
title: &3 !ruby/object:ActiveRecord::Type::String
precision:
scale:
limit:
body: &4 !ruby/object:ActiveRecord::Type::Text
precision:
scale:
limit:
published_at: !ruby/object:ActiveRecord::AttributeMethods::TimeZoneConversion::TimeZoneConverter
subtype: &1 !ruby/object:ActiveRecord::Type::DateTime
precision:
scale:
limit:
created_at: !ruby/object:ActiveRecord::AttributeMethods::TimeZoneConversion::TimeZoneConverter
subtype: *1
updated_at: !ruby/object:ActiveRecord::AttributeMethods::TimeZoneConversion::TimeZoneConverter
subtype: *1
Invoking dev.off()
to make RStudio open up a new graphics device with default settings worked for me. HTH.
You can change the color of the text in the toolbar with these:
<item name="android:textColorPrimary">#FFFFFF</item>
<item name="android:textColor">#FFFFFF</item>
$('form :input').change(function() {
// Something has changed
});
That error also shows when the video has played fine and the script will finish but that error always throws because the imshow() will get empty frames after all frames have been consumed.
That is especially the case if you are playing a short (few sec) video file and you don't notice that the video actually played on the background (behind your code editor) and after that the script ends with that error.
Late to this one, but I just discovered an alternative way of doing it:
On your template,
<a (click)="navigateAssociates()">Associates</a>
And on your component.ts, you can use serializeUrl
to convert the route into a string, which can be used with window.open()
navigateAssociates() {
const url = this.router.serializeUrl(
this.router.createUrlTree(['/page1'])
);
window.open(url, '_blank');
}
I ran into the same issue. What I needed to do was add a reference at the top of the class and change the CultureInfo of the thread that is currently executing.
using System.Threading;
string cultureName = "fr-CA";
Thread.CurrentThread.CurrentCulture = new CultureInfo(cultureName);
DateTime theDate = new DateTime(2015, 11, 06);
theDate.ToString("g");
Console.WriteLine(theDate);
All you have to do is change the culture name, for example: "en-US" = United States "fr-FR" = French-speaking France "fr-CA" = French-speaking Canada etc...
You can solve your problem like below bunch of codes
public class Response
{
public string loopa { get; set; }
public string drupa{ get; set; }
public Image[] images { get; set; }
}
public class RootObject<T>
{
public List<T> response{ get; set; }
}
var des = (RootObject<Response>)Newtonsoft.Json.JsonConvert.DeserializeObject(Your JSon String, typeof(RootObject<Response>));
For me none of the other answers worked because I am using the latest version of MaterializeCSS and Meteor and there is incompatability between the jquery versions, Meteor 1.1.10 uses jquery 1.11 (overriding this dependancy is not easy and will probably break Meteor/Blaze) and testing Materialise with jquery 2.2 works fine. See https://stackoverflow.com/a/34809976/2882279 for more info.
This is a known issue with dropdowns and selects in materialize 0.97.2 and 0.97.3; for more info see https://github.com/Dogfalo/materialize/issues/2265 and https://github.com/Dogfalo/materialize/commit/45feae64410252fe51e56816e664c09d83dc8931.
I'm using the Sass version of MaterializeCSS in Meteor and worked around the problem by using poetic:[email protected] in my meteor packages file to force the old version. The dropdowns now work, old jquery and all!
Let me add a little to Sebastian Roth's answer.
Your project can be compiled by using ndk-build
in the command line after adding the code Sebastian had posted. But as for me, there were syntax errors in Eclipse, and I didn't have code completion.
Note that your project must be converted to a C/C++ project.
How to convert a C/C++ project
To fix this issue right-click on your project, click Properties
Choose C/C++ General -> Paths and Symbols and include the ${ANDROID_NDK}/sources/cxx-stl/stlport/stlport
to Include directories
Click Yes when a dialog shows up.
Before
After
Update #1
GNU C. Add directories, rebuild. There won't be any errors in C source files
GNU C++. Add directories, rebuild. There won't be any errors in CPP source files.
I think you need to update your libraries so that your VBA code works, your using ms outlook
file = open('Failed.py', 'w')
file.write('whatever')
file.close()
Here is a more pythonic version, which automatically closes the file, even if there was an exception in the wrapped block:
with open('Failed.py', 'w') as file:
file.write('whatever')
You are lucky that you didn't complete the rebase, so you can still do git rebase --abort
. If you had completed the rebase (it rewrites history), things would have been much more complex. Consider tagging the tips of branches before doing potentially damaging operations (particularly history rewriting), that way you can rewind if something blows up.
It is safe unless you overloaded the delete operator. if you overloaded the delete operator and not handling null condition then it is not safe at all.
Also you can try this:
MultivaluedMap formData = new MultivaluedMapImpl();
formData.add("name1", "val1");
formData.add("name2", "val2");
webResource.path("yourJerseysPathPost").queryParams(formData).post();
"Deceptively simple task." – Potatoswatter
Indeed. There's many little devils hanging out in the details of this problem. It was very fun to solve tho.
EDIT: This update takes a much more compositional approach. Previously there was one big function which wrapped a couple other proprietary functions. Instead, this time we define generic reusable functions which could be used for many varieties of tasks. More about those after we take a look at numToWords
itself …
// numToWords :: (Number a, String a) => a -> String
let numToWords = n => {
let a = [
'', 'one', 'two', 'three', 'four',
'five', 'six', 'seven', 'eight', 'nine',
'ten', 'eleven', 'twelve', 'thirteen', 'fourteen',
'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'
];
let b = [
'', '', 'twenty', 'thirty', 'forty',
'fifty', 'sixty', 'seventy', 'eighty', 'ninety'
];
let g = [
'', 'thousand', 'million', 'billion', 'trillion', 'quadrillion',
'quintillion', 'sextillion', 'septillion', 'octillion', 'nonillion'
];
// this part is really nasty still
// it might edit this again later to show how Monoids could fix this up
let makeGroup = ([ones,tens,huns]) => {
return [
num(huns) === 0 ? '' : a[huns] + ' hundred ',
num(ones) === 0 ? b[tens] : b[tens] && b[tens] + '-' || '',
a[tens+ones] || a[ones]
].join('');
};
// "thousands" constructor; no real good names for this, i guess
let thousand = (group,i) => group === '' ? group : `${group} ${g[i]}`;
// execute !
if (typeof n === 'number') return numToWords(String(n));
if (n === '0') return 'zero';
return comp (chunk(3)) (reverse) (arr(n))
.map(makeGroup)
.map(thousand)
.filter(comp(not)(isEmpty))
.reverse()
.join(' ');
};
Here are the dependencies:
You'll notice these require next to no documentation because their intents are immediately clear. chunk
might be the only one that takes a moment to digest, but it's really not too bad. Plus the function name gives us a pretty good indication what it does, and it's probably a function we've encountered before.
const arr = x => Array.from(x);
const num = x => Number(x) || 0;
const str = x => String(x);
const isEmpty = xs => xs.length === 0;
const take = n => xs => xs.slice(0,n);
const drop = n => xs => xs.slice(n);
const reverse = xs => xs.slice(0).reverse();
const comp = f => g => x => f (g (x));
const not = x => !x;
const chunk = n => xs =>
isEmpty(xs) ? [] : [take(n)(xs), ...chunk (n) (drop (n) (xs))];
"So these make it better?"
Look at how the code has cleaned up significantly
// NEW CODE (truncated)
return comp (chunk(3)) (reverse) (arr(n))
.map(makeGroup)
.map(thousand)
.filter(comp(not)(isEmpty))
.reverse()
.join(' ');
// OLD CODE (truncated)
let grp = n => ('000' + n).substr(-3);
let rem = n => n.substr(0, n.length - 3);
let cons = xs => x => g => x ? [x, g && ' ' + g || '', ' ', xs].join('') : xs;
let iter = str => i => x => r => {
if (x === '000' && r.length === 0) return str;
return iter(cons(str)(fmt(x))(g[i]))
(i+1)
(grp(r))
(rem(r));
};
return iter('')(0)(grp(String(n)))(rem(String(n)));
Most importantly, the utility functions we added in the new code can be used other places in your app. This means that, as a side effect of implementing numToWords
in this way, we get the other functions for free. Bonus soda !
Some tests
console.log(numToWords(11009));
//=> eleven thousand nine
console.log(numToWords(10000001));
//=> ten million one
console.log(numToWords(987));
//=> nine hundred eighty-seven
console.log(numToWords(1015));
//=> one thousand fifteen
console.log(numToWords(55111222333));
//=> fifty-five billion one hundred eleven million two hundred
// twenty-two thousand three hundred thirty-three
console.log(numToWords("999999999999999999999991"));
//=> nine hundred ninety-nine sextillion nine hundred ninety-nine
// quintillion nine hundred ninety-nine quadrillion nine hundred
// ninety-nine trillion nine hundred ninety-nine billion nine
// hundred ninety-nine million nine hundred ninety-nine thousand
// nine hundred ninety-one
console.log(numToWords(6000753512));
//=> six billion seven hundred fifty-three thousand five hundred
// twelve
Runnable demo
const arr = x => Array.from(x);_x000D_
const num = x => Number(x) || 0;_x000D_
const str = x => String(x);_x000D_
const isEmpty = xs => xs.length === 0;_x000D_
const take = n => xs => xs.slice(0,n);_x000D_
const drop = n => xs => xs.slice(n);_x000D_
const reverse = xs => xs.slice(0).reverse();_x000D_
const comp = f => g => x => f (g (x));_x000D_
const not = x => !x;_x000D_
const chunk = n => xs =>_x000D_
isEmpty(xs) ? [] : [take(n)(xs), ...chunk (n) (drop (n) (xs))];_x000D_
_x000D_
// numToWords :: (Number a, String a) => a -> String_x000D_
let numToWords = n => {_x000D_
_x000D_
let a = [_x000D_
'', 'one', 'two', 'three', 'four',_x000D_
'five', 'six', 'seven', 'eight', 'nine',_x000D_
'ten', 'eleven', 'twelve', 'thirteen', 'fourteen',_x000D_
'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'_x000D_
];_x000D_
_x000D_
let b = [_x000D_
'', '', 'twenty', 'thirty', 'forty',_x000D_
'fifty', 'sixty', 'seventy', 'eighty', 'ninety'_x000D_
];_x000D_
_x000D_
let g = [_x000D_
'', 'thousand', 'million', 'billion', 'trillion', 'quadrillion',_x000D_
'quintillion', 'sextillion', 'septillion', 'octillion', 'nonillion'_x000D_
];_x000D_
_x000D_
// this part is really nasty still_x000D_
// it might edit this again later to show how Monoids could fix this up_x000D_
let makeGroup = ([ones,tens,huns]) => {_x000D_
return [_x000D_
num(huns) === 0 ? '' : a[huns] + ' hundred ',_x000D_
num(ones) === 0 ? b[tens] : b[tens] && b[tens] + '-' || '',_x000D_
a[tens+ones] || a[ones]_x000D_
].join('');_x000D_
};_x000D_
_x000D_
let thousand = (group,i) => group === '' ? group : `${group} ${g[i]}`;_x000D_
_x000D_
if (typeof n === 'number')_x000D_
return numToWords(String(n));_x000D_
else if (n === '0')_x000D_
return 'zero';_x000D_
else_x000D_
return comp (chunk(3)) (reverse) (arr(n))_x000D_
.map(makeGroup)_x000D_
.map(thousand)_x000D_
.filter(comp(not)(isEmpty))_x000D_
.reverse()_x000D_
.join(' ');_x000D_
};_x000D_
_x000D_
_x000D_
console.log(numToWords(11009));_x000D_
//=> eleven thousand nine_x000D_
_x000D_
console.log(numToWords(10000001));_x000D_
//=> ten million one _x000D_
_x000D_
console.log(numToWords(987));_x000D_
//=> nine hundred eighty-seven_x000D_
_x000D_
console.log(numToWords(1015));_x000D_
//=> one thousand fifteen_x000D_
_x000D_
console.log(numToWords(55111222333));_x000D_
//=> fifty-five billion one hundred eleven million two hundred _x000D_
// twenty-two thousand three hundred thirty-three_x000D_
_x000D_
console.log(numToWords("999999999999999999999991"));_x000D_
//=> nine hundred ninety-nine sextillion nine hundred ninety-nine_x000D_
// quintillion nine hundred ninety-nine quadrillion nine hundred_x000D_
// ninety-nine trillion nine hundred ninety-nine billion nine_x000D_
// hundred ninety-nine million nine hundred ninety-nine thousand_x000D_
// nine hundred ninety-one_x000D_
_x000D_
console.log(numToWords(6000753512));_x000D_
//=> six billion seven hundred fifty-three thousand five hundred_x000D_
// twelve
_x000D_
You can transpile the code using babel.js if you want to see the ES5 variant
(i === 0 ? "true" : "false")
Exporting without default
means it's a "named export". You can have multiple named exports in a single file. So if you do this,
class Template {}
class AnotherTemplate {}
export { Template, AnotherTemplate }
then you have to import these exports using their exact names. So to use these components in another file you'd have to do,
import {Template, AnotherTemplate} from './components/templates'
Alternatively if you export as the default
export like this,
export default class Template {}
Then in another file you import the default export without using the {}
, like this,
import Template from './components/templates'
There can only be one default export per file. In React it's a convention to export one component from a file, and to export it is as the default export.
You're free to rename the default export as you import it,
import TheTemplate from './components/templates'
And you can import default and named exports at the same time,
import Template,{AnotherTemplate} from './components/templates'
In Ubuntu In the conf file: /etc/apache2/sites-enabled/your-file.conf
change
AddHandler application/x-httpd-php .js .xml .htc .css
to:
AddHandler application/x-httpd-php .js .xml .htc
If, after reading the other questions and viewing the links mentioned in the comment sections, you still can't figure it out, read on.
First of all, where you're going wrong is the offset.
It should look more like this...
set mydate=%date:~10,4%%date:~6,2%/%date:~4,2%
echo %mydate%
If the date was Tue 12/02/2013
then it would display it as 2013/02/12
.
To remove the slashes, the code would look more like
set mydate=%date:~10,4%%date:~7,2%%date:~4,2%
echo %mydate%
which would output 20130212
And a hint for doing it in the future, if mydate
equals something like %date:~10,4%%date:~7,2%
or the like, you probably forgot a tilde (~).
If you want to add plots to your Jupyter notebook, then %matplotlib inline
is a standard solution. And there are other magic commands will use matplotlib
interactively within Jupyter.
%matplotlib
: any plt
plot command will now cause a figure window to open, and further commands can be run to update the plot. Some changes will not draw automatically, to force an update, use plt.draw()
%matplotlib notebook
: will lead to interactive plots embedded within the notebook, you can zoom and resize the figure
%matplotlib inline
: only draw static images in the notebook
I've tried different numbers, and it always acts as if the 0s aren't there and sorts the numbers correctly otherwise. Anyone know why?
You're getting a lexicographical sort (e.g. convert objects to strings, and sort them in dictionary order), which is the default sort behavior in Javascript:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort
array.sort([compareFunction])
Parameters
compareFunction
Specifies a function that defines the sort order. If omitted, the array is sorted lexicographically (in dictionary order) according to the string conversion of each element.
In the ECMAscript specification (the normative reference for the generic Javascript), ECMA-262, 3rd ed., section 15.4.4.11, the default sort order is lexicographical, although they don't come out and say it, instead giving the steps for a conceptual sort function that calls the given compare function if necessary, otherwise comparing the arguments when converted to strings:
13. If the argument comparefn is undefined, go to step 16.
14. Call comparefn with arguments x and y.
15. Return Result(14).
16. Call ToString(x).
17. Call ToString(y).
18. If Result(16) < Result(17), return -1.
19. If Result(16) > Result(17), return 1.
20. Return +0.
Actually, pretty much anywhere in typescript, passing a value to a function with a specified type will work as desired as long as the type being passed is compatible.
That being said, the following works...
fetch(`http://swapi.co/api/people/1/`)
.then(res => res.json())
.then((res: Actor) => {
// res is now an Actor
});
I wanted to wrap all of my http calls in a reusable class - which means I needed some way for the client to process the response in its desired form. To support this, I accept a callback lambda as a parameter to my wrapper method. The lambda declaration accepts an any type as shown here...
callBack: (response: any) => void
But in use the caller can pass a lambda that specifies the desired return type. I modified my code from above like this...
fetch(`http://swapi.co/api/people/1/`)
.then(res => res.json())
.then(res => {
if (callback) {
callback(res); // Client receives the response as desired type.
}
});
So that a client can call it with a callback like...
(response: IApigeeResponse) => {
// Process response as an IApigeeResponse
}
In Java 8, You can directly use this filter method and then do that.
List<String> lines = Arrays.asList("java", "pramod", "example");
List<String> result = lines.stream()
.filter(line -> !"pramod".equals(line))
.collect(Collectors.toList());
result.forEach(System.out::println);
Using LIKE:
SELECT *
FROM TABLE
WHERE column LIKE '%cats%' --case-insensitive
You could use the DirectoryInfo and FileInfo classes.
//GetFiles on DirectoryInfo returns a FileInfo object.
var pdfFiles = new DirectoryInfo("C:\\Documents").GetFiles("*.pdf");
//FileInfo has a Name property that only contains the filename part.
var firstPdfFilename = pdfFiles[0].Name;
If you declare your callback as mentioned by @lex82 like
callback = "callback(item.id, arg2)"
You can call the callback method in the directive scope with object map and it would do the binding correctly. Like
scope.callback({arg2:"some value"});
without requiring for $parse. See my fiddle(console log) http://jsfiddle.net/k7czc/2/
Update: There is a small example of this in the documentation:
& or &attr - provides a way to execute an expression in the context of the parent scope. If no attr name is specified then the attribute name is assumed to be the same as the local name. Given and widget definition of scope: { localFn:'&myAttr' }, then isolate scope property localFn will point to a function wrapper for the count = count + value expression. Often it's desirable to pass data from the isolated scope via an expression and to the parent scope, this can be done by passing a map of local variable names and values into the expression wrapper fn. For example, if the expression is increment(amount) then we can specify the amount value by calling the localFn as localFn({amount: 22}).
Nothing special. Just as same as common Java Class Instance.
But those class are Synthetic proxy classes
created by java.lang.reflect.Proxy#newProxyInstance
Introduced in 1.3
http://docs.oracle.com/javase/1.3/docs/relnotes/features.html#reflection
It is a part of Java. so each JVM should support it.
In short : they are created using JVM ASM tech ( defining javabyte code at runtime )
something using same tech:
java.lang.reflect.Proxy#newProxyInstance
getProxyClass0
to obtain a `Class
`
ProxyGenerator.generateProxyClass
which return a byte[]define class
to load the generated $Proxy
Class (the classname you have seen)each method is build with same bytecode like
invocation handler
's invoke()
invocation handler
's invoke()
the class(bytecode) represent in form of byte[]
How to draw a class
Thinking your java codes are compiled into bytecodes, just do this at runtime
core method in sun/misc/ProxyGenerator.java
generateClassFile
/**
* Generate a class file for the proxy class. This method drives the
* class file generation process.
*/
private byte[] generateClassFile() {
/* ============================================================
* Step 1: Assemble ProxyMethod objects for all methods to
* generate proxy dispatching code for.
*/
/*
* Record that proxy methods are needed for the hashCode, equals,
* and toString methods of java.lang.Object. This is done before
* the methods from the proxy interfaces so that the methods from
* java.lang.Object take precedence over duplicate methods in the
* proxy interfaces.
*/
addProxyMethod(hashCodeMethod, Object.class);
addProxyMethod(equalsMethod, Object.class);
addProxyMethod(toStringMethod, Object.class);
/*
* Now record all of the methods from the proxy interfaces, giving
* earlier interfaces precedence over later ones with duplicate
* methods.
*/
for (int i = 0; i < interfaces.length; i++) {
Method[] methods = interfaces[i].getMethods();
for (int j = 0; j < methods.length; j++) {
addProxyMethod(methods[j], interfaces[i]);
}
}
/*
* For each set of proxy methods with the same signature,
* verify that the methods' return types are compatible.
*/
for (List<ProxyMethod> sigmethods : proxyMethods.values()) {
checkReturnTypes(sigmethods);
}
/* ============================================================
* Step 2: Assemble FieldInfo and MethodInfo structs for all of
* fields and methods in the class we are generating.
*/
try {
methods.add(generateConstructor());
for (List<ProxyMethod> sigmethods : proxyMethods.values()) {
for (ProxyMethod pm : sigmethods) {
// add static field for method's Method object
fields.add(new FieldInfo(pm.methodFieldName,
"Ljava/lang/reflect/Method;",
ACC_PRIVATE | ACC_STATIC));
// generate code for proxy method and add it
methods.add(pm.generateMethod());
}
}
methods.add(generateStaticInitializer());
} catch (IOException e) {
throw new InternalError("unexpected I/O Exception");
}
if (methods.size() > 65535) {
throw new IllegalArgumentException("method limit exceeded");
}
if (fields.size() > 65535) {
throw new IllegalArgumentException("field limit exceeded");
}
/* ============================================================
* Step 3: Write the final class file.
*/
/*
* Make sure that constant pool indexes are reserved for the
* following items before starting to write the final class file.
*/
cp.getClass(dotToSlash(className));
cp.getClass(superclassName);
for (int i = 0; i < interfaces.length; i++) {
cp.getClass(dotToSlash(interfaces[i].getName()));
}
/*
* Disallow new constant pool additions beyond this point, since
* we are about to write the final constant pool table.
*/
cp.setReadOnly();
ByteArrayOutputStream bout = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(bout);
try {
/*
* Write all the items of the "ClassFile" structure.
* See JVMS section 4.1.
*/
// u4 magic;
dout.writeInt(0xCAFEBABE);
// u2 minor_version;
dout.writeShort(CLASSFILE_MINOR_VERSION);
// u2 major_version;
dout.writeShort(CLASSFILE_MAJOR_VERSION);
cp.write(dout); // (write constant pool)
// u2 access_flags;
dout.writeShort(ACC_PUBLIC | ACC_FINAL | ACC_SUPER);
// u2 this_class;
dout.writeShort(cp.getClass(dotToSlash(className)));
// u2 super_class;
dout.writeShort(cp.getClass(superclassName));
// u2 interfaces_count;
dout.writeShort(interfaces.length);
// u2 interfaces[interfaces_count];
for (int i = 0; i < interfaces.length; i++) {
dout.writeShort(cp.getClass(
dotToSlash(interfaces[i].getName())));
}
// u2 fields_count;
dout.writeShort(fields.size());
// field_info fields[fields_count];
for (FieldInfo f : fields) {
f.write(dout);
}
// u2 methods_count;
dout.writeShort(methods.size());
// method_info methods[methods_count];
for (MethodInfo m : methods) {
m.write(dout);
}
// u2 attributes_count;
dout.writeShort(0); // (no ClassFile attributes for proxy classes)
} catch (IOException e) {
throw new InternalError("unexpected I/O Exception");
}
return bout.toByteArray();
}
addProxyMethod
/**
* Add another method to be proxied, either by creating a new
* ProxyMethod object or augmenting an old one for a duplicate
* method.
*
* "fromClass" indicates the proxy interface that the method was
* found through, which may be different from (a subinterface of)
* the method's "declaring class". Note that the first Method
* object passed for a given name and descriptor identifies the
* Method object (and thus the declaring class) that will be
* passed to the invocation handler's "invoke" method for a given
* set of duplicate methods.
*/
private void addProxyMethod(Method m, Class fromClass) {
String name = m.getName();
Class[] parameterTypes = m.getParameterTypes();
Class returnType = m.getReturnType();
Class[] exceptionTypes = m.getExceptionTypes();
String sig = name + getParameterDescriptors(parameterTypes);
List<ProxyMethod> sigmethods = proxyMethods.get(sig);
if (sigmethods != null) {
for (ProxyMethod pm : sigmethods) {
if (returnType == pm.returnType) {
/*
* Found a match: reduce exception types to the
* greatest set of exceptions that can thrown
* compatibly with the throws clauses of both
* overridden methods.
*/
List<Class<?>> legalExceptions = new ArrayList<Class<?>>();
collectCompatibleTypes(
exceptionTypes, pm.exceptionTypes, legalExceptions);
collectCompatibleTypes(
pm.exceptionTypes, exceptionTypes, legalExceptions);
pm.exceptionTypes = new Class[legalExceptions.size()];
pm.exceptionTypes =
legalExceptions.toArray(pm.exceptionTypes);
return;
}
}
} else {
sigmethods = new ArrayList<ProxyMethod>(3);
proxyMethods.put(sig, sigmethods);
}
sigmethods.add(new ProxyMethod(name, parameterTypes, returnType,
exceptionTypes, fromClass));
}
Full code about gen the proxy method
private MethodInfo generateMethod() throws IOException {
String desc = getMethodDescriptor(parameterTypes, returnType);
MethodInfo minfo = new MethodInfo(methodName, desc,
ACC_PUBLIC | ACC_FINAL);
int[] parameterSlot = new int[parameterTypes.length];
int nextSlot = 1;
for (int i = 0; i < parameterSlot.length; i++) {
parameterSlot[i] = nextSlot;
nextSlot += getWordsPerType(parameterTypes[i]);
}
int localSlot0 = nextSlot;
short pc, tryBegin = 0, tryEnd;
DataOutputStream out = new DataOutputStream(minfo.code);
code_aload(0, out);
out.writeByte(opc_getfield);
out.writeShort(cp.getFieldRef(
superclassName,
handlerFieldName, "Ljava/lang/reflect/InvocationHandler;"));
code_aload(0, out);
out.writeByte(opc_getstatic);
out.writeShort(cp.getFieldRef(
dotToSlash(className),
methodFieldName, "Ljava/lang/reflect/Method;"));
if (parameterTypes.length > 0) {
code_ipush(parameterTypes.length, out);
out.writeByte(opc_anewarray);
out.writeShort(cp.getClass("java/lang/Object"));
for (int i = 0; i < parameterTypes.length; i++) {
out.writeByte(opc_dup);
code_ipush(i, out);
codeWrapArgument(parameterTypes[i], parameterSlot[i], out);
out.writeByte(opc_aastore);
}
} else {
out.writeByte(opc_aconst_null);
}
out.writeByte(opc_invokeinterface);
out.writeShort(cp.getInterfaceMethodRef(
"java/lang/reflect/InvocationHandler",
"invoke",
"(Ljava/lang/Object;Ljava/lang/reflect/Method;" +
"[Ljava/lang/Object;)Ljava/lang/Object;"));
out.writeByte(4);
out.writeByte(0);
if (returnType == void.class) {
out.writeByte(opc_pop);
out.writeByte(opc_return);
} else {
codeUnwrapReturnValue(returnType, out);
}
tryEnd = pc = (short) minfo.code.size();
List<Class<?>> catchList = computeUniqueCatchList(exceptionTypes);
if (catchList.size() > 0) {
for (Class<?> ex : catchList) {
minfo.exceptionTable.add(new ExceptionTableEntry(
tryBegin, tryEnd, pc,
cp.getClass(dotToSlash(ex.getName()))));
}
out.writeByte(opc_athrow);
pc = (short) minfo.code.size();
minfo.exceptionTable.add(new ExceptionTableEntry(
tryBegin, tryEnd, pc, cp.getClass("java/lang/Throwable")));
code_astore(localSlot0, out);
out.writeByte(opc_new);
out.writeShort(cp.getClass(
"java/lang/reflect/UndeclaredThrowableException"));
out.writeByte(opc_dup);
code_aload(localSlot0, out);
out.writeByte(opc_invokespecial);
out.writeShort(cp.getMethodRef(
"java/lang/reflect/UndeclaredThrowableException",
"<init>", "(Ljava/lang/Throwable;)V"));
out.writeByte(opc_athrow);
}
Your csv is malformed. The output is not three loopings but just one output. To ensure that this is a single loop, add a counter and increment it with every loop. It should only count to one.
This is what your code sees
0,Filipe,19,M\n1,Maria,20,F\n2,Walter,60,M
Try this
0,Filipe,19,M
1,Maria,20,F
2,Walter,60,M
while(file.good())
{
getline(file, ID, ',');
cout << "ID: " << ID << " " ;
getline(file, nome, ',') ;
cout << "User: " << nome << " " ;
getline(file, idade, ',') ;
cout << "Idade: " << idade << " " ;
getline(file, genero) ; \\ diff
cout << "Sexo: " << genero;\\diff
}
The camprocessor available on Sourceforge.net will do xml test case generation for any XSD. There is a tutorial available to show you how to generate your own test examples - including using content hints to ensure realistic examples, not just random junk ones.
The tutorial is available here: http://www.oasis-open.org/committees/download.php/29661/XSD%20and%20jCAM%20tutorial.pdf
And more information on the tool - which is using the OASIS Content Assembly Mechanism (CAM) standard to refactor your XSD into a more XSLT friendly structure - can be found from the resource website - http://www.jcam.org.uk
Enjoy, DW
you can use this
List<Car> requiredCars = cars.stream()
.filter (t-> t!= null && StringUtils.startsWith(t.getName(),"M"))
.collect(Collectors.toList());
Poor man's string trim (spaces only):
std::string trimSpaces(const std::string& str)
{
int start, len;
for (start = 0; start < str.size() && str[start] == ' '; start++);
for (len = str.size() - start; len > 0 && str[start + len - 1] == ' '; len--);
return str.substr(start, len);
}
You don't need underscore, just use built-in map:
var string = 'Hello World!';_x000D_
_x000D_
document.write(string.split('').map(function(c) { return c.charCodeAt(); }));
_x000D_
If you use Express 4.x, you can use the req.get(headerName)
method as described in Express 4.x API Reference
The other methods are all good. However, if you prefer to not specify the field (e.g. for some dynamic method), you can use this:
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['email'].widget.attrs['placeholder'] = self.fields['email'].label or '[email protected]'
It also allows the placeholder to depend on the instance for ModelForms with instance specified.
Just the thread.
I do not find NoControlUpgrade=1
on my vbp project.
Instead, I develop on both xp and windows7 x64. When I moved the project from window 7 to xp, the error occurred.
From what I find out, these are different:
Object={831FDD16-0C5C-11D2-A9FC-0000F8754DA1}#2.0#0; MSCOMCTL.OCX
Object={831FDD16-0C5C-11D2-A9FC-0000F8754DA1}#2.1#0; MSCOMCTL.OCX
I just changed the #2,1
back to #2.0
on the vbp file and it can run immediately.
These kind of problems occurred before, so hope Microsoft explain and solve them accordingly.
Thanks.
For completeness' sake, don't forget std::string::copy()
.
std::string str = "string";
const size_t MAX = 80;
char chrs[MAX];
str.copy(chrs, MAX);
std::string::copy()
doesn't NUL terminate. If you need to ensure a NUL terminator for use in C string functions:
std::string str = "string";
const size_t MAX = 80;
char chrs[MAX];
memset(chrs, '\0', MAX);
str.copy(chrs, MAX-1);
The advantage of a wordier approach comes when your code is inside a 300,000 line project.
Using the action, as you have, there is no way to tell me what bool, int, and Blah are. If your action passed an object that defined the parameters then ok.
Using an EventHandler that wanted an EventArgs and if you would complete your DiagnosticsArgs example with getters for the properties that commented their purpose then you application would be more understandable. Also, please comment or fully name the arguments in the DiagnosticsArgs constructor.
For your purpose you can use this snnippet:
import org.apache.commons.lang3.StringUtils;
StringUtils.normalizeSpace(string);
This will normalize the spacing to single and will strip off the starting and trailing whitespaces as well.
String sampleString = "Hello world!";
sampleString.replaceAll("\\s{2}", " "); // replaces exactly two consecutive spaces
sampleString.replaceAll("\\s{2,}", " "); // replaces two or more consecutive white spaces
Consider building an Add-on that has an actual button and not using the outdated method of linking an image to a script function.
In the script editor, under the Help menu >> Welcome Screen >> link to Google Sheets Add-on - will give you sample code to use.
I use two methods for relative sizing. I have a class called Relative
with three attached properties To
, WidthPercent
and HeightPercent
which is useful if I want an element to be a relative size of an element anywhere in the visual tree and feels less hacky than the converter approach - although use what works for you, that you're happy with.
The other approach is rather more cunning. Add a ViewBox
where you want relative sizes inside, then inside that, add a Grid
at width 100. Then if you add a TextBlock
with width 10 inside that, it is obviously 10% of 100.
The ViewBox
will scale the Grid
according to whatever space it has been given, so if its the only thing on the page, then the Grid
will be scaled out full width and effectively, your TextBlock
is scaled to 10% of the page.
If you don't set a height on the Grid
then it will shrink to fit its content, so it'll all be relatively sized. You'll have to ensure that the content doesn't get too tall, i.e. starts changing the aspect ratio of the space given to the ViewBox
else it will start scaling the height as well. You can probably work around this with a Stretch
of UniformToFill
.
Yes, mysql_fetch_array()
only returns one result. If you want to retrieve more than one row, you need to put the function call in a while
loop.
Two examples:
This will only return the first row
$row = mysql_fetch_array($result);
This will return one row on each loop, until no more rows are available from the result set
while($row = mysql_fetch_array($result))
{
//Do stuff with contents of $row
}
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(foo);
foreach (PropertyDescriptor property in properties)
{
if (property.Name == "Name")
{
Console.WriteLine(property.DisplayName); // Something To Name
}
}
where foo
is an instance of Class1
"Initialized from the environment variable PYTHONPATH, plus an installation-dependent default"
I prefer use a function this way.
DELIMITER $$ DROP FUNCTION IF EXISTS `db`.`F_AGE` $$
CREATE FUNCTION `F_AGE`(in_dob datetime) RETURNS int(11)
NO SQL
BEGIN
DECLARE l_age INT;
IF DATE_FORMAT(NOW( ),'00-%m-%d') >= DATE_FORMAT(in_dob,'00-%m-%d') THEN
-- This person has had a birthday this year
SET l_age=DATE_FORMAT(NOW( ),'%Y')-DATE_FORMAT(in_dob,'%Y');
ELSE
-- Yet to have a birthday this year
SET l_age=DATE_FORMAT(NOW( ),'%Y')-DATE_FORMAT(in_dob,'%Y')-1;
END IF;
RETURN(l_age);
END $$
DELIMITER ;
now to use
SELECT F_AGE('1979-02-11') AS AGE;
OR
SELECT F_AGE(date) AS age FROM table;
use Illuminate\Support\Facades\Route;
Warning Disappeared after importing the corresponding namespace.
Version's
i'll throw in my 2 cents because i didn't see an answer that resolved my issue.
my particular use case, relates to starting a legacy rails application using ruby 2.6.3 with postgres 10.x series.
haven't started the rails app in several months, needed to perform some maintenance on the app today and, got some lovely ? error messages below,
9): Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib (LoadError)
Referenced from: /usr/local/opt/postgresql/lib/libpq.5.dylib
echo "and"
9): Library not loaded: /usr/local/opt/openssl/lib/libcrypto.1.0.0.dylib (LoadError)
Referenced from: /usr/local/opt/postgresql/lib/libpq.5.dylib
Reason: image not found -
the quickest way to work around my particular issue was to create a smylink from the current,
libssl.1.1.dylib
libcrypto.1.1.dylib
create 2 symlinks
cd /usr/local/opt/openssl/lib/
ln -sf libcrypto.1.1.dylib libcrypto.1.0.0.dylib
ln -sf libssl.1.1.dylib libssl.1.0.0.dylib
paths and version numbers are obviously going to change over time so pay attention to the path and version numbers while creating the above symlinks. after the symlinks were created, i am able to start my rails app.
cheers
leaving this here for future me
ScheduledExecutorService
The Answer by Lee is close, but only runs once. The Question seems to be asking to run indefinitely until an external state changes (until the response from a web site/service changes).
The ScheduledExecutorService
interface is part of the java.util.concurrent
package built into Java 5 and later as a more modern replacement for the old Timer
class.
Here is a complete example. Call either scheduleAtFixedRate
or scheduleWithFixedDelay
.
ScheduledExecutorService executor = Executors.newScheduledThreadPool ( 1 );
Runnable r = new Runnable () {
@Override
public void run () {
try { // Always wrap your Runnable with a try-catch as any uncaught Exception causes the ScheduledExecutorService to silently terminate.
System.out.println ( "Now: " + Instant.now () ); // Our task at hand in this example: Capturing the current moment in UTC.
if ( Boolean.FALSE ) { // Add your Boolean test here to see if the external task is fonud to be completed, as described in this Question.
executor.shutdown (); // 'shutdown' politely asks ScheduledExecutorService to terminate after previously submitted tasks are executed.
}
} catch ( Exception e ) {
System.out.println ( "Oops, uncaught Exception surfaced at Runnable in ScheduledExecutorService." );
}
}
};
try {
executor.scheduleAtFixedRate ( r , 0L , 5L , TimeUnit.SECONDS ); // ( runnable , initialDelay , period , TimeUnit )
Thread.sleep ( TimeUnit.MINUTES.toMillis ( 1L ) ); // Let things run a minute to witness the background thread working.
} catch ( InterruptedException ex ) {
Logger.getLogger ( App.class.getName () ).log ( Level.SEVERE , null , ex );
} finally {
System.out.println ( "ScheduledExecutorService expiring. Politely asking ScheduledExecutorService to terminate after previously submitted tasks are executed." );
executor.shutdown ();
}
Expect output like this:
Now: 2016-12-27T02:52:14.951Z
Now: 2016-12-27T02:52:19.955Z
Now: 2016-12-27T02:52:24.951Z
Now: 2016-12-27T02:52:29.951Z
Now: 2016-12-27T02:52:34.953Z
Now: 2016-12-27T02:52:39.952Z
Now: 2016-12-27T02:52:44.951Z
Now: 2016-12-27T02:52:49.953Z
Now: 2016-12-27T02:52:54.953Z
Now: 2016-12-27T02:52:59.951Z
Now: 2016-12-27T02:53:04.952Z
Now: 2016-12-27T02:53:09.951Z
ScheduledExecutorService expiring. Politely asking ScheduledExecutorService to terminate after previously submitted tasks are executed.
Now: 2016-12-27T02:53:14.951Z
If you are stuck with a machine where you don't have root access, then it is better to deal with a custom Python installation.
The Anaconda installation worked like a charm:
After installation,
[bash]$ /xxx/devTools/python/anaconda/bin/pip list --format=columns | grep numpy
numpy 1.13.3 numpydoc 0.7.0
If you want to completely destroy the target, you have a couple of options. First you can remove the object from the DOM as described above...
console.log($target); // jQuery object
$target.remove(); // remove target from the DOM
console.log($target); // $target still exists
Option 1 - Then replace target with an empty jQuery object (jQuery 1.4+)
$target = $();
console.log($target); // empty jQuery object
Option 2 - Or delete the property entirely (will cause an error if you reference it elsewhere)
delete $target;
console.log($target); // error: $target is not defined
More reading: info about empty jQuery object, and info about delete
<button class="myButton" data-id="345" ng-click="doStuff($element.target)">Button</button>
I added class to button to get by querySelector, then get data attribute
var myButton = angular.element( document.querySelector( '.myButton' ) );
console.log( myButton.data( 'id' ) );
public string SendFile(string filePath)
{
WebResponse response = null;
try
{
string sWebAddress = "Https://www.address.com";
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(sWebAddress);
wr.ContentType = "multipart/form-data; boundary=" + boundary;
wr.Method = "POST";
wr.KeepAlive = true;
wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
Stream stream = wr.GetRequestStream();
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
stream.Write(boundarybytes, 0, boundarybytes.Length);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(filePath);
stream.Write(formitembytes, 0, formitembytes.Length);
stream.Write(boundarybytes, 0, boundarybytes.Length);
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
string header = string.Format(headerTemplate, "file", Path.GetFileName(filePath), Path.GetExtension(filePath));
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
stream.Write(headerbytes, 0, headerbytes.Length);
FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
stream.Write(buffer, 0, bytesRead);
fileStream.Close();
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
stream.Write(trailer, 0, trailer.Length);
stream.Close();
response = wr.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream);
string responseData = streamReader.ReadToEnd();
return responseData;
}
catch (Exception ex)
{
return ex.Message;
}
finally
{
if (response != null)
response.Close();
}
}
Spring Data
is a convenience library on top of JPA
that abstracts away many things and brings Spring magic (like it or not) to the persistence store access. It is primarily used for working with relational databases. In short, it allows you to declare interfaces that have methods like findByNameOrderByAge(String name);
that will be parsed in runtime and converted into appropriate JPA
queries.
Its placement atop of JPA
makes its use tempting for:
Rookie developers who don't know SQL
or know it badly. This is a
recipe for disaster but they can get away with it if the project is trivial.
Experienced engineers who know what they do and want to spindle up things fast. This might be a viable strategy (but read further).
From my experience with Spring Data
, its magic is too much (this is applicable to Spring
in general). I started to use it heavily in one project and eventually hit several corner cases where I couldn't get the library out of my way and ended up with ugly workarounds. Later I read other users' complaints and realized that these issues are typical for Spring Data
. For example, check this issue that led to hours of investigation/swearing:
public TourAccommodationRate createTourAccommodationRate(
@RequestBody TourAccommodationRate tourAccommodationRate
) {
if (tourAccommodationRate.getId() != null) {
throw new BadRequestException("id MUST NOT be specified in a body during entry creation");
}
// This is an ugly hack required for the Room slim model to work. The problem stems from the fact that
// when we send a child entity having the many-to-many (M:N) relation to the containing entity, its
// information is not fetched. As a result, we get NPEs when trying to access all but its Id in the
// code creating the corresponding slim model. By detaching the entity from the persistence context we
// force the ORM to re-fetch it from the database instead of taking it from the cache
tourAccommodationRateRepository.save(tourAccommodationRate);
entityManager.detach(tourAccommodationRate);
return tourAccommodationRateRepository.findOne(tourAccommodationRate.getId());
}
I ended up going lower level and started using JDBI
- a nice library with just enough "magic" to save you from the boilerplate. With it, you have complete control over SQL queries and almost never have to fight the library.
So i had a adifferent case where i needed to assign values before running a session, So this was the easiest way to do that:
other_variable = tf.get_variable("other_variable", dtype=tf.int32,
initializer=tf.constant([23, 42]))
here i'm creating a variable as well as assigning it values at the same time
I created a simplified version using Array.prototype.includes(). My technique is similar to @Kunle Babatunde.
const isVowel = (char) => ["a", "e", "i", "o", "u"].includes(char);_x000D_
_x000D_
console.log(isVowel("o"), isVowel("s"));
_x000D_
Spring boot doc 'was' wrong (they have since fixed it) :
To switch it off you can set error.whitelabel.enabled=false
should be
To switch it off you can set server.error.whitelabel.enabled=false
go to tsconfig.json and comment the line the //strict:true this worked for me
After a bit of time (and more searching), I found this blog entry by Jomo Fisher.
One of the recent problems we’ve seen is that, because of the support for side-by-side runtimes, .NET 4.0 has changed the way that it binds to older mixed-mode assemblies. These assemblies are, for example, those that are compiled from C++\CLI. Currently available DirectX assemblies are mixed mode. If you see a message like this then you know you have run into the issue:
Mixed mode assembly is built against version 'v1.1.4322' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information.
[Snip]
The good news for applications is that you have the option of falling back to .NET 2.0 era binding for these assemblies by setting an app.config flag like so:
<startup useLegacyV2RuntimeActivationPolicy="true"> <supportedRuntime version="v4.0"/> </startup>
So it looks like the way the runtime loads mixed-mode assemblies has changed. I can't find any details about this change, or why it was done. But the useLegacyV2RuntimeActivationPolicy
attribute reverts back to CLR 2.0 loading.
The pack
method sizes the frame so that all its contents are at or above their preferred sizes. An alternative to pack is to establish a frame size explicitly by calling setSize
or setBounds
(which also sets the frame location). In general, using pack is preferable to calling setSize
, since pack leaves the frame layout manager in charge of the frame size, and layout managers are good at adjusting to platform dependencies and other factors that affect component size.
From Java tutorial
You should also refer to Javadocs any time you need additional information on any Java API
It is normally provided by the browser and hard to change, so the only way around it will be a CSS/JavaScript hack,
See the following links for some approaches:
The problem is that buttonClickedEvent
is a member function and you need a pointer to member in order to invoke it.
Try this:
void (MyClass::*func)(int);
func = &MyClass::buttonClickedEvent;
And then when you invoke it, you need an object of type MyClass
to do so, for example this
:
(this->*func)(<argument>);
http://www.codeguru.com/cpp/cpp/article.php/c17401/C-Tutorial-PointertoMember-Function.htm
Set each index in the array at the beginning (or before the $output
array is used) would probably be the easiest solution for your case.
Example
$output['admin_link'] = ""
$output['alternate_title'] = ""
$output['access_info'] = ""
$output['description'] = ""
$output['url'] = ""
Also not really relevant for your case but where you said you were new to PHP and this is not really immediately obvious isset()
can take multiple arguments. So in stead of this:
if(isset($var1) && isset($var2) && isset($var3) ...){
// all are set
}
You can do:
if(isset($var1, $var2, $var3)){
// all are set
}
Function convert image to base64 using jquery (you can convert to vanila js). Hope it help to you!
Usage: input is your nameId input has file image
<input type="file" id="asd"/>
<button onclick="proccessData()">Submit</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
async function converImageToBase64(inputId) {
let image = $('#'+inputId)[0]['files']
if (image && image[0]) {
const reader = new FileReader();
return new Promise(resolve => {
reader.onload = ev => {
resolve(ev.target.result)
}
reader.readAsDataURL(image[0])
})
}
}
async function proccessData() {
const image = await converImageToBase64('asd')
console.log(image)
}
</script>
Example: converImageToBase64('yourFileInputId')
There is a simpler solution that is faster and better, and if the numbers are different can even give you quantities differences:
df1_i = df1.set_index(['Date','Fruit','Color'])
df2_i = df2.set_index(['Date','Fruit','Color'])
df_diff = df1_i.join(df2_i,how='outer',rsuffix='_').fillna(0)
df_diff = (df_diff['Num'] - df_diff['Num_'])
Here df_diff is a synopsis of the differences. You can even use it to find the differences in quantities. In your example:
Explanation: Similarly to comparing two lists, to do it efficiently we should first order them then compare them (converting the list to sets/hashing would also be fast; both are an incredible improvement to the simple O(N^2) double comparison loop
Note: the following code produces the tables:
df1=pd.DataFrame({
'Date':['2013-11-24','2013-11-24','2013-11-24','2013-11-24'],
'Fruit':['Banana','Orange','Apple','Celery'],
'Num':[22.1,8.6,7.6,10.2],
'Color':['Yellow','Orange','Green','Green'],
})
df2=pd.DataFrame({
'Date':['2013-11-24','2013-11-24','2013-11-24','2013-11-24','2013-11-25','2013-11-25'],
'Fruit':['Banana','Orange','Apple','Celery','Apple','Orange'],
'Num':[22.1,8.6,7.6,10.2,22.1,8.6],
'Color':['Yellow','Orange','Green','Green','Red','Orange'],
})
You could try:
<html>
<head>
<style>
#main {
width: 500; /*Set to whatever*/
height: 500;/*Set to whatever*/
}
</style>
</head>
<body id="main">
</body>
</html>
Maybe something like this:
SELECT count(*) FROM user_tab_columns WHERE table_name = 'FOO'
this will count number of columns in a the table FOO
You can also just
select count(*) from all_tab_columns where owner='BAR' and table_name='FOO';
where the owner is schema and note that Table Names are upper case
I know the solution employing printing of new lines isn't much supported, but if all else fails, why not? Especially where one is operating in an environment where someone else is likely to be able to see the screen, yet not able to keylog. One potential solution then, is the following alias:
alias c="printf '\r\n%.0s' {1..50}"
Then, to "clear" away the current contents of the screen (or rather, hide them), just type c+Enter
at the terminal.
Javadocs don't offer any special tools for external links, so you should just use standard html:
See <a href="http://groversmill.com/">Grover's Mill</a> for a history of the
Martian invasion.
or
@see <a href="http://groversmill.com/">Grover's Mill</a> for a history of
the Martian invasion.
Don't use {@link ...}
or {@linkplain ...}
because these are for links to the javadocs of other classes and methods.
I have tried the following, with socat
:
socat TCP-L:8080,fork,reuseaddr -
And even though I have not made a connection to the socket, I cannot listen twice on the same port, in spite of the reuseaddr
option.
I get this message (which I expected before):
2016/02/23 09:56:49 socat[2667] E bind(5, {AF=2 0.0.0.0:8080}, 16): Address already in use
Update 3:
This warning can also be triggered by labels that have numberOfLines
set to anything but 1 if your deployment target is set to 7.1. This is completely reproducible with new single-view project.
Steps to Reproduce:
I've filed the following radar:
rdar://problem/18700567
Update 2:
Unfortunately, this is a thing again in the release version of Xcode 6. Note that you can, for the most part, manually edit your storyboard/xib to fix the problem. Per Charles A. in the comments below:
It's worth mentioning that you can pretty easily accidentally introduce this warning, and the warning itself doesn't help in finding the label that is the culprit. This is unfortunate in a complex storyboard. You can open the storyboard as a source file and search with the regex
<label(?!.*preferredMaxLayoutWidth)
to find labels that omit a preferredMaxLayoutWidth attribute/value. If you add in preferredMaxLayoutWidth="0" on such lines, it is the same as marking explicit and setting the value 0.
Update 1:
This bug has now been fixed in Xcode 6 GM.
Original Answer
This is a bug in Xcode6-Beta6 and XCode6-Beta7 and can be safely ignored for now.
An Apple engineer in the Apple Developer forums had this to say about the bug:
Preferred max layout width is an auto layout property on UILabel that allows it to automatically grow vertically to fit its content. Versions of Xcode prior to 6.0 would set preferredMaxLayoutWidth for multiline labels to the current bounds size at design time. You would need to manually update preferredMaxLayoutWidth at runtime if your horizontal layout changed.
iOS 8 added support for automatically computing preferredMaxLayoutWidth at runtime, which makes creating multiline labels even easier. This setting is not backwards compatible with iOS 7. To support both iOS 7 and iOS 8, Xcode 6 allows you to pick either "Automatic" or "Explicit" for preferredMaxLayoutWidth in the size inspector. You should:
Pick "Automatic" if targeting iOS 8 for the best experience. Pick "Explicit" if targeting < iOS 8. You can then enter the value of preferredMaxLayoutWidth you would like set. Enabling "Explicit" defaults to the current bounds size at the time you checked the box.
The warning will appear if (1) you're using auto layout, (2) "Automatic" is set for a multiline label [you can check this in the size inspector for the label], and (3) your deployment target < iOS 8.
It seems the bug is that this warning appears for non-autolayout documents. If you are seeing this warning and not using auto layout you can ignore the warning.
Alternately, you can work around the issue by using the file inspector on the storyboard or xib in question and change "Builds for" to "Builds for iOS 8.0 and Later"
Try something like this:
#include <signal.h>
pid_t child_pid = -1 ; //Global
void kill_child(int sig)
{
kill(child_pid,SIGKILL);
}
int main(int argc, char *argv[])
{
signal(SIGALRM,(void (*)(int))kill_child);
child_pid = fork();
if (child_pid > 0) {
/*PARENT*/
alarm(30);
/*
* Do parent's tasks here.
*/
wait(NULL);
}
else if (child_pid == 0){
/*CHILD*/
/*
* Do child's tasks here.
*/
}
}
Easiest way to see if the file is being cached is to append a query string to the <link />
element so that the browser will re-load it.
To do this you can change your stylesheet reference to something like
<link rel="stylesheet" type="text/css" href="/css/stylesheet.css?v=1" />
Note the v=1
part. You can update this each time you make a new version to see if it is indeed being cached.
Batch Files automatically pass the text after the program so long as their are variables to assign them to. They are passed in order they are sent; e.g. %1 will be the first string sent after the program is called, etc.
If you have Hello.bat and the contents are:
@echo off
echo.Hello, %1 thanks for running this batch file (%2)
pause
and you invoke the batch in command via
hello.bat APerson241 %date%
you should receive this message back:
Hello, APerson241 thanks for running this batch file (01/11/2013)
Well, the above answer is correct, auto_now_add and auto_now would do it, but it would be better to make an abstract class and use it in any model where you require created_at
and updated_at
fields.
class TimeStampMixin(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
Now anywhere you want to use it you can do a simple inherit and you can use timestamp in any model you make like.
class Posts(TimeStampMixin):
name = models.CharField(max_length=50)
...
...
In this way, you can leverage object-oriented reusability, in Django DRY(don't repeat yourself)
Access 2010 has both stored procedures, and also has table triggers. And, both features are available even when you not using a server (so, in 100% file based mode).
If you using SQL Server with Access, then of course the stored procedures are built using SQL Server and not Access.
For Access 2010, you open up the table (non-design view), and then choose the table tab. You see options there to create store procedures and table triggers.
For example:
Note that the stored procedure language is its own flavor just like Oracle or SQL Server (T-SQL). Here is example code to update an inventory of fruits as a result of an update in the fruit order table
Keep in mind these are true engine-level table triggers. In fact if you open up that table with VB6, VB.NET, FoxPro or even modify the table on a computer WITHOUT Access having been installed, the procedural code and the trigger at the table level will execute. So, this is a new feature of the data engine jet (now called ACE) for Access 2010. As noted, this is procedural code that runs, not just a single statement.
You need to use the CSS white-space
attribute.
In particular, white-space: nowrap
and white-space: pre
are the most commonly used values. The first one seems to be what you 're after.
Remember that CURRENT_TIMESTAMP - (number) works fine, but that you need to understand what number it is looking for - it is floating-point number of days. So CURRENT_TIMESTAMP-1.0 is 1 day ago, CURRENT_TIMESTAMP-0.5 is 1/2 day ago. For 30 minutes, that is 1.0/48.0 (use radix so result is a floating point number) or 0.0208333333333333, so your query will work if re-written as
select * from
[Janus999DB].[dbo].[tblCustomerPlay]
where DatePlayed < CURRENT_TIMESTAMP
and DatePlayed >
CURRENT_TIMESTAMP-1.0/48.0
You could also use 1.0/24.0/2.0 if that looks more like 1/2 hour to you.
I'm not saying that Array
-> |value,index|
and Hash
-> |key,value|
is not insane (see Horace Loeb's comment), but I am saying that there is a sane way to expect this arrangement.
When I am dealing with arrays, I am focused on the elements in the array (not the index because the index is transitory). The method is each with index, i.e. each+index, or |each,index|, or |value,index|
. This is also consistent with the index being viewed as an optional argument, e.g. |value| is equivalent to |value,index=nil| which is consistent with |value,index|.
When I am dealing with hashes, I am often more focused on the keys than the values, and I am usually dealing with keys and values in that order, either key => value
or hash[key] = value
.
If you want duck-typing, then either explicitly use a defined method as Brent Longborough showed, or an implicit method as maxhawkins showed.
Ruby is all about accommodating the language to suit the programmer, not about the programmer accommodating to suit the language. This is why there are so many ways. There are so many ways to think about something. In Ruby, you choose the closest and the rest of the code usually falls out extremely neatly and concisely.
As for the original question, "What is the “right” way to iterate through an array in Ruby?", well, I think the core way (i.e. without powerful syntactic sugar or object oriented power) is to do:
for index in 0 ... array.size
puts "array[#{index}] = #{array[index].inspect}"
end
But Ruby is all about powerful syntactic sugar and object oriented power, but anyway here is the equivalent for hashes, and the keys can be ordered or not:
for key in hash.keys.sort
puts "hash[#{key.inspect}] = #{hash[key].inspect}"
end
So, my answer is, "The “right” way to iterate through an array in Ruby depends on you (i.e. the programmer or the programming team) and the project.". The better Ruby programmer makes the better choice (of which syntactic power and/or which object oriented approach). The better Ruby programmer continues to look for more ways.
Now, I want to ask another question, "What is the “right” way to iterate through a Range in Ruby backwards?"! (This question is how I came to this page.)
It is nice to do (for the forwards):
(1..10).each{|i| puts "i=#{i}" }
but I don't like to do (for the backwards):
(1..10).to_a.reverse.each{|i| puts "i=#{i}" }
Well, I don't actually mind doing that too much, but when I am teaching going backwards, I want to show my students a nice symmetry (i.e. with minimal difference, e.g. only adding a reverse, or a step -1, but without modifying anything else). You can do (for symmetry):
(a=*1..10).each{|i| puts "i=#{i}" }
and
(a=*1..10).reverse.each{|i| puts "i=#{i}" }
which I don't like much, but you can't do
(*1..10).each{|i| puts "i=#{i}" }
(*1..10).reverse.each{|i| puts "i=#{i}" }
#
(1..10).step(1){|i| puts "i=#{i}" }
(1..10).step(-1){|i| puts "i=#{i}" }
#
(1..10).each{|i| puts "i=#{i}" }
(10..1).each{|i| puts "i=#{i}" } # I don't want this though. It's dangerous
You could ultimately do
class Range
def each_reverse(&block)
self.to_a.reverse.each(&block)
end
end
but I want to teach pure Ruby rather than object oriented approaches (just yet). I would like to iterate backwards:
I believe this is impossible without defining a pred
method, which means modifying the Range class to use it. If you can do this please let me know, otherwise confirmation of impossibility would be appreciated though it would be disappointing. Perhaps Ruby 1.9 addresses this.
(Thanks for your time in reading this.)
Although "Mark Circular Dependencies" enables you to compile the code, it may lead to a slower environment and future issues.
That's happening because at some point Eclipse has lost it's directions on your build path.
1 - Remove the project and it's references from the workspace. 2 - Import it back again. 3 - Check the references.
It is the best solution.
I wanted to keep the formulas in place, which the above code did not do.
Here's what I've been doing, note that this leaves one empty row in the table.
Sub DeleteTableRows(ByRef Table As ListObject, KeepFormulas as boolean)
On Error Resume Next
if not KeepFormulas then
Table.DataBodyRange.clearcontents
end if
Table.DataBodyRange.Rows.Delete
On Error GoTo 0
End Sub
(PS don't ask me why!)
I would do this:
std::string a("Hello ");
std::string b("World");
std::string c = a + b;
Which compiles in VS2008.
Take a look at your code :
getUsers(): Observable<User[]> {
return Observable.create(observer => {
this.http.get('http://users.org').map(response => response.json();
})
}
and code from https://angular.io/docs/ts/latest/tutorial/toh-pt6.html (BTW. really good tutorial, you should check it out)
getHeroes(): Promise<Hero[]> {
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json().data as Hero[])
.catch(this.handleError);
}
The HttpService inside Angular2 already returns an observable, sou don't need to wrap another Observable around like you did here:
return Observable.create(observer => {
this.http.get('http://users.org').map(response => response.json()
Try to follow the guide in link that I provided. You should be just fine when you study it carefully.
---EDIT----
First of all WHERE you log the this.users variable? JavaScript isn't working that way. Your variable is undefined and it's fine, becuase of the code execution order!
Try to do it like this:
getUsers(): void {
this.userService.getUsers()
.then(users => {
this.users = users
console.log('this.users=' + this.users);
});
}
See where the console.log(...) is!
Try to resign from toPromise() it's seems to be just for ppl with no RxJs background.
Catch another link: https://scotch.io/tutorials/angular-2-http-requests-with-observables Build your service once again with RxJs observables.
I was facing same issue for changing default gradle version from 5.0 to 4.7, Below are the steps to change default gradle version in intellij
1) Change gradle version in gradle/wrapper/gradle-wrapper.properties in this property distributionUrl
2) Hit refresh button in gradle projects menu so that it will start downloading new gradle zip version
Check following to help the understand the concept of CTE recursion
DECLARE
@startDate DATETIME,
@endDate DATETIME
SET @startDate = '11/10/2011'
SET @endDate = '03/25/2012'
; WITH CTE AS (
SELECT
YEAR(@startDate) AS 'yr',
MONTH(@startDate) AS 'mm',
DATENAME(mm, @startDate) AS 'mon',
DATEPART(d,@startDate) AS 'dd',
@startDate 'new_date'
UNION ALL
SELECT
YEAR(new_date) AS 'yr',
MONTH(new_date) AS 'mm',
DATENAME(mm, new_date) AS 'mon',
DATEPART(d,@startDate) AS 'dd',
DATEADD(d,1,new_date) 'new_date'
FROM CTE
WHERE new_date < @endDate
)
SELECT yr AS 'Year', mon AS 'Month', count(dd) AS 'Days'
FROM CTE
GROUP BY mon, yr, mm
ORDER BY yr, mm
OPTION (MAXRECURSION 1000)
If your object is myObject
, and you want to test to see if it is an NSString
, the code would be:
[myObject isKindOfClass:[NSString class]]
Likewise, if you wanted to test myObject
for a UIImageView
:
[myObject isKindOfClass:[UIImageView class]]
All tables should have a primary key (consisting of a single or multiple columns), duplicate rows doesn't make sense in a relational database. You can limit the number of delete rows using LIMIT
though:
DELETE FROM orders WHERE id_users = 1 AND id_product = 2 LIMIT 1
But that just solves your current issue, you should definitely work on the bigger issue by defining primary keys.
simply run below command.
react-native start --reset-cache
Go to the file location where the POM is stored and open cmd. Then type "mvn --v" to check the maven version and java runtime provided. Check runtime attribute and if it is "C:\Program Files\Java\jre1.8.0_191" or even close to a JRE, go to environment variables and add a new "system variable" called "JAVA_HOME" with a value "C:\Program Files\Java\jdk1.8.0_191".
Reopen the cmd and then "clean install" the project.
I don't think min/max validations attribute exist. I would use something like
[Range(1, Int32.MaxValue)]
for minimum value 1 and
[Range(Int32.MinValue, 10)]
for maximum value 10
Here is an example using openssl_encrypt
//Encryption:
$textToEncrypt = "My Text to Encrypt";
$encryptionMethod = "AES-256-CBC";
$secretHash = "encryptionhash";
$iv = mcrypt_create_iv(16, MCRYPT_RAND);
$encryptedText = openssl_encrypt($textToEncrypt,$encryptionMethod,$secretHash, 0, $iv);
//Decryption:
$decryptedText = openssl_decrypt($encryptedText, $encryptionMethod, $secretHash, 0, $iv);
print "My Decrypted Text: ". $decryptedText;
From here what I understand DataFrames are:
DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. You can think of it like a spreadsheet or SQL table, or a dict of Series objects.
And Series are:
Series is a one-dimensional labeled array capable of holding any data type (integers, strings, floating point numbers, Python objects, etc.).
Series have a name
attribute which can be accessed like so:
In [27]: s = pd.Series(np.random.randn(5), name='something')
In [28]: s
Out[28]:
0 0.541
1 -1.175
2 0.129
3 0.043
4 -0.429
Name: something, dtype: float64
In [29]: s.name
Out[29]: 'something'
EDIT: Based on OP's comments, I think OP was looking for something like:
>>> df = pd.DataFrame(...)
>>> df.name = 'df' # making a custom attribute that DataFrame doesn't intrinsically have
>>> print(df.name)
'df'
You can try something like this:
package_version(R.version)
getRversion()
To see non-staged (non-added) changes to existing files
git diff
Note that this does not track new files. To see staged, non-commited changes
git diff --cached
Using System.out.println() is bad practice (better use logging framework) -> you should not have many occurences in your code base. Using another method to simply shorten it does not seem a good option.
I got the error using TFS, my AssemblyInfo wasn't mapped in the branch I was working on.
Using -Dhttps.protocols=TLSv1.2 JVM argument didn't work for me. What worked is the following code
RequestConfig.Builder requestBuilder = RequestConfig.custom();
//other configuration, for example
requestBuilder = requestBuilder.setConnectTimeout(1000);
SSLContext sslContext = SSLContextBuilder.create().useProtocol("TLSv1.2").build();
HttpClientBuilder builder = HttpClientBuilder.create();
builder.setDefaultRequestConfig(requestBuilder.build());
builder.setProxy(new HttpHost("your.proxy.com", 3333)); //if you have proxy
builder.setSSLContext(sslContext);
HttpClient client = builder.build();
Use the following JVM argument to verify
-Djavax.net.debug=all
for importing the image in flask you want a sub folder named static into the folder keep your img
and go into your html file and write
I use the react-native-rename* npm package. Install it via
npm install react-native-rename -g
Then, from the root of your React Native project, execute the following:
react-native-rename "MyApp" -b com.mycompany.myapp
Be careful with jobs
1 - if you have a job based in maven, Jenkins takes your default java configuration and you decide the compilation level in your POM.XML.
2 - if you have a free style job, in the the configuration option of the job you can select the JDK that you want to use.
Hope this help.
for me this works
unicode(data).encode('utf-8')
Try this
getExternalFilesDir(Environment.getDataDirectory().getAbsolutePath()).getAbsolutePath()
I pre-allocate a vector with
> (a <- rep(NA, 10))
[1] NA NA NA NA NA NA NA NA NA NA
You can then use [] to insert values into it.
When you have everything #included, an unresolved external symbol is often a missing * or & in the declaration or definition of a function.
I took what you had, and added another X-Testing
header
var config = {headers: {
'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
'Accept': 'application/json;odata=verbose',
"X-Testing" : "testing"
}
};
$http.get("/test", config);
And in the Chrome network tab, I see them being sent.
GET /test HTTP/1.1
Host: localhost:3000
Connection: keep-alive
Accept: application/json;odata=verbose
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22
Authorization: Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==
X-Testing: testing
Referer: http://localhost:3000/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Are you not seeing them from the browser, or on the server? Try the browser tooling or a debug proxy and see what is being sent out.
The shells above will do the trick, and you could even convert them to an alias (you may need to wrap in a function to handle parameters):
alias myWatch='_() { while :; do clear; $2; sleep $1; done }; _'
Examples:
myWatch 1 ls ## Self-explanatory
myWatch 5 "ls -lF $HOME" ## Every 5 seconds, list out home directory; double-quotes around command to keep its arguments together
Alternately, Homebrew can install the watch from http://procps.sourceforge.net/:
brew install watch
Assuming the original date is in cell A1:
=A1-180
Works in at least Excel 2003 and 2010.
There are several options. You can use the WebMethod attribute, for your purpose.
$("#chk0") is refering to an element with the id chk0. You might try adding id's to the elements. Ids are unique even though the names are the same so that in jQuery you can access a single element by it's id.
If you want a formula to do it then:
=IF(ISNUMBER(SEARCH("*texts are *",A1)),LEFT(A1,FIND("texts are ",A1) + 9) & "WORD",A1)
This will do it. Change `"WORD" To the word you want.
The statement java.io.IOException: Could not locate executable null\bin\winutils.exe
explains that the null is received when expanding or replacing an Environment Variable. If you see the Source in Shell.Java in Common Package you will find that HADOOP_HOME variable is not getting set and you are receiving null in place of that and hence the error.
So, HADOOP_HOME needs to be set for this properly or the variable hadoop.home.dir property.
Hope this helps.
Thanks, Kamleshwar.
The root reason for this error is that PHP separated itself from the MySQL Client libraries some time ago. So what's happening (mainly on older compiles of linux) is that people will compile PHP against a given build of the MySQL Client (meaning the version of MySQL installed is irrelevant) and not upgrade (in CentOS this package is listed as mysqlclientXX
, where XX
represents the package number). This also allows the package maintainer to support lower versions of MySQL. It's a messy way to do it, but it was the only way given how PHP and MySQL use different licensing.
MySQLND solves the problem by using PHP's own native driver (the ND), which no longer relies on MySQL Client. It's also compiled for the version of PHP you're using. This is a better solution all around, if for no other reason that MySQLND is made to have PHP talk to MySQL.
If you can't install MySQLND you can actually safely ignore this error for the most part. It's just more of an FYI notice than anything. It just sounds scary.
I had this problem when trying to consume a value returned from a stored procedure.
console.log(result[0]);
would output "[ RowDataPacket { datetime: '2019-11-15 16:37:05' } ]".
I found that
console.log(results[0][0].datetime);
Gave me the value I wanted.
I tried to fix the 'no public DNS' once the EC2 was up and running, I couldnt add a public DNS
this is even after following the above steps making mods to the VPC or the Subnet
so, I had to make modifications to the subnet and the vpc, before starting another instance, and THEN start up a new instance.
the new instance had a public DNS. That is how it worked for me.
I was catching GuzzleHttp\Exception\BadResponseException
as @dado is suggesting. But one day I got GuzzleHttp\Exception\ConnectException
when DNS for domain wasn't available.
So my suggestion is - catch GuzzleHttp\Exception\ConnectException
to be safe about DNS errors as well.
df.sort()
is deprecated, use df.sort_values(...)
: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html
Then follow joris' answer by doing df.reset_index(drop=True)
As per latest Ansible Version 2.5, to check if a variable is defined and depending upon this if you want to run any task, use undefined
keyword.
tasks:
- shell: echo "I've got '{{ foo }}' and am not afraid to use it!"
when: foo is defined
- fail: msg="Bailing out. this play requires 'bar'"
when: bar is undefined
The top answers in this question may be misleading in some cases. Imagine that the file, whose absolute path you want to find, is in the $PATH
variable:
# node is in $PATH variable
type -P node
# /home/user/.asdf/shims/node
cd /tmp
touch node
readlink -e node
# /tmp/node
readlink -m node
# /tmp/node
readlink -f node
# /tmp/node
echo "$(cd "$(dirname "node")"; pwd -P)/$(basename "node")"
# /tmp/node
realpath node
# /tmp/node
realpath -e node
# /tmp/node
# Now let's say that for some reason node does not exist in current directory
rm node
readlink -e node
# <nothing printed>
readlink -m node
# /tmp/node # Note: /tmp/node does not exist, but is printed
readlink -f node
# /tmp/node # Note: /tmp/node does not exist, but is printed
echo "$(cd "$(dirname "node")"; pwd -P)/$(basename "node")"
# /tmp/node # Note: /tmp/node does not exist, but is printed
realpath node
# /tmp/node # Note: /tmp/node does not exist, but is printed
realpath -e node
# realpath: node: No such file or directory
Based on the above I can conclude that: realpath -e
and readlink -e
can be used for finding the absolute path of a file, that we expect to exist in current directory, without result being affected by the $PATH
variable. The only difference is that realpath
outputs to stderr, but both will return error code if file is not found:
cd /tmp
rm node
realpath -e node ; echo $?
# realpath: node: No such file or directory
# 1
readlink -e node ; echo $?
# 1
Now in case you want the absolute path a of a file that exists in $PATH
, the following command would be suitable, independently on whether a file with same name exists in current dir.
type -P example.txt
# /path/to/example.txt
# Or if you want to follow links
readlink -e $(type -P example.txt)
# /originalpath/to/example.txt
# If the file you are looking for is an executable (and wrap again through `readlink -e` for following links )
which executablefile
# /opt/bin/executablefile
And a, fallback to $PATH
if missing, example:
cd /tmp
touch node
echo $(readlink -e node || type -P node)
# /tmp/node
rm node
echo $(readlink -e node || type -P node)
# /home/user/.asdf/shims/node
sc queryex <service name>
taskkill /F /PID <Service PID>
eg
Use the put method: https://developer.android.com/reference/org/json/JSONObject.html
JSONObject person = jsonArray.getJSONObject(0).getJSONObject("person");
person.put("name", "Sammie");
At the time you emit the very first line,
Artist Title Price Genre Disc Sale Tax Cash
to achieve "alignment", you have to know "in advance" how wide each column will need to be (otherwise, alignment is impossible). Once you do know the needed width for each column (there are several possible ways to achieve that depending on where your data's coming from), then the setw
function mentioned in the other answer will help, or (more brutally;-) you could emit carefully computed number of extra spaces (clunky, to be sure), etc. I don't recommend tabs anyway as you have no real control on how the final output device will render those, in general.
Back to the core issue, if you have each column's value in a vector<T>
of some sort, for example, you can do a first formatting pass to determine the maximum width of the column, for example (be sure to take into account the width of the header for the column, too, of course).
If your rows are coming "one by one", and alignment is crucial, you'll have to cache or buffer the rows as they come in (in memory if they fit, otherwise on a disk file that you'll later "rewind" and re-read from the start), taking care to keep updated the vector of "maximum widths of each column" as the rows do come. You can't output anything (not even the headers!), if keeping alignment is crucial, until you've seen the very last row (unless you somehow magically have previous knowledge of the columns' widths, of course;-).
The script below lists all the default constraints and the default values for the user tables in the database in which it is being run:
SELECT
b.name AS TABLE_NAME,
d.name AS COLUMN_NAME,
a.name AS CONSTRAINT_NAME,
c.text AS DEFAULT_VALUE
FROM sys.sysobjects a INNER JOIN
(SELECT name, id
FROM sys.sysobjects
WHERE xtype = 'U') b on (a.parent_obj = b.id)
INNER JOIN sys.syscomments c ON (a.id = c.id)
INNER JOIN sys.syscolumns d ON (d.cdefault = a.id)
WHERE a.xtype = 'D'
ORDER BY b.name, a.name
If you go to the Flat file connection manager under Advanced and Look at the "OutputColumnWidth" description's ToolTip It will tell you that Composit characters may use more spaces. So the "é" in "Société" most likely occupies more than one character.
EDIT: Here's something about it: http://en.wikipedia.org/wiki/Precomposed_character
log2(x) = log10(x) / log10(2)
It´s very simple to do:
Just add following attribute and code to your Main-method:
[STAThread]
void Main(string[] args])
{
Application.EnableVisualStyles();
//Do some stuff...
while(!Exit)
{
Application.DoEvents(); //Now if you call "form.Show()" your form won´t be frozen
//Do your stuff
}
}
Now you´re fully able to show WinForms :)
Just reset the merge commit with git reset --hard HEAD^
.
If you use --no-ff git always creates a merge, even if you did not commit anything in between. Without --no-ff git will just do a fast forward, meaning your branches HEAD will be set to HEAD of the merged branch. To resolve this find the commit-id you want to revert to and git reset --hard $COMMITID
.
I used the logic in the replies by rampion and schnaader. I will summarise how I confirmed the results. I changed the numbers to binary and then used the XOR-operation. Alternatively, you can use the Hexadecimal tables: Click here!
the name attribute is used for posting to e.g. a webserver. The id is primarily used for css (and javascript). Suppose you have this setup:
<input id="message_id" name="message_name" type="text" />
in order to get the value with PHP when posting your form, it will use the name-attribute, like this:
$_POST["message_name"];
The id is used for styling, as said before, for when you want to use specific css.
#message_id
{
background-color: #cccccc;
}
Of course, you can use the same denomination for your id and name-attribute. These two will not interfere with each other.
also, name can be used for more items, like when you are using radiobuttons. Name is then used to group your radiobuttons, so you can only select one of those options.
<input id="button_1" type="radio" name="option" />
<input id="button_2" type="radio" name="option" />
And in this very specific case, I can further say how id is used, because you will probably want a label with your radiobutton. Label has a for-attribute, which uses the id of your input to link this label to your input (when you click the label, the button is checked). Example can be found below
<input id="button_1" type="radio" name="option" /><label for="button_1">Text for button 1</label>
<input id="button_2" type="radio" name="option" /><label for="button_2">Text for button 2</label>
assertTrue
will fail if the second parameter evaluates to false
(in other words, it ensures that the value is true). assertFalse
does the opposite.
assertTrue("This will succeed.", true);
assertTrue("This will fail!", false);
assertFalse("This will succeed.", false);
assertFalse("This will fail!", true);
As with many other things, the best way to become familiar with these methods is to just experiment :-).
npm install --silent
Seems to suppress the funding issue.
I'm looking into this as well, and while I don't have a good solution for you I did manage to dig up SIPDroid's video code:
http://code.google.com/p/sipdroid/source/browse/trunk/src/org/sipdroid/sipua/ui/VideoCamera.java
You can use the condition if x is not null then...
. It's not a function. There's also the NVL()
function, a good example of usage here: NVL function ref.
Read this thread R - boolean operators && and ||.
Basically, the &
is vectorized, i.e. it acts on each element of the comparison returning a logical array with the same dimension as the input. &&
is not, returning a single logical.
Use the shell error handling for unset variables (note the double $
):
$ cat Makefile
foo:
echo "something is set to $${something:?}"
$ make foo
echo "something is set to ${something:?}"
/bin/sh: something: parameter null or not set
make: *** [foo] Error 127
$ make foo something=x
echo "something is set to ${something:?}"
something is set to x
If you need a custom error message, add it after the ?
:
$ cat Makefile
hello:
echo "hello $${name:?please tell me who you are via \$$name}"
$ make hello
echo "hello ${name:?please tell me who you are via \$name}"
/bin/sh: name: please tell me who you are via $name
make: *** [hello] Error 127
$ make hello name=jesus
echo "hello ${name:?please tell me who you are via \$name}"
hello jesus
Unlike Java, C++ doesn't have a "standard style". Pretty much very company I've ever worked at has its own C++ coding style, and most open source projects have their own styles too. A few coding conventions you might want to look at:
It's interesting to note that C++ coding standards often specify which parts of the language not to use. For example, the Google C++ Style Guide says "We do not use C++ exceptions". Almost everywhere I've worked has prohibited certain parts of C++. (One place I worked basically said, "program in C, but new
and delete
are okay"!)
I just declare an interface and use a variable of that type access the enum. Keeping the interface and enum in sync is actually easy, since TypeScript complains if something changes in the enum, like so.
error TS2345: Argument of type 'typeof EAbFlagEnum' is not assignable to parameter of type 'IAbFlagEnum'. Property 'Move' is missing in type 'typeof EAbFlagEnum'.
The advantage of this method is no type casting is required in order to use the enum (interface) in various situations, and more types of situations are thus supported, such as the switch/case.
// Declare a TypeScript enum using unique string
// (per hack mentioned by zjc0816)
enum EAbFlagEnum {
None = <any> "none",
Select = <any> "sel",
Move = <any> "mov",
Edit = <any> "edit",
Sort = <any> "sort",
Clone = <any> "clone"
}
// Create an interface that shadows the enum
// and asserts that members are a type of any
interface IAbFlagEnum {
None: any;
Select: any;
Move: any;
Edit: any;
Sort: any;
Clone: any;
}
// Export a variable of type interface that points to the enum
export var AbFlagEnum: IAbFlagEnum = EAbFlagEnum;
Using the variable, rather than the enum, produces the desired results.
var strVal: string = AbFlagEnum.Edit;
switch (strVal) {
case AbFlagEnum.Edit:
break;
case AbFlagEnum.Move:
break;
case AbFlagEnum.Clone
}
Flags were another necessity for me, so I created an NPM module that adds to this example, and includes tests.
If you want to set specific learning rates for intervals of epochs like 0 < a < b < c < ...
. Then you can define your learning rate as a conditional tensor, conditional on the global step, and feed this as normal to the optimiser.
You could achieve this with a bunch of nested tf.cond
statements, but its easier to build the tensor recursively:
def make_learning_rate_tensor(reduction_steps, learning_rates, global_step):
assert len(reduction_steps) + 1 == len(learning_rates)
if len(reduction_steps) == 1:
return tf.cond(
global_step < reduction_steps[0],
lambda: learning_rates[0],
lambda: learning_rates[1]
)
else:
return tf.cond(
global_step < reduction_steps[0],
lambda: learning_rates[0],
lambda: make_learning_rate_tensor(
reduction_steps[1:],
learning_rates[1:],
global_step,)
)
Then to use it you need to know how many training steps there are in a single epoch, so that we can use the global step to switch at the right time, and finally define the epochs and learning rates you want. So if I want the learning rates [0.1, 0.01, 0.001, 0.0001]
during the epoch intervals of [0, 19], [20, 59], [60, 99], [100, \infty]
respectively, I would do:
global_step = tf.train.get_or_create_global_step()
learning_rates = [0.1, 0.01, 0.001, 0.0001]
steps_per_epoch = 225
epochs_to_switch_at = [20, 60, 100]
epochs_to_switch_at = [x*steps_per_epoch for x in epochs_to_switch_at ]
learning_rate = make_learning_rate_tensor(epochs_to_switch_at , learning_rates, global_step)
I also tried to make an executable jar file that I could run with the following command:
java -jar <jarfile>
After some searching I found the following link:
Packaging and Deploying Desktop Java Applications
I set the project's main class:
Then in the fodler dist the newly created jar should be executable with the command I mentioned above.
In TortoiseSVN, you can also Shift + right-click to get a menu that includes "Delete (keep local)".
Here is another method, much simple, lets say your dataframe name is daat
and column name is YEARMONTH
daat.YEARMONTH.value_counts()
If you've got PowerShell on your system, you can just execute this command:
powershell -command "Start-Sleep -s 5"
Edit: people raised an issue where the amount of time powershell takes to start is significant compared to how long you're trying to wait for. If the accuracy of the wait time is important (ie a second or two extra delay is not acceptable), you can use this approach:
powershell -command "$sleepUntil = [DateTime]::Parse('%date% %time%').AddSeconds(5); $sleepDuration = $sleepUntil.Subtract((get-date)).TotalMilliseconds; start-sleep -m $sleepDuration"
This takes the time when the windows command was issued, and the powershell script sleeps until 5 seconds after that time. So as long as powershell takes less time to start than your sleep duration, this approach will work (it's around 600ms on my machine).
The table normally contains multiple rows. Use a loop and use row.Field<string>(0)
to access the value of each row.
foreach(DataRow row in dt.Rows)
{
string file = row.Field<string>("File");
}
You can also access it via index:
foreach(DataRow row in dt.Rows)
{
string file = row.Field<string>(0);
}
If you expect only one row, you can also use the indexer of DataRowCollection
:
string file = dt.Rows[0].Field<string>(0);
Since this fails if the table is empty, use dt.Rows.Count
to check if there is a row:
if(dt.Rows.Count > 0)
file = dt.Rows[0].Field<string>(0);
My situation was not covered by any of the above answers. I found the following: MSDN article on threading that explains that when stuck in some primitive native threading operations, the debugger can't access the data. As an example, when a thread is sitting on Task.Wait(), this comes up.
There is a simpler solution
if (inputDate.getDate() === todayDate.getDate()) {
// do stuff
}
like that you don't loose the time attached to inputDate
if any
LIBRARY_PATH
is used by gcc before compilation to search directories containing static and shared libraries that need to be linked to your program.
LD_LIBRARY_PATH
is used by your program to search directories containing shared libraries after it has been successfully compiled and linked.
EDIT:
As pointed below, your libraries can be static or shared. If it is static then the code is copied over into your program and you don't need to search for the library after your program is compiled and linked. If your library is shared then it needs to be dynamically linked to your program and that's when LD_LIBRARY_PATH
comes into play.
Class.cast()
is rarely ever used in Java code. If it is used then usually with types that are only known at runtime (i.e. via their respective Class
objects and by some type parameter). It is only really useful in code that uses generics (that's also the reason it wasn't introduced earlier).
It is not similar to reinterpret_cast
, because it will not allow you to break the type system at runtime any more than a normal cast does (i.e. you can break generic type parameters, but can't break "real" types).
The evils of the C-style cast operator generally don't apply to Java. The Java code that looks like a C-style cast is most similar to a dynamic_cast<>()
with a reference type in Java (remember: Java has runtime type information).
Generally comparing the C++ casting operators with Java casting is pretty hard since in Java you can only ever cast reference and no conversion ever happens to objects (only primitive values can be converted using this syntax).
In addition to the above answers here is how you might handle a 500 series response from your api where you receive an error message encoded in json:
function callApi(url) {
return fetch(url)
.then(response => {
if (response.ok) {
return response.json().then(response => ({ response }));
}
return response.json().then(error => ({ error }));
})
;
}
let url = 'http://jsonplaceholder.typicode.com/posts/6';
const { response, error } = callApi(url);
if (response) {
// handle json decoded response
} else {
// handle json decoded 500 series response
}
This is a very simple code I use and you manipulate it to change the colour and size of the table as you see fit.
First connect to the database:
<?php
$connect=mysql_connect('localhost', 'root', 'password');
mysql_select_db("name");
//here u select the data you want to retrieve from the db
$query="select * from tablename";
$result= mysql_query($query);
//here you check to see if any data has been found and you define the width of the table
If($result){
echo "<table width ='340' align='left'>
<tr color ='#5D9951>";
$i=0;
If(mysql_num_rows($result)>0)
{
//here you fetch the data from the database and print it in the respective columns
while($i<mysql_num_fields($result))
{
echo "<th>".mysql_field_name($result, $i)."</th>";
$i++;
}
echo "</tr>";
$color=1;
while($rows=mysql_fetch_array($result, MYSQL_ASSOC))
{
If ($color==1){
echo "<tr color='#'#cccccc'>";
foreach ($rows as $data){
echo "<td align='center'>".$data. "</td>";
}
$color=2;
}
$color=1;
}
} else {
echo"no results found";
echo "</table>";
} else {
echo "error running query:".MYSQL_error();
}
?>
It's a very elementary piece of code but it helps if you are not used to using functions.
If you face this error when you start Symfony project with docker (my Symfony version 5.1). Or errors like these:
Uncaught Exception: Failed to write file "/var/www/html/mysite.com.local/var/cache/dev/App_KernelDevDebugContainer.xml"" while reading upstream
Uncaught Warning: file_put_contents(/var/www/html/mysite.com.local/var/cache/dev/App_KernelDevDebugContainerDeprecations.log): failed to open stream: Permission denied" while reading upstream
Fix below helped me.
In Dockerfile for nginx container add line:
RUN usermod -u 1000 www-data
In Dockerfile for php-fpm container add line:
RUN usermod -u 1000 www-data
Then remove everything in directories "/var/cache", "/var/log" and rebuild docker's containers.
Just style the content with white-space: pre-wrap;
.
div {_x000D_
white-space: pre-wrap;_x000D_
}
_x000D_
<div>_x000D_
This is some text with some extra spacing and a_x000D_
few newlines along with some trailing spaces _x000D_
and five leading spaces thrown in_x000D_
for good_x000D_
measure _x000D_
</div>
_x000D_
Test Data
DECLARE @Table1 TABLE(ID INT, Value INT)
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400)
Query
SELECT ID
,STUFF((SELECT ', ' + CAST(Value AS VARCHAR(10)) [text()]
FROM @Table1
WHERE ID = t.ID
FOR XML PATH(''), TYPE)
.value('.','NVARCHAR(MAX)'),1,2,' ') List_Output
FROM @Table1 t
GROUP BY ID
Result Set
+--------------------------+
¦ ID ¦ List_Output ¦
¦----+---------------------¦
¦ 1 ¦ 100, 200, 300, 400 ¦
+--------------------------+
SQL Server 2017 and Later Versions
If you are working on SQL Server 2017 or later versions, you can use built-in SQL Server Function STRING_AGG to create the comma delimited list:
DECLARE @Table1 TABLE(ID INT, Value INT);
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400);
SELECT ID , STRING_AGG([Value], ', ') AS List_Output
FROM @Table1
GROUP BY ID;
Result Set
+--------------------------+
¦ ID ¦ List_Output ¦
¦----+---------------------¦
¦ 1 ¦ 100, 200, 300, 400 ¦
+--------------------------+
<section [ngClass]="{'class1': expression1, 'class2': expression2,
'class3': expression3}">
Don't forget to add single quotes around class names.
Even you can use like default value the value of another variable
having a file defvalue.sh
#!/bin/bash
variable1=$1
variable2=${2:-$variable1}
echo $variable1
echo $variable2
run ./defvalue.sh first-value second-value
output
first-value
second-value
and run ./defvalue.sh first-value
output
first-value
first-value
Depending on your usage, I had success with the following:
ssh root@server "script"
This will prompt for the root password and then execute the command correctly.
This will add a new column to your data.frame
with the specified format.
df$Month_Yr <- format(as.Date(df$Date), "%Y-%m")
df
#> ID Date Month_Yr
#> 1 1 2004-02-06 2004-02
#> 2 2 2006-03-14 2006-03
#> 3 3 2007-07-16 2007-07
# your data sample
df <- data.frame( ID=1:3,Date = c("2004-02-06" , "2006-03-14" , "2007-07-16") )
a simple example:
dates <- "2004-02-06"
format(as.Date(dates), "%Y-%m")
> "2004-02"
side note:
the data.table
approach can be quite faster in case you're working with a big dataset.
library(data.table)
setDT(df)[, Month_Yr := format(as.Date(Date), "%Y-%m") ]
I prefer to use the @ symbol so I see the query exactly as I can copy and paste into a query file:
string name = "Joe";
string gender = "M";
string query = String.Format(@"
SELECT
*
FROM
tableA
WHERE
Name = '{0}' AND
Gender = '{1}'", name, gender);
It's really great with long complex queries. Nice thing is it keeps tabs and line feeds so pasting into a query browser retains the nice formatting
Although it's okay to add a subview to a control, there's no guarantee it'll actually work, because the control might not expect it to be there and might thus behave poorly. If you can get away with it, just add the label as a sibling view of the button and set its frame so that it overlaps the button; as long as it's set to appear on top of the button, nothing the button can do will obscure it.
In other words:
[button.superview addSubview:myLabel];
myLabel.center = button.center;
Update: For a better approach, please refer to Blackus's answer in the same thread.
If you are not averse to using JavaScript and Regex, you can use the below solution to find all width
and height
properties in the style
attribute and replace
them with nothing.
//Get the value of style attribute based on element's Id
var originalStyle = document.getElementById('sample_id').getAttribute('style');
var regex = new RegExp(/(width:|height:).+?(;[\s]?|$)/g);
//Replace matches with null
var modStyle = originalStyle.replace(regex, "");
//Set the modified style value to element using it's Id
document.getElementById('sample_id').setAttribute('style', modStyle);
Is correct?
<script>
$( "#box" ).one( "click", function() {
$( this ).css( "width", "+=200" );
});
</script>
It would be better to implement a synchronization mechanism. The easiest is to write a file after the first file is complete. So you have a sentinel file.
So the external programs looks for the sentinel file to exist. When it does it knows that it can safely use the data in the real file.
Another way to do this, which is similar to how some browsers do it when downloading files, is to have the file named base-name_part until the file is completely downloaded and then at the end rename the file to base-name. This way the external program can't "see" the file until it is complete. This way wouldn't require rewrite of the external program. Which might make it best for this situation.
Please see this, more current solution before using a custom parsing function like below, or a 3rd party library.
The a code below works and is still useful in situations where URLSearchParams
is not available, but it was written in a time when there was no native solution available in JavaScript. In modern browsers or Node.js, prefer to use the built-in functionality.
function parseURLParams(url) {
var queryStart = url.indexOf("?") + 1,
queryEnd = url.indexOf("#") + 1 || url.length + 1,
query = url.slice(queryStart, queryEnd - 1),
pairs = query.replace(/\+/g, " ").split("&"),
parms = {}, i, n, v, nv;
if (query === url || query === "") return;
for (i = 0; i < pairs.length; i++) {
nv = pairs[i].split("=", 2);
n = decodeURIComponent(nv[0]);
v = decodeURIComponent(nv[1]);
if (!parms.hasOwnProperty(n)) parms[n] = [];
parms[n].push(nv.length === 2 ? v : null);
}
return parms;
}
Use as follows:
var urlString = "http://www.example.com/bar?a=a+a&b%20b=b&c=1&c=2&d#hash";
urlParams = parseURLParams(urlString);
which returns a an object like this:
{
"a" : ["a a"], /* param values are always returned as arrays */
"b b": ["b"], /* param names can have special chars as well */
"c" : ["1", "2"] /* an URL param can occur multiple times! */
"d" : [null] /* parameters without values are set to null */
}
So
parseURLParams("www.mints.com?name=something")
gives
{name: ["something"]}
EDIT: The original version of this answer used a regex-based approach to URL-parsing. It used a shorter function, but the approach was flawed and I replaced it with a proper parser.
I would suggest this:
$('input[type="radio"].toggle').click(function () {
var $rb = $(this);
if ($rb.val() === 'on') {
$rb.val('off');
this.checked = false;
}
else {
$rb.val('on');
this.checked = true;
}
});
Your HTML would look like this:
<input type="radio" class="toggle" value="off" />
"Better" is subjective.
querySelector
is the newer feature.
getElementById
is better supported than querySelector
.
querySelector
is better supported than getElementsByClassName
.
querySelector
lets you find elements with rules that can't be expressed with getElementById
and getElementsByClassName
You need to pick the appropriate tool for any given task.
(In the above, for querySelector
read querySelector
/ querySelectorAll
).
Create a git clone of that includes your Subversion trunk, tags, and branches with
git svn clone http://svn.example.com/project -T trunk -b branches -t tags
The --stdlayout
option is a nice shortcut if your Subversion repository uses the typical structure:
git svn clone http://svn.example.com/project --stdlayout
Make your git repository ignore everything the subversion repo does:
git svn show-ignore >> .git/info/exclude
You should now be able to see all the Subversion branches on the git side:
git branch -r
Say the name of the branch in Subversion is waldo
. On the git side, you'd run
git checkout -b waldo-svn remotes/waldo
The -svn suffix is to avoid warnings of the form
warning: refname 'waldo' is ambiguous.
To update the git branch waldo-svn
, run
git checkout waldo-svn git svn rebase
To add a Subversion branch to a trunk-only clone, modify your git repository's .git/config
to contain
[svn-remote "svn-mybranch"] url = http://svn.example.com/project/branches/mybranch fetch = :refs/remotes/mybranch
You'll need to develop the habit of running
git svn fetch --fetch-all
to update all of what git svn
thinks are separate remotes. At this point, you can create and track branches as above. For example, to create a git branch that corresponds to mybranch, run
git checkout -b mybranch-svn remotes/mybranch
For the branches from which you intend to git svn dcommit
, keep their histories linear!
You may also be interested in reading an answer to a related question.
Do you have multiple Radio Buttons on the page..
Because what I see is that you are assigning the events to all the radio button's on the page when you click on a radio button
Query 1: SELECT * FROM yourtable WHERE id > 0 ORDER BY id LIMIT 500
Query 2: SELECT * FROM tbl LIMIT 0,500;
Query 1 run faster with small or medium records, if number of records equal 5,000 or higher, the result are similar.
Result for 500 records:
Query1 take 9.9999904632568 milliseconds
Query2 take 19.999980926514 milliseconds
Result for 8,000 records:
Query1 take 129.99987602234 milliseconds
Query2 take 160.00008583069 milliseconds
NSLocationWhenInUseUsageDescription = Request permission to use location service when the apps is in background. in your plist file.
If this works then please vote the answer.
You can fix this problem by adding "$(ProjectDir)" (or wherever the stdafx.h is) to list of directories under Project->Properties->Configuration Properties->C/C++->General->Additional Include Directories.
I have got the JDK installed
You haven't specified the version. I think it is not 6 nor 5.
JDK 6 was the latest version at time of NetBeans 6.0 - 6.9 are developed. For that reason, They require JDK 6 (or JDK 5) and do not run on JDK 7 or later.
If the output of MAX(CreationDate) is not wanted - like in the example of the original question - the only answer is the second statement of Prashant Gupta's answer:
SELECT [Category] FROM [MonitoringJob]
GROUP BY [Category] ORDER BY MAX([CreationDate]) DESC
Explanation: you can't use the ORDER BY clause in an inline function, so the statement in the answer of Prutswonder is not useable in this case, you can't put an outer select around it and discard the MAX(CreationDate) part.