ctrl+a->(click)commands->cleanup word HTML
this will work as well
require_once(realpath($_SERVER["DOCUMENT_ROOT"]) .'/mysite/php/includes/dbconn.inc');
<a target="_blank" title="Share this page" href="http://www.sharethis.com/share?url=[INSERT URL]&title=[INSERT TITLE]&summary=[INSERT SUMMARY]&img=[INSERT IMAGE URL]&pageInfo=%7B%22hostname%22%3A%22[INSERT DOMAIN NAME]%22%2C%22publisher%22%3A%22[INSERT PUBLISHERID]%22%7D"><img width="86" height="25" alt="Share this page" src="http://w.sharethis.com/images/share-classic.gif"></a>
Instructions
First, insert these lines wherever you want within your newsletter code. Then:
If you are using this on an email newsletter, make sure you add our sharing buttons to the destination page. This will ensure that you get complete sharing analytics for your page. Make sure you replace "INSERT PUBLISHERID" with your own.
include() needs a full file path, relative to the file system's root directory.
This should work:
include_once("C:/xampp/htdocs/PoliticalForum/headerSite.php");
Use date format
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = format.parse(datetime);
SimpleDateFormat df = new SimpleDateFormat("yyyy");
year = df.format(date);
I have written a simple component using jQuery and bootstrap. Give it a try: https://github.com/mahpour/bootstrap-input-clear-button
Your mileage may vary (mine sure did), but here's what worked for me (current version of Chrome as of this post is 33.x, and I was interested in 24.x)
Visit the Chromium repo proxy lookup site: http://omahaproxy.appspot.com/
In the little box called "Revision Lookup" type in the version number. This will translate it to a Subversion revision number. Keep that number in mind.
Visit the build repository: http://commondatastorage.googleapis.com/chromium-browser-snapshots/index.html
Select the folder corresponding to the OS you're interested in (I have Win x64, but had to use Win,because there was no x64 build corresponding to the version I was looking for).
If you select Win, you could be in for a wait - as some of the pages have a lot of entries. Once the page loads, scroll to the folder containing the revision number you identified in an earlier step. If you don't find one, choose the next one up. This is a bit of trial and error to be honest - I had to back up about 50 revisions until I found a version close to the one I was looking for
Drill into that folder and download (on the Win version) chrome-win32.zip. That's all you need.
Unzip that file and then run chrome.exe
This worked for me and I'm running the latest Chrome alongside version 25, without problems (some profile issues on the older version, but that's neither here nor there). Didn't need to do anything else.
Again, YMMV, but try this solution first since it requires the least amount of tomfoolery.
Take a look at this answer: ImportError: no module named win32api
You can use
pip install pypiwin32
By the sounds of it you have an OnDelete/OnUpdate action on one of your existing Foreign Keys, that will modify your codes table.
So by creating this Foreign Key, you'd be creating a cyclic problem,
E.g. Updating Employees, causes Codes to changed by an On Update Action, causes Employees to be changed by an On Update Action... etc...
If you post your Table Definitions for both tables, & your Foreign Key/constraint definitions we should be able to tell you where the problem is...
You can use the following command to update any module with its dependencies
composer update vendor-name/module-name --with-dependencies
Installing CuDNN just involves placing the files in the CUDA directory. If you have specified the routes and the CuDNN option correctly while installing caffe it will be compiled with CuDNN.
You can check that using cmake
. Create a directory caffe/build
and run cmake ..
from there. If the configuration is correct you will see these lines:
-- Found cuDNN (include: /usr/local/cuda-7.0/include, library: /usr/local/cuda-7.0/lib64/libcudnn.so)
-- NVIDIA CUDA:
-- Target GPU(s) : Auto
-- GPU arch(s) : sm_30
-- cuDNN : Yes
If everything is correct just run the make
orders to install caffe from there.
Fast-forward merging makes sense for short-lived branches, but in a more complex history, non-fast-forward merging may make the history easier to understand, and make it easier to revert a group of commits.
Warning: Non-fast-forwarding has potential side effects as well. Please review https://sandofsky.com/blog/git-workflow.html, avoid the 'no-ff' with its "checkpoint commits" that break bisect or blame, and carefully consider whether it should be your default approach for master
.
(From nvie.com, Vincent Driessen, post "A successful Git branching model")
Incorporating a finished feature on develop
Finished features may be merged into the develop branch to add them to the upcoming release:
$ git checkout develop
Switched to branch 'develop'
$ git merge --no-ff myfeature
Updating ea1b82a..05e9557
(Summary of changes)
$ git branch -d myfeature
Deleted branch myfeature (was 05e9557).
$ git push origin develop
The
--no-ff
flag causes the merge to always create a new commit object, even if the merge could be performed with a fast-forward. This avoids losing information about the historical existence of a feature branch and groups together all commits that together added the feature.
Jakub Narebski also mentions the config merge.ff
:
By default, Git does not create an extra merge commit when merging a commit that is a descendant of the current commit. Instead, the tip of the current branch is fast-forwarded.
When set tofalse
, this variable tells Git to create an extra merge commit in such a case (equivalent to giving the--no-ff
option from the command line).
When set to 'only
', only such fast-forward merges are allowed (equivalent to giving the--ff-only
option from the command line).
The fast-forward is the default because:
But if you anticipate an iterative workflow on one topic/feature branch (i.e., I merge, then I go back to this feature branch and add some more commits), then it is useful to include only the merge in the main branch, rather than all the intermediate commits of the feature branch.
In this case, you can end up setting this kind of config file:
[branch "master"]
# This is the list of cmdline options that should be added to git-merge
# when I merge commits into the master branch.
# The option --no-commit instructs git not to commit the merge
# by default. This allows me to do some final adjustment to the commit log
# message before it gets commited. I often use this to add extra info to
# the merge message or rewrite my local branch names in the commit message
# to branch names that are more understandable to the casual reader of the git log.
# Option --no-ff instructs git to always record a merge commit, even if
# the branch being merged into can be fast-forwarded. This is often the
# case when you create a short-lived topic branch which tracks master, do
# some changes on the topic branch and then merge the changes into the
# master which remained unchanged while you were doing your work on the
# topic branch. In this case the master branch can be fast-forwarded (that
# is the tip of the master branch can be updated to point to the tip of
# the topic branch) and this is what git does by default. With --no-ff
# option set, git creates a real merge commit which records the fact that
# another branch was merged. I find this easier to understand and read in
# the log.
mergeoptions = --no-commit --no-ff
The OP adds in the comments:
I see some sense in fast-forward for [short-lived] branches, but making it the default action means that git assumes you... often have [short-lived] branches. Reasonable?
Jefromi answers:
I think the lifetime of branches varies greatly from user to user. Among experienced users, though, there's probably a tendency to have far more short-lived branches.
To me, a short-lived branch is one that I create in order to make a certain operation easier (rebasing, likely, or quick patching and testing), and then immediately delete once I'm done.
That means it likely should be absorbed into the topic branch it forked from, and the topic branch will be merged as one branch. No one needs to know what I did internally in order to create the series of commits implementing that given feature.
More generally, I add:
it really depends on your development workflow:
- if it is linear, one branch makes sense.
- If you need to isolate features and work on them for a long period of time and repeatedly merge them, several branches make sense.
See "When should you branch?"
Actually, when you consider the Mercurial branch model, it is at its core one branch per repository (even though you can create anonymous heads, bookmarks and even named branches)
See "Git and Mercurial - Compare and Contrast".
Mercurial, by default, uses anonymous lightweight codelines, which in its terminology are called "heads".
Git uses lightweight named branches, with injective mapping to map names of branches in remote repository to names of remote-tracking branches.
Git "forces" you to name branches (well, with the exception of a single unnamed branch, which is a situation called a "detached HEAD"), but I think this works better with branch-heavy workflows such as topic branch workflow, meaning multiple branches in a single repository paradigm.
Taking help from above answer link mentioned in the above answer sets the max value with option
yAxis: { max: 100 },
On similar line min value can be set.So if you want to set min-max value then
yAxis: {
min: 0,
max: 100
},
If you are using HighRoller php library for integration if Highchart graphs then you just need to set the option
$series->yAxis->min=0;
$series->yAxis->max=100;
There are a lot of good answers here. I had the same need after reloading my Django database.
But I needed:
This seems very similar need to what the original ask was for.
Thanks to Baldiry and Mauro got me on the right track.
drop function IF EXISTS reset_sequences(text[], text) RESTRICT;
CREATE OR REPLACE FUNCTION reset_sequences(
in_schema_name_list text[] = '{"django", "dbaas", "metrics", "monitor", "runner", "db_counts"}',
in_table_name text = '%') RETURNS text[] as
$body$
DECLARE changed_seqs text[];
DECLARE sequence_defs RECORD; c integer ;
BEGIN
FOR sequence_defs IN
select
DISTINCT(ccu.table_name) as table_name,
ccu.column_name as column_name,
replace(replace(c.column_default,'''::regclass)',''),'nextval(''','') as sequence_name
from information_schema.constraint_column_usage ccu,
information_schema.columns c
where ccu.table_schema = ANY(in_schema_name_list)
and ccu.table_schema = c.table_schema
AND c.table_name = ccu.table_name
and c.table_name like in_table_name
AND ccu.column_name = c.column_name
AND c.column_default is not null
ORDER BY sequence_name
LOOP
EXECUTE 'select max(' || sequence_defs.column_name || ') from ' || sequence_defs.table_name INTO c;
IF c is null THEN c = 1; else c = c + 1; END IF;
EXECUTE 'alter sequence ' || sequence_defs.sequence_name || ' restart with ' || c;
changed_seqs = array_append(changed_seqs, 'alter sequence ' || sequence_defs.sequence_name || ' restart with ' || c);
END LOOP;
changed_seqs = array_append(changed_seqs, 'Done');
RETURN changed_seqs;
END
$body$ LANGUAGE plpgsql;
Then to Execute and See the changes run:
select *
from unnest(reset_sequences('{"django", "dbaas", "metrics", "monitor", "runner", "db_counts"}'));
Returns
activity_id_seq restart at 22
api_connection_info_id_seq restart at 4
api_user_id_seq restart at 1
application_contact_id_seq restart at 20
If you're going for simple, you can avoid the "new" keyword entirely and just use factory methods. I prefer this, sometimes, because I like using JSON to create objects.
function getSomeObj(var1, var2){
var obj = {
instancevar1: var1,
instancevar2: var2,
someMethod: function(param)
{
//stuff;
}
};
return obj;
}
var myobj = getSomeObj("var1", "var2");
myobj.someMethod("bla");
I'm not sure what the performance hit is for large objects, though.
Hate to be the one to bump an old subject, but I found this post extremely useful. After running performance tests on the snippets by stej and it's refinement by Graham Gold, plus the BITS suggestion by Nacht, I have decuded that:
Faced with the decision between the two... I found that Start-BitsTransfer supported Asynchronous mode. So here is the result of my merging the two.
function Copy-File {
# ref: https://stackoverflow.com/a/55527732/3626361
param([string]$From, [string]$To)
try {
$job = Start-BitsTransfer -Source $From -Destination $To `
-Description "Moving: $From => $To" `
-DisplayName "Backup" -Asynchronous
# Start stopwatch
$sw = [System.Diagnostics.Stopwatch]::StartNew()
Write-Progress -Activity "Connecting..."
while ($job.JobState.ToString() -ne "Transferred") {
switch ($job.JobState.ToString()) {
"Connecting" {
break
}
"Transferring" {
$pctcomp = ($job.BytesTransferred / $job.BytesTotal) * 100
$elapsed = ($sw.elapsedmilliseconds.ToString()) / 1000
if ($elapsed -eq 0) {
$xferrate = 0.0
}
else {
$xferrate = (($job.BytesTransferred / $elapsed) / 1mb);
}
if ($job.BytesTransferred % 1mb -eq 0) {
if ($pctcomp -gt 0) {
$secsleft = ((($elapsed / $pctcomp) * 100) - $elapsed)
}
else {
$secsleft = 0
}
Write-Progress -Activity ("Copying file '" + ($From.Split("\") | Select-Object -last 1) + "' @ " + "{0:n2}" -f $xferrate + "MB/s") `
-PercentComplete $pctcomp `
-SecondsRemaining $secsleft
}
break
}
"Transferred" {
break
}
Default {
throw $job.JobState.ToString() + " unexpected BITS state."
}
}
}
$sw.Stop()
$sw.Reset()
}
finally {
Complete-BitsTransfer -BitsJob $job
Write-Progress -Activity "Completed" -Completed
}
}
The solution is quite simple ... you're reading getchar() which gives you the first character in the input buffer, and scanf just parsed it (really don't know why) to an integer, if you just forget the getchar for a second, it will read the full buffer until a newline char.
printf("> ");
int x;
scanf("%d", &x);
printf("got the number: %d", x);
> [prompt expecting input, lets write:] 1234 [Enter]
got the number: 1234
First, you have to create two animation resources in res/anim dir
slide_up.xml
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:duration="@android:integer/config_mediumAnimTime"
android:fromYDelta="100%"
android:interpolator="@android:anim/accelerate_interpolator"
android:toXDelta="0">
</translate>
</set>
slide_bottom.xml
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:duration="@android:integer/config_mediumAnimTime"
android:fromYDelta="0%p"
android:interpolator="@android:anim/accelerate_interpolator"
android:toYDelta="100%p">
</translate>
</set>
then you have to create a style
<style name="DialogAnimation">
<item name="android:windowEnterAnimation">@anim/slide_up</item>
<item name="android:windowExitAnimation">@anim/slide_bottom</item>
</style>
and add this line to your class
dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation; //style id
Based in http://www.devexchanges.info/2015/10/showing-dialog-with-animation-in-android.html
If you don't want to use a download manager then you can use this code
webView.setDownloadListener(new DownloadListener() {
@Override
public void onDownloadStart(String url, String userAgent, String contentDisposition
, String mimetype, long contentLength) {
String fileName = URLUtil.guessFileName(url, contentDisposition, mimetype);
try {
String address = Environment.getExternalStorageDirectory().getAbsolutePath() + "/"
+ Environment.DIRECTORY_DOWNLOADS + "/" +
fileName;
File file = new File(address);
boolean a = file.createNewFile();
URL link = new URL(url);
downloadFile(link, address);
} catch (Exception e) {
e.printStackTrace();
}
}
});
public void downloadFile(URL url, String outputFileName) throws IOException {
try (InputStream in = url.openStream();
ReadableByteChannel rbc = Channels.newChannel(in);
FileOutputStream fos = new FileOutputStream(outputFileName)) {
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
}
// do your work here
}
This will download files in the downloads folder in phone storage. You can use threads if you want to download that in the background (use thread.alive() and timer class to know the download is complete or not). This is useful when we download small files, as you can do the next task just after the download.
Solution given by Shashi's link is the best... no needs to contact dba or someone else
make a backup
create table xxxx_backup as select * from xxxx;
delete all rows
delete from xxxx;
commit;
insert your backup.
insert into xxxx (select * from xxxx_backup);
commit;
MySQL has 4 levels of collation: server, database, table, column. If you change the collation of the server, database or table, you don't change the setting for each column, but you change the default collations.
E.g if you change the default collation of a database, each new table you create in that database will use that collation, and if you change the default collation of a table, each column you create in that table will get that collation.
Can I do it dynamically?
Create view class:
public class View {
static class Public { }
static class ExtendedPublic extends Public { }
static class Internal extends ExtendedPublic { }
}
Annotate you model
@Document
public class User {
@Id
@JsonView(View.Public.class)
private String id;
@JsonView(View.Internal.class)
private String email;
@JsonView(View.Public.class)
private String name;
@JsonView(View.Public.class)
private Instant createdAt = Instant.now();
// getters/setters
}
Specify the view class in your controller
@RequestMapping("/user/{email}")
public class UserController {
private final UserRepository userRepository;
@Autowired
UserController(UserRepository userRepository) {
this.userRepository = userRepository;
}
@RequestMapping(method = RequestMethod.GET)
@JsonView(View.Internal.class)
public @ResponseBody Optional<User> get(@PathVariable String email) {
return userRepository.findByEmail(email);
}
}
Data example:
{"id":"5aa2496df863482dc4da2067","name":"test","createdAt":"2018-03-10T09:35:31.050353800Z"}
When you have a copy of an object the [checked]
attribute might not work, in that case, you can use (change)
in this way:
<input type="checkbox" [checked]="item.selected" (change)="item.selected = !item.selected">
Note: I now this is not the answer for the post, but maybe this will be helpful for some one that is looking.
If Nothing of this works for you, try on a Mac this to see if helps you, in the last version of Android Studio, the studio.vmoptions is inside the AndroidStudio.app in your Applications folder.
So right click or ctrl click on your AndroidStudio.App and then select show package content the studio.vmoptions is in:
Contents/bin/studio.vmoptions
Replace or change it and you will get all the RAM you need.
Regards.
If you logged into "phpmyadmin", then logged out, you might have trouble attempting to log back in on the same browser window. The logout sends the browser to a URL that looks like this:
http://localhost/phpmyadmin/index.php?db=&token=354a350abed02588e4b59f44217826fd&old_usr=tester
But for me, on Mac OS X in Safari browser, that URL just doesn't want to work. Therefore, I have to put in the clean URL:
http://localhost/phpmyadmin
Don't know why, but as of today, Oct 20, 2015, that is what I am experiencing.
Solutions suggested above will work only if data is aligned..
See solution in the link using PythonScript Notepad++ plugin, It Works great!
I solved this problem very simply using a little hack in the adapter. Here is my code:
public class MyPagerAdapter extends FragmentStatePagerAdapter
{
public static int LOOPS_COUNT = 1000;
private ArrayList<Product> mProducts;
public MyPagerAdapter(FragmentManager manager, ArrayList<Product> products)
{
super(manager);
mProducts = products;
}
@Override
public Fragment getItem(int position)
{
if (mProducts != null && mProducts.size() > 0)
{
position = position % mProducts.size(); // use modulo for infinite cycling
return MyFragment.newInstance(mProducts.get(position));
}
else
{
return MyFragment.newInstance(null);
}
}
@Override
public int getCount()
{
if (mProducts != null && mProducts.size() > 0)
{
return mProducts.size()*LOOPS_COUNT; // simulate infinite by big number of products
}
else
{
return 1;
}
}
}
And then, in the ViewPager, we set current page to the middle:
mAdapter = new MyPagerAdapter(getSupportFragmentManager(), mProducts);
mViewPager.setAdapter(mAdapter);
mViewPager.setCurrentItem(mViewPager.getChildCount() * MyPagerAdapter.LOOPS_COUNT / 2, false); // set current item in the adapter to middle
Try operator instanceof
.
Laravel optional() Helper is comes to solve this problem. Try this helper so that if any key have not value then it not return error
foreach ($sample_arr as $key => $value) {
$sample_data[] = array(
'client_phone' =>optional($users)->phone
);
}
print_r($sample_data);
You can't. CSS is a presentation language. It isn't designed to add content (except for the very trivial with :before
and :after
).
In [56]: df = pd.DataFrame(np.abs(randn(3, 4)), index=[1,2,3], columns=['A','B','C','D'])
In [57]: df.divide(df.sum(axis=1), axis=0)
Out[57]:
A B C D
1 0.319124 0.296653 0.138206 0.246017
2 0.376994 0.326481 0.230464 0.066062
3 0.036134 0.192954 0.430341 0.340571
I've just used Excel 2016 to open Access 2003 tables.
You can use the utility method in Collections
class
public static <T extends Comparable<? super T>> void sort(List<T> list)
or
public static <T> void sort(List<T> list,Comparator<? super T> c)
Refer to Comparable
and Comparator
interfaces for more flexibility on sorting the object.
You are looking for wctomb()
: it's in the ANSI standard, so you can count on it. It works even when the wchar_t
uses a code above 255. You almost certainly do not want to use it.
wchar_t
is an integral type, so your compiler won't complain if you actually do:
char x = (char)wc;
but because it's an integral type, there's absolutely no reason to do this. If you accidentally read Herbert Schildt's C: The Complete Reference, or any C book based on it, then you're completely and grossly misinformed. Characters should be of type int
or better. That means you should be writing this:
int x = getchar();
and not this:
char x = getchar(); /* <- WRONG! */
As far as integral types go, char
is worthless. You shouldn't make functions that take parameters of type char
, and you should not create temporary variables of type char
, and the same advice goes for wchar_t
as well.
char*
may be a convenient typedef for a character string, but it is a novice mistake to think of this as an "array of characters" or a "pointer to an array of characters" - despite what the cdecl tool says. Treating it as an actual array of characters with nonsense like this:
for(int i = 0; s[i]; ++i) {
wchar_t wc = s[i];
char c = doit(wc);
out[i] = c;
}
is absurdly wrong. It will not do what you want; it will break in subtle and serious ways, behave differently on different platforms, and you will most certainly confuse the hell out of your users. If you see this, you are trying to reimplement wctombs()
which is part of ANSI C already, but it's still wrong.
You're really looking for iconv()
, which converts a character string from one encoding (even if it's packed into a wchar_t
array), into a character string of another encoding.
Now go read this, to learn what's wrong with iconv.
Start Visual Studio. Go to Tools->Options and expand Projects and solutions. Select VC++ Directories from the tree and choose Include Files from the combo on the right.
You should see:
$(WindowsSdkDir)\include
If this is missing, you found a problem. If not, search for a file. It should be located in
32 bit systems:
C:\Program Files\Microsoft SDKs\Windows\v6.0A\Include
64 bit systems:
C:\Program Files (x86)\Microsoft SDKs\Windows\v6.0A\Include
if VS was installed in the default directory.
Use below command on UNIX terminal :
java -XshowSettings
This will display all java properties and system settings.
In this look for java.io.tmpdir
value.
require
loads a file from the $LOAD_PATH
. If you want to require a file relative to the currently executing file instead of from the $LOAD_PATH
, use require_relative
.
This is working code:
<html>
<body bgcolor=cyan>
<img src ="backgr1.JPG" id="my" width="310" height="392" style="position: absolute; top:92px; left:375px; visibility:hidden"/>
<script type="text/javascript">
function tend() {
document.getElementById('my').style.visibility='visible';
}
function tn() {
document.getElementById('my').style.visibility='hidden';
}
</script>
<input type="button" onclick="tend()" value="back">
<input type="button" onclick="tn()" value="close">
</body>
</html>
Ugh everyone's answers on here are incomplete, and lets stop using jquery in SO answers already please. Check jquery's documentation if you want info on jquery.
Here's a generalized pure-javascript function for testing whether or not an element has scrollbars in a complete way:
// dimension - Either 'y' or 'x'
// computedStyles - (Optional) Pass in the domNodes computed styles if you already have it (since I hear its somewhat expensive)
function hasScrollBars(domNode, dimension, computedStyles) {
dimension = dimension.toUpperCase()
if(dimension === 'Y') {
var length = 'Height'
} else {
var length = 'Width'
}
var scrollLength = 'scroll'+length
var clientLength = 'client'+length
var overflowDimension = 'overflow'+dimension
var hasVScroll = domNode[scrollLength] > domNode[clientLength]
// Check the overflow and overflowY properties for "auto" and "visible" values
var cStyle = computedStyles || getComputedStyle(domNode)
return hasVScroll && (cStyle[overflowDimension] == "visible"
|| cStyle[overflowDimension] == "auto"
)
|| cStyle[overflowDimension] == "scroll"
}
For *nix you can use a shell_exec
for rm -R
or DEL /S folder_name
for Windows.
<session-config>
<session-timeout>-1</session-timeout>
</session-config>
In the above code "60" stands for the minutes.
The session will expired after 60 minutes.
So if you want to more time. For Example -1
that is described your session never expires.
It worked for me.
Here is my test code. Test run follows:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
FileInfo f = new FileInfo(args[0]);
bool result = modifyFile(f, args[1],args[2]);
}
private static bool modifyFile(FileInfo file, string extractedMethod, string modifiedMethod)
{
Boolean result = false;
FileStream fs = new FileStream(file.FullName + ".tmp", FileMode.Create, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
StreamReader streamreader = file.OpenText();
String originalPath = file.FullName;
string input = streamreader.ReadToEnd();
Console.WriteLine("input : {0}", input);
String tempString = input.Replace(extractedMethod, modifiedMethod);
Console.WriteLine("replaced String {0}", tempString);
try
{
sw.Write(tempString);
sw.Flush();
sw.Close();
sw.Dispose();
fs.Close();
fs.Dispose();
streamreader.Close();
streamreader.Dispose();
File.Copy(originalPath, originalPath + ".old", true);
FileInfo newFile = new FileInfo(originalPath + ".tmp");
File.Delete(originalPath);
File.Copy(originalPath + ".tmp", originalPath, true);
result = true;
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
return result;
}
}
}
C:\testarea>ConsoleApplication1.exe file.txt padding testing
input : <style type="text/css">
<!--
#mytable {
border-collapse: collapse;
width: 300px;
}
#mytable th,
#mytable td
{
border: 1px solid #000;
padding: 3px;
}
#mytable tr.highlight {
background-color: #eee;
}
//-->
</style>
replaced String <style type="text/css">
<!--
#mytable {
border-collapse: collapse;
width: 300px;
}
#mytable th,
#mytable td
{
border: 1px solid #000;
testing: 3px;
}
#mytable tr.highlight {
background-color: #eee;
}
//-->
</style>
above given methods are for if you have an web url ,but if you have an local html then you can have also html by this code
AssetManager mgr = mContext.getAssets();
try {
InputStream in = null;
if(condition)//you have a local html saved in assets
{
in = mgr.open(mFileName,AssetManager.ACCESS_BUFFER);
}
else if(condition)//you have an url
{
URL feedURL = new URL(sURL);
in = feedURL.openConnection().getInputStream();}
// here you will get your html
String sHTML = streamToString(in);
in.close();
//display this html in the browser or web view
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public static String streamToString(InputStream in) throws IOException {
if(in == null) {
return "";
}
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
}
return writer.toString();
}
ruby on rails notes has a very nice blogpost about commenting in erb-files
the short version is
to comment a single line use
<%# commented line %>
to comment a whole block use a if false
to surrond your code like this
<% if false %>
code to comment
<% end %>
In my case where each splash screen was individually designed instead of autogenerated or laid out in a story board format, I had to stick with my Legacy Launch screen configuration and add portrait and landscape images to target iPhoneX 1125×2436 orientations to the config.xml like so:
<splash height="2436" src="resources/ios/splash/Default-2436h.png" width="1125" />
<splash height="1125" src="resources/ios/splash/Default-Landscape-2436h.png" width="2436" />
After adding these to config.xml ("viewport-fit=cover" was already set in index.hml) my app built with Ionic Pro fills the entire screen on iPhoneX devices.
Here is an answer that should work in all cases:
def is_empty(s):
"Check whether a string is empty"
return not s or not s.strip()
If the variable is None, it will stop at not s
and not evaluate further (since not None == True
). Apparently, the strip()
method takes care of the usual cases of tab, newline, etc.
I faced the same exception "TransactionRequiredException Executing an update/delete query" but for me the reason was that I've created another bean in the spring applicationContext.xml file with the name "transactionManager" refering to "org.springframework.jms.connection.JmsTransactionManager" however there was another bean with the same name "transactionManager" refering to "org.springframework.orm.jpa.JpaTransactionManager". So the JPA bean is overriten by the JMS bean.
After renaming the bean name of the Jms, issue is resolved.
Check out the recently1 released upload handler from the guys that created the TinyMCE editor. It has a jQuery widget and looks like it has a nice set of features and fallbacks.
public static int countWords(String s){
int wordCount = 0;
boolean word = false;
int endOfLine = s.length() - 1;
for (int i = 0; i < s.length(); i++) {
// if the char is a letter, word = true.
if (Character.isLetter(s.charAt(i)) && i != endOfLine) {
word = true;
// if char isn't a letter and there have been letters before,
// counter goes up.
} else if (!Character.isLetter(s.charAt(i)) && word) {
wordCount++;
word = false;
// last word of String; if it doesn't end with a non letter, it
// wouldn't count without this.
} else if (Character.isLetter(s.charAt(i)) && i == endOfLine) {
wordCount++;
}
}
return wordCount;
}
I ran into a similar problem where I have a dependency property that I wanted the class to listen to change events to grab related data from a service.
public static readonly DependencyProperty CustomerProperty =
DependencyProperty.Register("Customer", typeof(Customer),
typeof(CustomerDetailView),
new PropertyMetadata(OnCustomerChangedCallBack));
public Customer Customer {
get { return (Customer)GetValue(CustomerProperty); }
set { SetValue(CustomerProperty, value); }
}
private static void OnCustomerChangedCallBack(
DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
CustomerDetailView c = sender as CustomerDetailView;
if (c != null) {
c.OnCustomerChanged();
}
}
protected virtual void OnCustomerChanged() {
// Grab related data.
// Raises INotifyPropertyChanged.PropertyChanged
OnPropertyChanged("Customer");
}
Try echo_read_request_body.
"echo_read_request_body ... Explicitly reads request body so that the $request_body variable will always have non-empty values (unless the body is so big that it has been saved by Nginx to a local temporary file)."
location /log {
log_format postdata $request_body;
access_log /mnt/logs/nginx/my_tracking.access.log postdata;
echo_read_request_body;
}
Just set ng-init as a function. You should not have to use watch.
<body ng-controller="MainCtrl" ng-init="init()">
<div ng-init="init('Blah')">{{ testInput }}</div>
</body>
app.controller('MainCtrl', ['$scope', function ($scope) {
$scope.testInput = null;
$scope.init = function(value) {
$scope.testInput= value;
}
}]);
Here's an example.
<a class="btn btn-large btn-success" id="fire" href="http://twitter.github.io/bootstrap/examples/marketing-narrow.html#">Send Email</a>
$('#fire').on('click', function (e) {
//your awesome code here
})
Rather than needing inline you could use Internal CSS
<a href="http://www.google.com" style="hover:text-decoration:none;">Google</a>
You could have:
<a href="http://www.google.com" id="gLink">Google</a>
<style>
#gLink:hover {
text-decoration: none;
}
</style>
afaik iPhone uses "Helvetica" by default < iOS 10
def safeget(_dct, *_keys):
if not isinstance(_dct, dict): raise TypeError("Is not instance of dict")
def foo(dct, *keys):
if len(keys) == 0: return dct
elif not isinstance(_dct, dict): return None
else: return foo(dct.get(keys[0], None), *keys[1:])
return foo(_dct, *_keys)
assert safeget(dict()) == dict()
assert safeget(dict(), "test") == None
assert safeget(dict([["a", 1],["b", 2]]),"a", "d") == None
assert safeget(dict([["a", 1],["b", 2]]),"a") == 1
assert safeget({"a":{"b":{"c": 2}},"d":1}, "a", "b")["c"] == 2
Had this exception even changed to
"audio/*"
But thanx to @Stan i have turned very simple but usefully solution:
Uri.fromFile(File(content))
instead Uri.parse(path)
val intent =Intent(Intent.ACTION_VIEW)
intent.setDataAndType(Uri.fromFile(File(content)),"audio/*")
startActivity(intent)
Even if you do start the executable outside Visual Studio, you can still use the "Attach" command to connect Visual Studio to your already-running executable. This can be useful e.g. when your application is run as a plug-in within another application.
None of the others worked for me. I had to add the following dependency, as explained here
compile group: 'cz.msebera.android' , name: 'httpclient', version: '4.4.1.1'
because I was targeting API 23.
The first case (export default {...}
) is ES2015 syntax for making some object definition available for use.
The second case (new Vue (...)
) is standard syntax for instantiating an object that has been defined.
The first will be used in JS to bootstrap Vue, while either can be used to build up components and templates.
See https://vuejs.org/v2/guide/components-registration.html for more details.
How about using object properties as a hash table? This way your best scenario is to only randomize 8 times. It would only be effective if you want a small part of the range of numbers. It's also much less memory intensive than Fisher-Yates because you don't have to allocate space for an array.
var ht={}, i=rands=8;
while ( i>0 || keys(ht).length<rands) ht[Math.ceil(Math.random()*100)]=i--;
alert(keys(ht));
I then found out that Object.keys(obj) is an ECMAScript 5 feature so the above is pretty much useless on the internets right now. Fear not, because I made it ECMAScript 3 compatible by adding a keys function like this.
if (typeof keys == "undefined")
{
var keys = function(obj)
{
props=[];
for (k in ht) if (ht.hasOwnProperty(k)) props.push(k);
return props;
}
}
FirstOrDefault or SingleOrDefault might be useful, depending on your scenario, and whether you want to handle there being zero or more than one matches:
FirstOrDefault: Returns the first element of a sequence, or a default value if no element is found.
SingleOrDefault: Returns the only element of a sequence, or a default value if the sequence is empty; this method throws an exception if there is more than one element in the sequence
I don't know how this works in a linq 'from' query but in lambda syntax it looks like this:
var item1 = Items.FirstOrDefault(x => x.Id == 123);
var item2 = Items.SingleOrDefault(x => x.Id == 123);
help=>install new software=>workwith choice Juno - http://download.eclipse.org/releases/juno and search in the below "type filter text" --------------market
you will see this plugs Marketplace Client
I've just run in a similar issue. git diff file
showed nothing because I added file to the Git index with some part of its name in uppercase: GeoJSONContainer.js
.
Afterwards, I've renamed it to GeoJsonContainer.js
and changes stopped being tracked. git diff GeoJsonContainer.js
was showing nothing. I had to remove the file from the index with a force flag, and add the file again:
git rm -f GeoJSONContainer.js
git add GeoJSONContainer.js
IPv4 address is a very complicated thing.
Note: Indentation and lining are only for illustration purposes and do not exist in the real RegEx.
\b(
((
(2(5[0-5]|[0-4][0-9])|1[0-9]{2}|[1-9]?[0-9])
|
0[Xx]0*[0-9A-Fa-f]{1,2}
|
0+[1-3]?[0-9]{1,2}
)\.){1,3}
(
(2(5[0-5]|[0-4][0-9])|1[0-9]{2}|[1-9]?[0-9])
|
0[Xx]0*[0-9A-Fa-f]{1,2}
|
0+[1-3]?[0-9]{1,2}
)
|
(
[1-3][0-9]{1,9}
|
[1-9][0-9]{,8}
|
(4([0-1][0-9]{8}
|2([0-8][0-9]{7}
|9([0-3][0-9]{6}
|4([0-8][0-9]{5}
|9([0-5][0-9]{4}
|6([0-6][0-9]{3}
|7([0-1][0-9]{2}
|2([0-8][0-9]{1}
|9([0-5]
))))))))))
)
|
0[Xx]0*[0-9A-Fa-f]{1,8}
|
0+[1-3]?[0-7]{,10}
)\b
These IPv4 addresses are validated by the above RegEx.
127.0.0.1
2130706433
0x7F000001
017700000001
0x7F.0.0.01 # Mixed hex/dec/oct
000000000017700000001 # Have as many leading zeros as you want
0x0000000000007F000001 # Same as above
127.1
127.0.1
These are rejected.
256.0.0.1
192.168.1.099 # 099 is not a valid number
4294967296 # UINT32_MAX + 1
0x100000000
020000000000
I was testing a CORS web service on my dev machine and was getting the "Access is denied" error message in only IE. Firefox and Chrome worked fine. It turns out this was caused by my use of localhost in the ajax call! So my browser URL was something like:
http://my_computer.my_domain.local/CORS_Service/test.html
and my ajax call inside of test.html was something like:
//fails in IE
$.ajax({
url: "http://localhost/CORS_Service/api/Controller",
...
});
Everything worked once I changed the ajax call to use my computer IP instead of localhost.
//Works in IE
$.ajax({
url: "http://192.168.0.1/CORS_Service/api/Controller",
...
});
The IE dev tools window "Network" tab also shows CORS Preflight OPTIONS request followed by the XMLHttpRequest GET, which is exactly what I expected to see.
$(document).ready(function(){
$('#userForm').on('submit', function(e){
e.preventDefault();
//I had an issue that the forms were submitted in geometrical progression after the next submit.
// This solved the problem.
e.stopImmediatePropagation();
// show that something is loading
$('#response').html("<b>Loading data...</b>");
// Call ajax for pass data to other place
$.ajax({
type: 'POST',
url: 'somephpfile.php',
data: $(this).serialize() // getting filed value in serialize form
})
.done(function(data){ // if getting done then call.
// show the response
$('#response').html(data);
})
.fail(function() { // if fail then getting message
// just in case posting your form failed
alert( "Posting failed." );
});
// to prevent refreshing the whole page page
return false;
});
I created a jar
library called JCDP (Java Colored Debug Printer).
For Linux it uses the ANSI escape codes that WhiteFang mentioned, but abstracts them using words instead of codes which is much more intuitive.
For Windows it actually includes the JAnsi library but creates an abstraction layer over it, maintaining the intuitive and simple interface created for Linux.
This library is licensed under the MIT License so feel free to use it.
Have a look at JCDP's github repository.
I used the
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ScrollView01"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RelativeLayout
and works perfectly
You should be using pip
to install packages, since it gives you uninstall capabilities.
Also, look into virtualenv
. It works well with pip
and gives you a sandbox so you can explore new stuff without accidentally hosing your system-wide install.
Not the simplest way but if you're a fan of recursion you might be interested in the following method to reverse an ArrayList:
public ArrayList<Object> reverse(ArrayList<Object> list) {
if(list.size() > 1) {
Object value = list.remove(0);
reverse(list);
list.add(value);
}
return list;
}
Or non-recursively:
public ArrayList<Object> reverse(ArrayList<Object> list) {
for(int i = 0, j = list.size() - 1; i < j; i++) {
list.add(i, list.remove(j));
}
return list;
}
I didn't like the slide effect either. To fix this all you have to do is make the the top
attribute the same for both .modal.fade and modal.fade.in. You can take off the top 0.3s ease-out
in the transitions too, but it doesn't hurt to leave it in. I like this approach because the fade in/out works, it just kills the slide.
.modal.fade {
top: 20%;
-webkit-transition: opacity 0.3s linear;
-moz-transition: opacity 0.3s linear;
-o-transition: opacity 0.3s linear;
transition: opacity 0.3s linear;
}
.modal.fade.in {
top: 20%;
}
If you're looking for a bootstrap 3 answer, look here
Using numpy, you can do:
y = x.astype(int)
If you were using a non-numpy array, you could use a list comprehension:
y = [int(val) for val in x]
As already mentioned, array_unique() could be used, but only when dealing with simple data. The objects are not so simple to handle.
When php tries to merge the arrays, it tries to compare the values of the array members. If a member is an object, it cannot get its value and uses the spl hash instead. Read more about spl_object_hash here.
Simply told if you have two objects, instances of the very same class and if one of them is not a reference to the other one - you will end up having two objects, no matter the value of their properties.
To be sure that you don't have any duplicates within the merged array, Imho you should handle the case on your own.
Also if you are going to merge multidimensional arrays, consider using array_merge_recursive() over array_merge().
If you want something prettier I would advise
{"<?php\n\$data =\n"|@cat:{$yourvariable|@var_export:true|@cat:";\n?>"}|@highlight_string:true}
just replace yourvariable by your variable
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
like a Back press
Keep a reference to the timer somewhere, and use:
timer.cancel();
timer.purge();
to stop whatever it's doing. You could put this code inside the task you're performing with a static int
to count the number of times you've gone around, e.g.
private static int count = 0;
public static void run() {
count++;
if (count >= 6) {
timer.cancel();
timer.purge();
return;
}
... perform task here ....
}
urls.py:
#...
url(r'element/update/(?P<pk>\d+)/$', 'element.views.element_update', name='element_update'),
views.py:
from django.shortcuts import redirect
from .models import Element
def element_info(request):
# ...
element = Element.object.get(pk=1)
return redirect('element_update', pk=element.id)
def element_update(request, pk)
# ...
Looking at your example, I think this is what you want:
var dict = TableObj.ToDictionary(t => t.Key, t=> t.TimeStamp);
List<T>
has a Reverse()
method, however it only reverses the order of two (or more) consecutive items.
your_list.Reverse(index, 2);
Where the second parameter 2
indicates we are reversing the order of 2 items, starting with the item at the given index
.
Source: https://msdn.microsoft.com/en-us/library/hf2ay11y(v=vs.110).aspx
Whenever possible, avoid applying functions to a column in the where clause:
SELECT *
FROM table_name
WHERE timestamp >= UNIX_TIMESTAMP('2010-10-01 00:00:00')
AND timestamp < UNIX_TIMESTAMP('2010-11-01 00:00:00');
Applying a function to the timestamp column (e.g., FROM_UNIXTIME(timestamp) = ...) makes indexing much harder.
Jacob Helwig mentions in his answer that:
It looks like rev-parse is being used without sufficient error checking before-hand
Commit 62f162f from Jeff King (peff
) should improve the robustness of git rev-parse
in Git 1.9/2.0 (Q1 2014) (in addition of commit 1418567):
For cases where we do not match (e.g., "
doesnotexist..HEAD
"), we would then want to try to treat the argument as a filename.
try_difference()
gets this right, and always unmunges in this case.
However,try_parent_shorthand()
never unmunges, leading to incorrect error messages, or even incorrect results:
$ git rev-parse foobar^@
foobar
fatal: ambiguous argument 'foobar': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'
If you like to call an activity method from within a custom layout class(non-Activity Class).You should create a delegate using interface.
It is untested and i coded it right . but i am conveying a way to achieve what you want.
First of all create and Interface
interface TaskCompleteListener<T> {
public void onProfileClicked(T result);
}
public class ProfileView extends LinearLayout
{
private TaskCompleteListener<String> callback;
TextView profileTitleTextView;
ImageView profileScreenImageButton;
boolean isEmpty;
ProfileData data;
String name;
public ProfileView(Context context, AttributeSet attrs, String name, final ProfileData profileData)
{
super(context, attrs);
......
......
}
public setCallBack( TaskCompleteListener<String> cb)
{
this.callback = cb;
}
//Heres where things get complicated
public void onClick(View v)
{
callback.onProfileClicked("Pass your result or any type");
}
}
And implement this to any Activity.
and call it like
ProfileView pv = new ProfileView(actvitiyContext, null, temp, tempPd);
pv.setCallBack(new TaskCompleteListener
{
public void onProfileClicked(String resultStringFromProfileView){}
});
Adding the keyword 'LOCAL' to my query worked for me:
LOAD DATA LOCAL INFILE 'file_name' INTO TABLE table_name
A detailed description of the keyword can be found here.
Either specify the type of T, or if you want to make it generic, you'll need to make the parent class generic.
public class MyClass<T>
{
etc
In swift 4.2 I used following code to show and hide code using NSNotification
@objc func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo? [UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
let keyboardheight = keyboardSize.height
print(keyboardheight)
}
}
To set the data in kotlin
val offerIds = ArrayList<Offer>()
offerIds.add(Offer(1))
retrunIntent.putExtra(C.OFFER_IDS, offerIds)
To get the data
val offerIds = data.getSerializableExtra(C.OFFER_IDS) as ArrayList<Offer>?
Now access the arraylist
I had the same issue with testing activity in my Android app. I used ActivityInstrumentationTestCase2
and MockitoAnnotations.initMocks(this);
didn't work.
I solved this issue with another class with respectively field. For example:
class CaptorHolder {
@Captor
ArgumentCaptor<Callback<AuthResponse>> captor;
public CaptorHolder() {
MockitoAnnotations.initMocks(this);
}
}
Then, in activity test method:
HubstaffService hubstaffService = mock(HubstaffService.class);
fragment.setHubstaffService(hubstaffService);
CaptorHolder captorHolder = new CaptorHolder();
ArgumentCaptor<Callback<AuthResponse>> captor = captorHolder.captor;
onView(withId(R.id.signInBtn))
.perform(click());
verify(hubstaffService).authorize(anyString(), anyString(), captor.capture());
Callback<AuthResponse> callback = captor.getValue();
If you have python various versions of python installed,you can launch any of them using pythonx.x.x
where x.x.x
represents your versions.
Try this simple in one line of code:-
$data= json_decode( json_encode($data), true);
Hope it helps :)
For those with Twitter Bootstrap and Rails 3
$('a').live('click', function (event) {
if(!($(this).attr('data-method')=='delete')){
var href = $(this).attr("href");
event.preventDefault();
window.location = href;
}
});
Delete links are still working this way.
See rawQuery(String, String[]) and the documentation for Cursor
Your DADABASE_COMPARE SQL statement is currently invalid, loginname
and loginpass
won't be escaped, there is no space between loginname
and the and
, and you end the statement with ); instead of ; -- If you were logging in as bob with the password of password, that statement would end up as
select count(*) from users where uname=boband pwd=password);
Also, you should probably use the selectionArgs feature, instead of concatenating loginname and loginpass.
To use selectionArgs you would do something like
final String SQL_STATEMENT = "SELECT COUNT(*) FROM users WHERE uname=? AND pwd=?";
private void someMethod() {
Cursor c = db.rawQuery(SQL_STATEMENT, new String[] { loginname, loginpass });
...
}
Try changing server name to "localhost"
pymssql.connect(server="localhost", user="myusername", password="mypwd", database="temp",port="1433")
Use FOR XML PATH('')
- which is converting the entries to a comma separated string and STUFF() -which is to trim the first comma- as follows Which gives you the same comma separated result
SELECT STUFF((SELECT ',' + INSTITUTIONNAME
FROM EDUCATION EE
WHERE EE.STUDENTNUMBER=E.STUDENTNUMBER
ORDER BY sortOrder
FOR XML PATH('')), 1, 1, '') AS listStr
FROM EDUCATION E
GROUP BY E.STUDENTNUMBER
Here is the FIDDLE
You can use a better approach for someone writing HTML for an already existing scss.
html
[attr.role]="<boolean>"
scss
[role = "true"] { ... }
That way you don't need to <boolean> ? true : null
every time.
FOR FADE add this first line with your animation's object.
.animate().alpha(1).setDuration(2000);
This will work
all = [a1, b1, b2, a2,.....]
map(lambda x: x.start(),all)
simple example
all = ["MILK","BREAD","EGGS"]
map(lambda x:x.lower(),all)
>>>['milk','bread','eggs']
and in python3
all = ["MILK","BREAD","EGGS"]
list(map(lambda x:x.lower(),all))
>>>['milk','bread','eggs']
Probably, the fastest, efficient and more generic way is this (you can merge any number of objects and even copy to the first one ->assign):
function object_merge(){
for (var i=1; i<arguments.length; i++)
for (var a in arguments[i])
arguments[0][a] = arguments[i][a];
return arguments[0];
}
It also allows you to modify the first object as it passed by reference. If you don't want this but want to have a completely new object containing all properties, then you can pass {} as the first argument.
var object1={a:1,b:2};
var object2={c:3,d:4};
var object3={d:5,e:6};
var combined_object=object_merge(object1,object2,object3);
combined_object and object1 both contain the properties of object1,object2,object3.
var object1={a:1,b:2};
var object2={c:3,d:4};
var object3={d:5,e:6};
var combined_object=object_merge({},object1,object2,object3);
In this case, the combined_object contains the properties of object1,object2,object3 but object1 is not modified.
Check here: https://jsfiddle.net/ppwovxey/1/
Note: JavaScript objects are passed by reference.
SIGABRT means in general that there is an uncaught exception. There should be more information on the console.
The Major Difference between a Service
and an IntentService
is described as follows:
Service :
1.A Service
by default, runs on the application's main thread.(here no default worker thread is available).So the user needs to create a separate thread and do the required work in that thread.
2.Allows Multiple requests at a time.(Multi Threading)
IntentService :
1.Now, coming to IntentService
, here a default worker thread is available to perform any operation. Note that - You need to implement onHandleIntent()
method ,which receives the intent for each start request, where you can do the background work.
2.But it allows only one request at a time.
You can show changes that have been staged with the --cached
flag:
$ git diff --cached
In more recent versions of git, you can also use the --staged
flag (--staged
is a synonym for --cached
):
$ git diff --staged
Loc2country is a Golang based tool that returns the ISO alpha-3 country code for given location coordinates (lat/lon). It responds in microseconds. It uses a geohash to country map.
The geohash data is generated using georaptor.
We use geohash at level 6 for this tool, i.e., boxes of size 1.2km x 600m.
I should be like this:
$.post(submitAddress, { 'yourArrayName' : javaScriptArrayToSubmitToServer },
function(response, status, xhr) {
alert("POST returned: \n" + response + "\n\n");
})
Python 3 renamed the unicode
type to str
, the old str
type has been replaced by bytes
.
if isinstance(unicode_or_str, str):
text = unicode_or_str
decoded = False
else:
text = unicode_or_str.decode(encoding)
decoded = True
You may want to read the Python 3 porting HOWTO for more such details. There is also Lennart Regebro's Porting to Python 3: An in-depth guide, free online.
Last but not least, you could just try to use the 2to3
tool to see how that translates the code for you.
Suppose your query is "select id,name from users where rollNo = 1001".
Here query will return a object with id and name column. Your Response class is like bellow:
public class UserObject{
int id;
String name;
String rollNo;
public UserObject(Object[] columns) {
this.id = (columns[0] != null)?((BigDecimal)columns[0]).intValue():0;
this.name = (String) columns[1];
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRollNo() {
return rollNo;
}
public void setRollNo(String rollNo) {
this.rollNo = rollNo;
}
}
here UserObject
constructor will get a Object Array and set data with object.
public UserObject(Object[] columns) {
this.id = (columns[0] != null)?((BigDecimal)columns[0]).intValue():0;
this.name = (String) columns[1];
}
Your query executing function is like bellow :
public UserObject getUserByRoll(EntityManager entityManager,String rollNo) {
String queryStr = "select id,name from users where rollNo = ?1";
try {
Query query = entityManager.createNativeQuery(queryStr);
query.setParameter(1, rollNo);
return new UserObject((Object[]) query.getSingleResult());
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
Here you have to import bellow packages:
import javax.persistence.Query;
import javax.persistence.EntityManager;
Now your main class, you have to call this function.
First you have to get EntityManager and call this getUserByRoll(EntityManager entityManager,String rollNo)
function. Calling procedure is given bellow:
@PersistenceContext
private EntityManager entityManager;
UserObject userObject = getUserByRoll(entityManager,"1001");
Now you have data in this userObject.
Here is Imports
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
Note:
query.getSingleResult() return a array. You have to maintain the column position and data type.
select id,name from users where rollNo = ?1
query return a array and it's [0] --> id and [1] -> name
.
For more info, visit this Answer
Thanks :)
You can do something like this:
public myform()
{
InitializeComponent(); // this will be called in ComboBox ComboBox = new System.Windows.Forms.ComboBox();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'myDataSet.someTable' table. You can move, or remove it, as needed.
this.myTableAdapter.Fill(this.myDataSet.someTable);
comboBox1.SelectedItem = null;
comboBox1.SelectedText = "--select--";
}
Without jquery or anything like that beacuse why not ?
var loaded=0;
var loaded1min=0;
document.addEventListener("DOMContentLoaded", function(event) {
loaded=1;
setTimeout(function () {
loaded1min=1;
}, 60000);
});
var floatValue = 10.23
var intValue = Int(floatValue)
This is enough to convert from float
to Int
Try using head or tail. If you want the 5 most-recently modified files:
ls -1t | head -5
The -1 (that's a one) says one file per line and the head says take the first 5 entries.
If you want the last 5 try
ls -1t | tail -5
To answer your question, yes you may pass JSON in the URI as part of a GET request (provided you URL-encode). However, considering your reason for doing this is due to the length of the URI, using JSON will be self-defeating (introducing more characters than required).
I suggest you send your parameters in body of a POST request, either in regular CGI style (param1=val1¶m2=val2
) or JSON (parsed by your API upon receipt)
Finally decided to downgrade the junit 5 to junit 4 and rebuild the testing environment.
It appears as if all the answers go around the bushes.
In your EditText
, use the property:
android:textCursorDrawable="@drawable/black_cursor"
and add the drawable black_cursor.xml
to your resources, as follows:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<size android:width="1dp" />
<solid android:color="#000000"/>
</shape>
This is also the way to create more diverse cursors, if you need.
Save this little extension:
extension Int {
var seconds: Int {
return self
}
var minutes: Int {
return self.seconds * 60
}
var hours: Int {
return self.minutes * 60
}
var days: Int {
return self.hours * 24
}
var weeks: Int {
return self.days * 7
}
var months: Int {
return self.weeks * 4
}
var years: Int {
return self.months * 12
}
}
Then use it intuitively like:
let threeDaysLater = TimeInterval(3.days)
date.addingTimeInterval(threeDaysLater)
The PGOPTIONS
environment variable may be used to achieve this in a flexible way.
In an Unix shell:
PGOPTIONS="--search_path=my_schema_01" psql -d myDataBase -a -f myInsertFile.sql
If there are several invocations in the script or sub-shells that need the same options, it's simpler to set PGOPTIONS
only once and export it.
PGOPTIONS="--search_path=my_schema_01"
export PGOPTIONS
psql -d somebase
psql -d someotherbase
...
or invoke the top-level shell script with PGOPTIONS
set from the outside
PGOPTIONS="--search_path=my_schema_01" ./my-upgrade-script.sh
In Windows CMD environment, set PGOPTIONS=value
should work the same.
move
and del
ARE certainly the equivalents, but from a functionality standpoint they are woefully NOT equivalent. For example, you can't move both files AND folders (in a wildcard scenario) with the move
command. And the same thing applies with del
.
The preferred solution in my view is to use Win32 ports of the Linux tools, the best collection of which I have found being here.
mv
and rm
are in the CoreUtils package and they work wonderfully!
maybe doesnt exists javaee-api-7.0.jar. download this jar and on your project right clik
Even better, try an OrderedDict (assuming you want something like a list). Closer to a list than a regular dict since the keys have an order just like list elements have an order. With a regular dict, the keys have an arbitrary order.
Note that this is available in Python 3 and 2.7. If you want to use with an earlier version of Python you can find installable modules to do that.
@Ahmed
Below is code that specifies fields from a named range for insertion into MS Access. The nice thing about this code is that you can name your fields in Excel whatever the hell you want (If you use * then the fields have to match exactly between Excel and Access) as you can see I have named an Excel column "Haha" even though the Access column is called "dte".
Sub test()
dbWb = Application.ActiveWorkbook.FullName
dsh = "[" & Application.ActiveSheet.Name & "$]" & "Data2" 'Data2 is a named range
sdbpath = "C:\Users\myname\Desktop\Database2.mdb"
sCommand = "INSERT INTO [main] ([dte], [test1], [values], [values2]) SELECT [haha],[test1],[values],[values2] FROM [Excel 8.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh
Dim dbCon As New ADODB.Connection
Dim dbCommand As New ADODB.Command
dbCon.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sdbpath & "; Jet OLEDB:Database Password=;"
dbCommand.ActiveConnection = dbCon
dbCommand.CommandText = sCommand
dbCommand.Execute
dbCon.Close
End Sub
in coffeescript:
b = (a.splice(0, len) while a.length)
demo
a = [1, 2, 3, 4, 5, 6, 7]
b = (a.splice(0, 2) while a.length)
[ [ 1, 2 ],
[ 3, 4 ],
[ 5, 6 ],
[ 7 ] ]
We use Liquid XML Studio, it provides a intuitive editable representation of an XSD schema. It also shows the annotations inline, which we find very useful and the split code/gfx view is invaluable when writting or editing an XSD.
The for-in statement is really there to enumerate over object properties, which is how it is implemented in TypeScript. There are some issues with using it on arrays.
I can't speak on behalf of the TypeScript team, but I believe this is the reason for the implementation in the language.
Just use CR to go to beginning of the line.
import time
for x in range (0,5):
b = "Loading" + "." * x
print (b, end="\r")
time.sleep(1)
In Python 3.7 a new keyword argument capture_output
was introduced for subprocess.run
. Enabling the short and simple:
import subprocess
p = subprocess.run("echo 'hello world!'", capture_output=True, shell=True, encoding="utf8")
assert p.stdout == 'hello world!\n'
If your integer is timestamp in milliseconds use:
SELECT strftime("%Y-%d-%m", col_name, 'unixepoch') AS col_name
It will format milliseconds to yyyy-mm-dd string.
@uvsmtid Your post finally lead me into the right direction
:
simply deleting (actually renaming) the public key file id_rsa.pub
solved the problem for me, that git was working though nagging about invalid format.
Not quite sure, yet the file is not actually needed, since the pub key can be extracted from private key file id_rsa
anyway.
for anyone coming here as of post-May 2015: there's a new "-proxy" option that will be included in the next release of openssl: https://rt.openssl.org/Ticket/Display.html?id=2651&user=guest&pass=guest
surprised no one mentioned this
without finding out the revision number you could write this, if you just committed something that you want to revert, this wont work if you changed some other file and the target file is not the last changed file
svn merge -r HEAD:PREV file
best way is
button.setBackgroundResource(android.R.drawable.ic_delete);
OR this for Drawable left and something like that for right etc.
int imgResource = R.drawable.left_img;
button.setCompoundDrawablesWithIntrinsicBounds(imgResource, 0, 0, 0);
and
getResources().getDrawable()
is now deprecated
I use an alpha-transparent PNG for that:
div.semi-transparent {
background: url('semi-transparent.png');
}
for Windows:
del D:\ProgramData\docker\containers\{CONTAINER ID}
del D:\ProgramData\docker\windowsfilter\{CONTAINER ID}
Then restart the Docker Desktop
It may be late but I came across something which explains your concern related to proxy (only 'external' method calls coming in through the proxy will be intercepted) nicely.
For example, you have a class that looks like this
@Component("mySubordinate")
public class CoreBusinessSubordinate {
public void doSomethingBig() {
System.out.println("I did something small");
}
public void doSomethingSmall(int x){
System.out.println("I also do something small but with an int");
}
}
and you have an aspect, that looks like this:
@Component
@Aspect
public class CrossCuttingConcern {
@Before("execution(* com.intertech.CoreBusinessSubordinate.*(..))")
public void doCrossCutStuff(){
System.out.println("Doing the cross cutting concern now");
}
}
When you execute it like this:
@Service
public class CoreBusinessKickOff {
@Autowired
CoreBusinessSubordinate subordinate;
// getter/setters
public void kickOff() {
System.out.println("I do something big");
subordinate.doSomethingBig();
subordinate.doSomethingSmall(4);
}
}
Results of calling kickOff above given code above.
I do something big
Doing the cross cutting concern now
I did something small
Doing the cross cutting concern now
I also do something small but with an int
but when you change your code to
@Component("mySubordinate")
public class CoreBusinessSubordinate {
public void doSomethingBig() {
System.out.println("I did something small");
doSomethingSmall(4);
}
public void doSomethingSmall(int x){
System.out.println("I also do something small but with an int");
}
}
public void kickOff() {
System.out.println("I do something big");
subordinate.doSomethingBig();
//subordinate.doSomethingSmall(4);
}
You see, the method internally calls another method so it won't be intercepted and the output would look like this:
I do something big
Doing the cross cutting concern now
I did something small
I also do something small but with an int
You can by-pass this by doing that
public void doSomethingBig() {
System.out.println("I did something small");
//doSomethingSmall(4);
((CoreBusinessSubordinate) AopContext.currentProxy()).doSomethingSmall(4);
}
Code snippets taken from: https://www.intertech.com/Blog/secrets-of-the-spring-aop-proxy/
I had the same problem as yours. I found that when i use the BoundField
tag in GridView to show my data. The row.Cells[1].Text
is working in:
GridViewRow row = dgCustomer.SelectedRow;
TextBox1.Text = "Cell Value" + row.Cells[1].Text + "";
But when i use TemplateField
tag to show data like this:
<asp:TemplateField HeaderText="??">
<ItemTemplate>
<asp:Label ID="Part_No" runat="server" Text='<%# Eval("Part_No")%>' ></asp:Label>
</ItemTemplate>
<HeaderStyle CssClass="bhead" />
<ItemStyle CssClass="bbody" />
</asp:TemplateField>
The row.Cells[1].Text
just return null. I got stuck in this problem for a long time. I figur out recently and i want to share with someone who have the same problem my solution. Please feel free to edit this post and/or correct me.
My Solution:
Label lbCod = GridView1.Rows["AnyValidIndex"].Cells["AnyValidIndex"].Controls["AnyValidIndex"] as Label;
I use Controls
attribute to find the Label
control which i use to show data, and you can find yours. When you find it and convert to the correct type object than you can extract text and so on. Ex:
string showText = lbCod.Text;
Reference: reference
Yes, you're right. With the css()
method you can retrieve the desired css value stored in the DOM. You can read more about this at: http://api.jquery.com/css/
But if you want to get its position you can check offset() and position() methods to get it's position.
Additional to nanselm2's answer, you can use 0
instead of False
:
df["col"].str.contains(word)==0
I found this thread on that there Interweb thing. Boils down to:
@echo off
setlocal enableextensions
for /f "tokens=*" %%a in (
'VER'
) do (
set myvar=%%a
)
echo/%%myvar%%=%myvar%
pause
endlocal
You can also redirect the output of a command to a temporary file, and then put the contents of that temporary file into your variable, likesuchashereby. It doesn't work with multiline input though.
cmd > tmpFile
set /p myvar= < tmpFile
del tmpFile
Credit to the thread on Tom's Hardware.
One of the reasons that C++ was designed was to make it easy to reuse code. In general, C++ should be written so that it works whether the class is instantiated on the heap, in an array, or on the stack. "Delete this" is a very bad coding practice because it will only work if a single instance is defined on the heap; and there had better not be another delete statement, which is typically used by most developers to clean up the heap. Doing this also assumes that no maintenance programmer in the future will cure a falsely perceived memory leak by adding a delete statement.
Even if you know in advance that your current plan is to only allocate a single instance on the heap, what if some happy-go-lucky developer comes along in the future and decides to create an instance on the stack? Or, what if he cuts and pastes certain portions of the class to a new class that he intends to use on the stack? When the code reaches "delete this" it will go off and delete it, but then when the object goes out of scope, it will call the destructor. The destructor will then try to delete it again and then you are hosed. In the past, doing something like this would screw up not only the program but the operating system and the computer would need to be rebooted. In any case, this is highly NOT recommended and should almost always be avoided. I would have to be desperate, seriously plastered, or really hate the company I worked for to write code that did this.
My comment might not be relevant to the tags given. However, I was lead to this page from my search. I was looking for similar check in R and I came up the following with the help of @hugovdbeg post. I hope it would be helpful for someone who is looking for similar solution in R
'USERNAME' %in% names(Sys.getenv())
In addition from the command prompt run SET.
This displayed the "LOGONSERVER" value which indicates the specific domain controller you are using (there can be more than one).
Then you got to that server's NetBios Share \Servername\SYSVOL\domain.local\scripts.
You should not ever want to do this. Select * should not be used as the basis for an insert as the columns may get moved around and break your insert (or worse not break your insert but mess up your data. Suppose someone adds a column to the table in the select but not the other table, you code will break. Or suppose someone, for reasons that surpass understanding but frequently happen, decides to do a drop and recreate on a table and move the columns around to a different order. Now your last_name is is the place first_name was in originally and select * will put it in the wrong column in the other table. It is an extremely poor practice to fail to specify columns and the specific mapping of one column to the column you want in the table you are interested in.
Right now you may have several problems, first the two structures don't match directly or second the table being inserted to has an identity column and so even though the insertable columns are a direct match, the table being inserted to has one more column than the other and by not specifying the database assumes you are going to try to insert to that column. Or you might have the same number of columns but one is an identity and thus can't be inserted into (although I think that would be a different error message).
ctypes can be used to access dlls, here's a tutorial:
I tried for a very long time to duplicate tabs in Chrome running using action_keys and send_keys on body. The only thing that worked for me was an answer here. This is what my duplicate tabs def ended up looking like, probably not the best but it works fine for me.
def duplicate_tabs(number, chromewebdriver):
#Once on the page we want to open a bunch of tabs
url = chromewebdriver.current_url
for i in range(number):
print('opened tab: '+str(i))
chromewebdriver.execute_script("window.open('"+url+"', 'new_window"+str(i)+"')")
It basically runs some java from inside of python, it's incredibly useful. Hope this helps somebody.
Note: I am using Ubuntu, it shouldn't make a difference but if it doesn't work for you this could be the reason.
Look at the r.status_code
attribute:
if r.status_code == 404:
# A 404 was issued.
Demo:
>>> import requests
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.status_code
404
If you want requests
to raise an exception for error codes (4xx or 5xx), call r.raise_for_status()
:
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.raise_for_status()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "requests/models.py", line 664, in raise_for_status
raise http_error
requests.exceptions.HTTPError: 404 Client Error: NOT FOUND
>>> r = requests.get('http://httpbin.org/status/200')
>>> r.raise_for_status()
>>> # no exception raised.
You can also test the response object in a boolean context; if the status code is not an error code (4xx or 5xx), it is considered ‘true’:
if r:
# successful response
If you want to be more explicit, use if r.ok:
.
if u want to have multiple selection on select row..
import React from 'react';
import ReactTable from 'react-table';
import 'react-table/react-table.css';
import { ReactTableDefaults } from 'react-table';
import matchSorter from 'match-sorter';
class ThreatReportTable extends React.Component{
constructor(props){
super(props);
this.state = {
selected: [],
row: []
}
}
render(){
const columns = this.props.label;
const data = this.props.data;
Object.assign(ReactTableDefaults, {
defaultPageSize: 10,
pageText: false,
previousText: '<',
nextText: '>',
showPageJump: false,
showPagination: true,
defaultSortMethod: (a, b, desc) => {
return b - a;
},
})
return(
<ReactTable className='threatReportTable'
data= {data}
columns={columns}
getTrProps={(state, rowInfo, column) => {
return {
onClick: (e) => {
var a = this.state.selected.indexOf(rowInfo.index);
if (a == -1) {
// this.setState({selected: array.concat(this.state.selected, [rowInfo.index])});
this.setState({selected: [...this.state.selected, rowInfo.index]});
// Pass props to the React component
}
var array = this.state.selected;
if(a != -1){
array.splice(a, 1);
this.setState({selected: array});
}
},
// #393740 - Lighter, selected row
// #302f36 - Darker, not selected row
style: {background: this.state.selected.indexOf(rowInfo.index) != -1 ? '#393740': '#302f36'},
}
}}
noDataText = "No available threats"
/>
)
}
}
export default ThreatReportTable;
<input id='r1' type='radio' class='rg' name="asdf"/>
<input id='r2' type='radio' class='rg' name="asdf"/>
<input id='r3' type='radio' class='rg' name="asdf"/>
<input id='r4' type='radio' class='rg' name="asdf"/><br/>
<input type='text' id='r1edit'/>
jquery part
$(".rg").change(function () {
if ($("#r1").attr("checked")) {
$('#r1edit:input').removeAttr('disabled');
}
else {
$('#r1edit:input').attr('disabled', 'disabled');
}
});
here is the DEMO
Here is a solution on pure js. You can do it with html5 saveAs. For example this lib could be helpful: https://github.com/eligrey/FileSaver.js
Look at the demo: http://eligrey.com/demos/FileSaver.js/
P.S. There is no information about json save, but you can do it changing file type to "application/json"
and format to .json
I would like to return two values from a function in two separate variables.
What would you expect it to look like on the calling end? You can't write a = select_choice(); b = select_choice()
because that would call the function twice.
Values aren't returned "in variables"; that's not how Python works. A function returns values (objects). A variable is just a name for a value in a given context. When you call a function and assign the return value somewhere, what you're doing is giving the received value a name in the calling context. The function doesn't put the value "into a variable" for you, the assignment does (never mind that the variable isn't "storage" for the value, but again, just a name).
When i tried to to use
return i, card
, it returns atuple
and this is not what i want.
Actually, it's exactly what you want. All you have to do is take the tuple
apart again.
And i want to be able to use these values separately.
So just grab the values out of the tuple
.
The easiest way to do this is by unpacking:
a, b = select_choice()
Just delete the table and create a new table with a different name. Also Don't delete entire row for that table. It seems when entire row containing table row is delete it damages the DataBodyRange is damaged
You cannot return value after resolving promise. Instead call another function when promise is resolved:
function justTesting() {
promise.then(function(output) {
// instead of return call another function
afterResolve(output + 1);
});
}
function afterResolve(result) {
// do something with result
}
var test = justTesting();
I was able to use this site to easily download and install curl on my Windows machine. It took all of 30 seconds. I'm using Windows 7 (w/ Admin privelages), so I downloaded curl-7.37.0-win64.msi from http://curl.haxx.se/download.html.
Also, don't forget to restart your console/terminal after you install curl, otherwise you will get the same error messages.
I did receive also the same error:
Error:Execution failed for task ':app:transformClassesWithDexForDebug'. com.android.build.api.transform.TransformException: java.lang.RuntimeException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.8.0_60\bin\java.exe'' finished with non-zero exit value 1
well I fixed this with help of following steps:
Open your app's build.gradle (not the one in the project root) and add:
android {
//snippet
//add this into your existing 'android' block
dexOptions {
javaMaxHeapSize "4g"
}
//snip
}
Try your build again.
Note: 4g is 4 Gigabytes and this is a maximum heap size for dex operation.
In Windows -> use Command Promt:
tnsping localhost
It show the version and if is installed 32 o 64 bit client, for example:
TNS Ping Utility for 64-bit Windows: Version 10.2.0.4.0 - Production on 03-MAR-2015 16:47:26
Source: https://decipherinfosys.wordpress.com/2007/02/10/checking-for-oracle-client-version-on-windows/
Compile constants can only be primitives and Strings:
15.28. Constant Expressions
A compile-time constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following:
- Literals of primitive type and literals of type
String
- Casts to primitive types and casts to type
String
- [...] operators [...]
- Parenthesized expressions whose contained expression is a constant expression.
- Simple names that refer to constant variables.
- Qualified names of the form TypeName . Identifier that refer to constant variables.
Actually in java there is no way to protect items in an array. At runtime someone can always do FieldValues.FIELD1[0]="value3"
, therefore the array cannot be really constant if we look deeper.
Here's the result of running your code in Ipython. Note that result
is a (2,0)
array, 2 rows, 0 columns, 0 elements. The append
produces a (2,)
array. result[0]
is (0,)
array. Your error message has to do with trying to assign that 2 item array into a size 0 slot. Since result
is dtype=float64
, only scalars can be assigned to its elements.
In [65]: result=np.asarray([np.asarray([]),np.asarray([])])
In [66]: result
Out[66]: array([], shape=(2, 0), dtype=float64)
In [67]: result[0]
Out[67]: array([], dtype=float64)
In [68]: np.append(result[0],[1,2])
Out[68]: array([ 1., 2.])
np.array
is not a Python list. All elements of an array are the same type (as specified by the dtype
). Notice also that result
is not an array of arrays.
Result could also have been built as
ll = [[],[]]
result = np.array(ll)
while
ll[0] = [1,2]
# ll = [[1,2],[]]
the same is not true for result.
np.zeros((2,0))
also produces your result
.
Actually there's another quirk to result
.
result[0] = 1
does not change the values of result
. It accepts the assignment, but since it has 0 columns, there is no place to put the 1
. This assignment would work in result was created as np.zeros((2,1))
. But that still can't accept a list.
But if result
has 2 columns, then you can assign a 2 element list to one of its rows.
result = np.zeros((2,2))
result[0] # == [0,0]
result[0] = [1,2]
What exactly do you want result
to look like after the append
operation?
keep the delimiter in single quotes it will work.
ROW FORMAT DELIMITED
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n';
This will work
If you really want to use Deleted, you'd have to make your foreign keys nullable, but then you'd end up with orphaned records (which is one of the main reasons you shouldn't be doing that in the first place). So just use Remove()
ObjectContext.DeleteObject(entity) marks the entity as Deleted in the context. (It's EntityState is Deleted after that.) If you call SaveChanges afterwards EF sends a SQL DELETE statement to the database. If no referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.
EntityCollection.Remove(childEntity) marks the relationship between parent and childEntity as Deleted. If the childEntity itself is deleted from the database and what exactly happens when you call SaveChanges depends on the kind of relationship between the two:
A thing worth noting is that setting .State = EntityState.Deleted
does not trigger automatically detected change. (archive)
Just in case someone is still getting the same error, even with all the help above: I had this problem, I tried all the solutions given here, and I just found out that my problem was actually another error from my error list (which was about a missing image set to be my splash screen. i just changed its path to the right one and then all started to work)
In case the extension is not known (it needs the / separator):
irb(main):024:0> f = 'C:\foobar\blah.txt'.gsub("\\","/")
=> "C:/foobar/blah.txt"
irb(main):027:0> File.basename(f,File.extname(f))
=> "blah"
Update to Justin answer above. if you want to use it using Data Annotation in MVC you can do as follow
[RegularExpression(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\da-zA-Z]).{8,15}$", ErrorMessage = "Password must be between 6 and 20 characters and contain one uppercase letter, one lowercase letter, one digit and one special character.")]
Before we write any code, let's discuss the difference between attributes and properties. Attributes are the settings you apply to elements in your HTML markup; the browser then parses the markup and creates DOM objects of various types that contain properties initialized with the values of the attributes. On DOM objects, such as a simple HTMLElement
, you almost always want to be working with its properties, not its attributes collection.
The current best practice is to avoid working with attributes unless they are custom or there is no equivalent property to supplement it. Since title
does indeed exist as a read/write property on many HTMLElement
s, we should take advantage of it.
You can read more about the difference between attributes and properties here or here.
With this in mind, let's manipulate that title
...
title
property without jQuerySince title
is a public property, you can set it on any DOM element that supports it with plain JavaScript:
document.getElementById('yourElementId').title = 'your new title';
Retrieval is almost identical; nothing special here:
var elementTitle = document.getElementById('yourElementId').title;
This will be the fastest way of changing the title if you're an optimization nut, but since you wanted jQuery involved:
title
property with jQuery (v1.6+)jQuery introduced a new method in v1.6 to get and set properties. To set the title
property on an element, use:
$('#yourElementId').prop('title', 'your new title');
If you'd like to retrieve the title, omit the second parameter and capture the return value:
var elementTitle = $('#yourElementId').prop('title');
Check out the prop()
API documentation for jQuery.
If you really don't want to use properties, or you're using a version of jQuery prior to v1.6, then you should read on:
title
attribute with jQuery (versions <1.6)You can change the title
attribute with the following code:
$('#yourElementId').attr('title', 'your new title');
Or retrieve it with:
var elementTitle = $('#yourElementId').attr('title');
Check out the attr()
API documentation for jQuery.
I faced same error but in a different way.
When you curl a page with a specific SSL protocol.
curl --sslv3 https://example.com
If --sslv3 is not supported by the target server then the error will be
curl: (35) TCP connection reset by peer
With the supported protocol, error will be gone.
curl --tlsv1.2 https://example.com
Call MimeMessage.saveChanges()
on the enclosing message, which will update the headers by cascading down the MIME structure into a call to MimeBodyPart.updateHeaders()
on your body part. It's this updateHeaders
call that transfers the content type from the DataHandler
to the part's MIME Content-Type
header.
When you set the content of a MimeBodyPart
, JavaMail internally (and not obviously) creates a DataHandler
object wrapping the object you passed in. The part's Content-Type
header is not updated immediately.
There's no straightforward way to do it in your test program, since you don't have a containing MimeMessage
and MimeBodyPart.updateHeaders()
isn't public
.
Here's a working example that illuminates expected and unexpected outputs:
public class MailTest {
public static void main( String[] args ) throws Exception {
Session mailSession = Session.getInstance( new Properties() );
Transport transport = mailSession.getTransport();
String text = "Hello, World";
String html = "<h1>" + text + "</h1>";
MimeMessage message = new MimeMessage( mailSession );
Multipart multipart = new MimeMultipart( "alternative" );
MimeBodyPart textPart = new MimeBodyPart();
textPart.setText( text, "utf-8" );
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent( html, "text/html; charset=utf-8" );
multipart.addBodyPart( textPart );
multipart.addBodyPart( htmlPart );
message.setContent( multipart );
// Unexpected output.
System.out.println( "HTML = text/html : " + htmlPart.isMimeType( "text/html" ) );
System.out.println( "HTML Content Type: " + htmlPart.getContentType() );
// Required magic (violates principle of least astonishment).
message.saveChanges();
// Output now correct.
System.out.println( "TEXT = text/plain: " + textPart.isMimeType( "text/plain" ) );
System.out.println( "HTML = text/html : " + htmlPart.isMimeType( "text/html" ) );
System.out.println( "HTML Content Type: " + htmlPart.getContentType() );
System.out.println( "HTML Data Handler: " + htmlPart.getDataHandler().getContentType() );
}
}
Dumping a database with a specific encoding and try to restore it on another database with a different encoding could result in data corruption. Data encoding must be set BEFORE any data is inserted into the database.
Check this : When copying any other database, the encoding and locale settings cannot be changed from those of the source database, because that might result in corrupt data.
And this : Some locale categories must have their values fixed when the database is created. You can use different settings for different databases, but once a database is created, you cannot change them for that database anymore. LC_COLLATE and LC_CTYPE are these categories. They affect the sort order of indexes, so they must be kept fixed, or indexes on text columns would become corrupt. (But you can alleviate this restriction using collations, as discussed in Section 22.2.) The default values for these categories are determined when initdb is run, and those values are used when new databases are created, unless specified otherwise in the CREATE DATABASE command.
I would rather rebuild everything from the begining properly with a correct local encoding on your debian OS as explained here :
su root
Reconfigure your local settings :
dpkg-reconfigure locales
Choose your locale (like for instance for french in Switzerland : fr_CH.UTF8)
Uninstall and clean properly postgresql :
apt-get --purge remove postgresql\*
rm -r /etc/postgresql/
rm -r /etc/postgresql-common/
rm -r /var/lib/postgresql/
userdel -r postgres
groupdel postgres
Re-install postgresql :
aptitude install postgresql-9.1 postgresql-contrib-9.1 postgresql-doc-9.1
Now any new database will be automatically be created with correct encoding, LC_TYPE (character classification), and LC_COLLATE (string sort order).
The way I resolved this was setup error logs correctly, first
<VirtualHost *:80>
DocumentRoot "D:/websites/test/"
ServerName test.dev
ErrorLog "D:/websites/test/logs/error.log"
CustomLog "D:/websites/test/logs/access.log" common
<Directory D:/websites/test/>
AllowOverride none
Require all granted
</Directory>
</VirtualHost>
After this error are being logged into "D:/websites/test/logs/" make sure to create logs folder yourself. The exact error that was recorded in error log was
AH01630: client denied by server configuration:
Which pointed me to correct solution using this link which said for the above error
Require all granted
is required. My sample sample code above fixes the problem by the way.
The question in the link you gave talks about naming of JavaScript variables, not about file naming, so forget about that for the context in which you ask your question.
As to file naming, it is purely a matter of preference and taste. I prefer naming files with hyphens because then I don't have to reach for the shift key, as I do when dealing with camelCase file names; and because I don't have to worry about differences between Windows and Linux file names (Windows file names are case-insensitive, at least through XP).
So the answer, like so many, is "it depends" or "it's up to you."
The one rule you should follow is to be consistent in the convention you choose.
Here is code not using the percentage in the keyframes. Because you used percentages the animation does nothing a long time.
How does this example work:
animation
. This is a short hand for animation properties.from
and to
in the keyframes. from is = 0% and to is = 100%animation: bounce 1s infinite alternate;
the 1s is how long the animation will last..ball {_x000D_
margin-top: 50px;_x000D_
border-radius: 50%;_x000D_
width: 50px;_x000D_
height: 50px;_x000D_
background-color: cornflowerblue;_x000D_
border: 2px solid #999;_x000D_
animation: bounce 1s infinite alternate;_x000D_
-webkit-animation: bounce 1s infinite alternate;_x000D_
}_x000D_
@keyframes bounce {_x000D_
from {_x000D_
transform: translateY(0px);_x000D_
}_x000D_
to {_x000D_
transform: translateY(-15px);_x000D_
}_x000D_
}_x000D_
@-webkit-keyframes bounce {_x000D_
from {_x000D_
transform: translateY(0px);_x000D_
}_x000D_
to {_x000D_
transform: translateY(-15px);_x000D_
}_x000D_
}
_x000D_
<div class="ball"></div>
_x000D_
In a previous version of the aws-php-sdk, prior to the deprecation of the S3Client::factory()
method, you were allowed to place part of the file path, or Key
as it is called in the S3Client->putObject()
parameters, on the bucket parameter. I had a file manager in production use, using the v2 SDK. Since the factory method still worked, I did not revisit this module after updating to ~3.70.0
. Today I spent the better part of two hours debugging why I had started receiving this error, and it ended up being due to the parameters I was passing (which used to work):
$s3Client = new S3Client([
'profile' => 'default',
'region' => 'us-east-1',
'version' => '2006-03-01'
]);
$result = $s3Client->putObject([
'Bucket' => 'awesomecatpictures/catsinhats',
'Key' => 'whitecats/white_cat_in_hat1.png',
'SourceFile' => '/tmp/asdf1234'
]);
I had to move the catsinhats
portion of my bucket/key path to the Key
parameter, like so:
$s3Client = new S3Client([
'profile' => 'default',
'region' => 'us-east-1',
'version' => '2006-03-01'
]);
$result = $s3Client->putObject([
'Bucket' => 'awesomecatpictures',
'Key' => 'catsinhats/whitecats/white_cat_in_hat1.png',
'SourceFile' => '/tmp/asdf1234'
]);
What I believe is happening is that the Bucket
name is now being URL Encoded. After further inspection of the exact message I was receiving from the SDK, I found this:
Error executing PutObject
on https://s3.amazonaws.com/awesomecatpictures%2Fcatsinhats/whitecats/white_cat_in_hat1.png
AWS HTTP error: Client error:
PUT https://s3.amazonaws.com/awesomecatpictures%2Fcatsinhats/whitecats/white_cat_in_hat1.png
resulted in a 403 Forbidden
This shows that the /
I provided to my Bucket
parameter has been through urlencode()
and is now %2F
.
The way the Signature works is fairly complicated, but the issue boils down to the bucket and key are used to generate the encrypted signature. If they do not match exactly on both the calling client, and within AWS, then the request will be denied with a 403. The error message does actually point out the issue:
The request signature we calculated does not match the signature you provided. Check your key and signing method.
So, my Key
was wrong because my Bucket
was wrong.
Anaconda3 version 4.4.0check image Go to Anaconda -> Environments -> from the dropdown select not installed -> If you can see xgboost pr Py-xgboost select and click apply.
Sometimes when the dev process has both WIN work stations and LINUX systems (hosting) and in the code you do not see any output before the related line, it could be the formatting of the file and the lack of Unix LF (linefeed) line ending.
What we usually do in order to quickly fix this, is rename the file and on the LINUX system create a new file instead of the renamed one, and then copy the content into that. Many times this solve the issue as some of the files that were created in WIN once moved to the hosting cause this issue.
This fix is an easy fix for sites we manage by FTP and sometimes can save our new team members some time.
To revert a merge commit, you need to use: git revert -m <parent number>
. So for example, to revert the recent most merge commit using the parent with number 1 you would use:
git revert -m 1 HEAD
To revert a merge commit before the last commit, you would do:
git revert -m 1 HEAD^
Use git show <merge commit SHA1>
to see the parents, the numbering is the order they appear e.g. Merge: e4c54b3 4725ad2
git merge documentation: http://schacon.github.com/git/git-merge.html
git merge discussion (confusing but very detailed): http://schacon.github.com/git/howto/revert-a-faulty-merge.txt
I would also recommend to think to ignore files like:
.*.swp
.*.swo
as you may have files that end with .swp
It seems that it doesn't turn it into a string. Try
row.HeaderCell.Value = String.Format("{0}", row.Index + 1);
If you are looking for a way to it without SQL you should be able to use delete_all.
Post.delete_all
or with a criteria
Post.delete_all "person_id = 5 AND (category = 'Something' OR category = 'Else')"
See here for more information.
The records are deleted without loading them first which makes it very fast but will break functionality like counter cache that depends on rails code to be executed upon deletion.
I have tried to make note about these and have collected and written examples from a java perspective.
Putting it here for any java developer who is looking into the same subject.
Detach
is unnecessary.
The answer (as of 2013) is simple:
$('#parentNode').append($('#childNode'));
According to http://api.jquery.com/append/
You can also select an element on the page and insert it into another:
$('.container').append($('h2'));
If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved into the target (not cloned).
Right click can be achieved using Java script executor as well(in cases where action class is not supported):
JavascriptExecutor js = (JavascriptExecutor) driver;
String javaScript = "var evt = document.createEvent('MouseEvents');"
+ "var RIGHT_CLICK_BUTTON_CODE = 2;"
+ "evt.initMouseEvent('contextmenu', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, RIGHT_CLICK_BUTTON_CODE, null);"
+ "arguments[0].dispatchEvent(evt)";
js.executeScript(javaScript, element);
For a long value you need to add the length info 'l' and 'u' for unsigned decimal integer,
as a reference of available options see sprintf
#include <stdio.h>
int main ()
{
unsigned long lval = 123;
char buffer [50];
sprintf (buffer, "%lu" , lval );
}
Default Colors:
android:textColorHint="@android:color/holo_blue_dark"
For Color code:
android:textColorHint="#33b5e5"
You should use Adaptive hashing like http://en.wikipedia.org/wiki/Bcrypt for securing passwords
Use it in App Delegate: I am using storyboard
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
CGSize iOSDeviceScreenSize = [[UIScreen mainScreen] bounds].size;
//----------------HERE WE SETUP FOR IPHONE 4/4s/iPod----------------------
if(iOSDeviceScreenSize.height == 480){
UIStoryboard *iPhone35Storyboard = [UIStoryboard storyboardWithName:@"iPhone" bundle:nil];
// Instantiate the initial view controller object from the storyboard
UIViewController *initialViewController = [iPhone35Storyboard instantiateInitialViewController];
// Instantiate a UIWindow object and initialize it with the screen size of the iOS device
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Set the initial view controller to be the root view controller of the window object
self.window.rootViewController = initialViewController;
// Set the window object to be the key window and show it
[self.window makeKeyAndVisible];
iphone=@"4";
NSLog(@"iPhone 4: %f", iOSDeviceScreenSize.height);
}
//----------------HERE WE SETUP FOR IPHONE 5----------------------
if(iOSDeviceScreenSize.height == 568){
// Instantiate a new storyboard object using the storyboard file named Storyboard_iPhone4
UIStoryboard *iPhone4Storyboard = [UIStoryboard storyboardWithName:@"iPhone5" bundle:nil];
// Instantiate the initial view controller object from the storyboard
UIViewController *initialViewController = [iPhone4Storyboard instantiateInitialViewController];
// Instantiate a UIWindow object and initialize it with the screen size of the iOS device
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Set the initial view controller to be the root view controller of the window object
self.window.rootViewController = initialViewController;
// Set the window object to be the key window and show it
[self.window makeKeyAndVisible];
NSLog(@"iPhone 5: %f", iOSDeviceScreenSize.height);
iphone=@"5";
}
} else if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
// NSLog(@"wqweqe");
storyboard = [UIStoryboard storyboardWithName:@"iPad" bundle:nil];
}
return YES;
}
You are having a controlled component where input
value is determined by this.state.city
. So once you submit you have to clear your state which will clear your input automatically.
onHandleSubmit(e) {
e.preventDefault();
const city = this.state.city;
this.props.onSearchTermChange(city);
this.setState({
city: ''
});
}
If you're having this problem in a Build Pipeline on Azure DevOps, try putting the Build Action as "Content" and Copy to Output Directory equal to "Copy if newer" in the AssembyInfo.cs file properties.
You can get the path via fp.name
. Example:
>>> f = open('foo/bar.txt')
>>> f.name
'foo/bar.txt'
You might need os.path.basename
if you want only the file name:
>>> import os
>>> f = open('foo/bar.txt')
>>> os.path.basename(f.name)
'bar.txt'
File object docs (for Python 2) here.
When a variable is declared static inside a class then it becomes a shared variable for all objects of that class which means that the variable is longer specific to any object. For example: -
#include<iostream.h>
#include<conio.h>
class test
{
void fun()
{
static int a=0;
a++;
cout<<"Value of a = "<<a<<"\n";
}
};
void main()
{
clrscr();
test obj1;
test obj2;
test obj3;
obj1.fun();
obj2.fun();
obj3.fun();
getch();
}
This program will generate the following output: -
Value of a = 1
Value of a = 2
Value of a = 3
The same goes for globally declared static variable. The above code will generate the same output if we declare the variable a outside function void fun()
Whereas if u remove the keyword static and declare a as a non-static local/global variable then the output will be as follows: -
Value of a = 1
Value of a = 1
Value of a = 1
The documentation has been updated. My answer has substantial changes vs the accepted answer: I wanted to reflect documentation is up-to-date, and accepted answer has a few broken links.
Also, I didn't understand when the accepted answer said "it defaults to node server.js
". I think the documentation clarifies the default behavior:
npm-start
Start a package
Synopsis
npm start [-- <args>]
Description
This runs an arbitrary command specified in the package's "
start
" property of its "scripts
" object. If no "start
" property is specified on the "scripts
" object, it will runnode server.js
.
In summary, running npm start
could do one of two things:
npm start {command_name}
: Run an arbitrary command (i.e. if such command is specified in the start
property of package.json's scripts
object)npm start
: Else if no start
property exists (or no command_name
is passed): Run node server.js
, (which may not be appropriate, for example the OP doesn't have server.js
; the OP runs node
app.js
)package.json
in the directory where you run npm start
, you may see an error: npm ERR! enoent ENOENT: no such file or directory, open '.\package.json'
Option(getObject) foreach (QueueManager add)
I had the same issue, there was no issue in my syntax, but when I moved the M2
, M2_HOME
, JAVA_HOME
environment variables from user to system it started working. Path variables stayed the same.
You need to convert the date field to varchar to strip out the time, then convert it back to datetime, this will reset the time to '00:00:00.000'.
SELECT *
FROM [TableName]
WHERE
(
convert(datetime,convert(varchar,GETDATE(),1))
between
convert(datetime,convert(varchar,[StartDate],1))
and
convert(datetime,convert(varchar,[EndDate],1))
)
I realize my opinion is probably not the popular one, but I guess I have a hard time jumping on the Linq-y band wagon. It's nifty. It's condensed. I get that and I'm not opposed to using it where it's appropriate. Maybe it's just me, but I feel like people have stopped thinking about creating utility functions to accomplish what they want and instead prefer to litter their code with (sometimes) excessively long lines of Linq code for the sake of creating a dense 1-liner.
I'm not saying that any of the Linq answers that people have provided here are bad, but I guess I feel like there is the potential that these single lines of code can start to grow longer and more obscure as you need to handle various situations. What if your array is null? What if you want a delimited string instead of just purely concatenated? What if some of the integers in your array are double-digit and you want to pad each value with leading zeros so that the string for each element is the same length as the rest?
Taking one of the provided answers as an example:
result = arr.Aggregate(string.Empty, (s, i) => s + i.ToString());
If I need to worry about the array being null, now it becomes this:
result = (arr == null) ? null : arr.Aggregate(string.Empty, (s, i) => s + i.ToString());
If I want a comma-delimited string, now it becomes this:
result = (arr == null) ? null : arr.Skip(1).Aggregate(arr[0].ToString(), (s, i) => s + "," + i.ToString());
This is still not too bad, but I think it's not obvious at a glance what this line of code is doing.
Of course, there's nothing stopping you from throwing this line of code into your own utility function so that you don't have that long mess mixed in with your application logic, especially if you're doing it in multiple places:
public static string ToStringLinqy<T>(this T[] array, string delimiter)
{
// edit: let's replace this with a "better" version using a StringBuilder
//return (array == null) ? null : (array.Length == 0) ? string.Empty : array.Skip(1).Aggregate(array[0].ToString(), (s, i) => s + "," + i.ToString());
return (array == null) ? null : (array.Length == 0) ? string.Empty : array.Skip(1).Aggregate(new StringBuilder(array[0].ToString()), (s, i) => s.Append(delimiter).Append(i), s => s.ToString());
}
But if you're going to put it into a utility function anyway, do you really need it to be condensed down into a 1-liner? In that case why not throw in a few extra lines for clarity and take advantage of a StringBuilder so that you're not doing repeated concatenation operations:
public static string ToStringNonLinqy<T>(this T[] array, string delimiter)
{
if (array != null)
{
// edit: replaced my previous implementation to use StringBuilder
if (array.Length > 0)
{
StringBuilder builder = new StringBuilder();
builder.Append(array[0]);
for (int i = 1; i < array.Length; i++)
{
builder.Append(delimiter);
builder.Append(array[i]);
}
return builder.ToString()
}
else
{
return string.Empty;
}
}
else
{
return null;
}
}
And if you're really so concerned about performance, you could even turn it into a hybrid function that decides whether to do string.Join or to use a StringBuilder depending on how many elements are in the array (this is a micro-optimization, not worth doing in my opinion and possibly more harmful than beneficial, but I'm using it as an example for this problem):
public static string ToString<T>(this T[] array, string delimiter)
{
if (array != null)
{
// determine if the length of the array is greater than the performance threshold for using a stringbuilder
// 10 is just an arbitrary threshold value I've chosen
if (array.Length < 10)
{
// assumption is that for arrays of less than 10 elements
// this code would be more efficient than a StringBuilder.
// Note: this is a crazy/pointless micro-optimization. Don't do this.
string[] values = new string[array.Length];
for (int i = 0; i < values.Length; i++)
values[i] = array[i].ToString();
return string.Join(delimiter, values);
}
else
{
// for arrays of length 10 or longer, use a StringBuilder
StringBuilder sb = new StringBuilder();
sb.Append(array[0]);
for (int i = 1; i < array.Length; i++)
{
sb.Append(delimiter);
sb.Append(array[i]);
}
return sb.ToString();
}
}
else
{
return null;
}
}
For this example, the performance impact is probably not worth caring about, but the point is that if you are in a situation where you actually do need to be concerned with the performance of your operations, whatever they are, then it will most likely be easier and more readable to handle that within a utility function than using a complex Linq expression.
That utility function still looks kind of clunky. Now let's ditch the hybrid stuff and do this:
// convert an enumeration of one type into an enumeration of another type
public static IEnumerable<TOut> Convert<TIn, TOut>(this IEnumerable<TIn> input, Func<TIn, TOut> conversion)
{
foreach (TIn value in input)
{
yield return conversion(value);
}
}
// concatenate the strings in an enumeration separated by the specified delimiter
public static string Delimit<T>(this IEnumerable<T> input, string delimiter)
{
IEnumerator<T> enumerator = input.GetEnumerator();
if (enumerator.MoveNext())
{
StringBuilder builder = new StringBuilder();
// start off with the first element
builder.Append(enumerator.Current);
// append the remaining elements separated by the delimiter
while (enumerator.MoveNext())
{
builder.Append(delimiter);
builder.Append(enumerator.Current);
}
return builder.ToString();
}
else
{
return string.Empty;
}
}
// concatenate all elements
public static string ToString<T>(this IEnumerable<T> input)
{
return ToString(input, string.Empty);
}
// concatenate all elements separated by a delimiter
public static string ToString<T>(this IEnumerable<T> input, string delimiter)
{
return input.Delimit(delimiter);
}
// concatenate all elements, each one left-padded to a minimum length
public static string ToString<T>(this IEnumerable<T> input, int minLength, char paddingChar)
{
return input.Convert(i => i.ToString().PadLeft(minLength, paddingChar)).Delimit(string.Empty);
}
Now we have separate and fairly compact utility functions, each of which are arguable useful on their own.
Ultimately, my point is not that you shouldn't use Linq, but rather just to say don't forget about the benefits of creating your own utility functions, even if they are small and perhaps only contain a single line that returns the result from a line of Linq code. If nothing else, you'll be able to keep your application code even more condensed than you could achieve with a line of Linq code, and if you are using it in multiple places, then using a utility function makes it easier to adjust your output in case you need to change it later.
For this problem, I'd rather just write something like this in my application code:
int[] arr = { 0, 1, 2, 3, 0, 1 };
// 012301
result = arr.ToString<int>();
// comma-separated values
// 0,1,2,3,0,1
result = arr.ToString(",");
// left-padded to 2 digits
// 000102030001
result = arr.ToString(2, '0');
The second parameter of findBy
is for ORDER.
$ens = $em->getRepository('AcmeBinBundle:Marks')
->findBy(
array('type'=> 'C12'),
array('id' => 'ASC')
);
Using a collection initializer
From C# 3, you can use collection initializers to construct a List and populate it using a single expression. The following example constructs a Human and its ContactNumbers:
var human = new Human(1, "Address", "Name") {
ContactNumbers = new List<ContactNumber>() {
new ContactNumber(1),
new ContactNumber(2),
new ContactNumber(3)
}
}
Specializing the Human
constructor
You can change the constructor of the Human
class to provide a way to populate the ContactNumbers
property:
public class Human
{
public Human(int id, string address, string name, IEnumerable<ContactNumber> contactNumbers) : this(id, address, name)
{
ContactNumbers = new List<ContactNumber>(contactNumbers);
}
public Human(int id, string address, string name, params ContactNumber[] contactNumbers) : this(id, address, name)
{
ContactNumbers = new List<ContactNumber>(contactNumbers);
}
}
// Using the first constructor:
List<ContactNumber> numbers = List<ContactNumber>() {
new ContactNumber(1),
new ContactNumber(2),
new ContactNumber(3)
};
var human = new Human(1, "Address", "Name", numbers);
// Using the second constructor:
var human = new Human(1, "Address", "Name",
new ContactNumber(1),
new ContactNumber(2),
new ContactNumber(3)
);
Bottom line
Which alternative is a best practice? Or at least a good practice? You judge it! IMO, the best practice is to write the program as clearly as possible to anyone who has to read it. Using the collection initializer is a winner for me, in this case. With much less code, it can do almost the same things as the alternatives -- at least, the alternatives I gave...
Track the value by hand.
var selects = jQuery("select.track_me");
selects.each(function (i, element) {
var select = jQuery(element);
var previousValue = select.val();
select.bind("change", function () {
var currentValue = select.val();
// Use currentValue and previousValue
// ...
previousValue = currentValue;
});
});
create table question_bank
(
question_id uniqueidentifier primary key,
question_exam_id uniqueidentifier not null constraint fk_exam_id foreign key references exams(exam_id),
question_text varchar(1024) not null,
question_point_value decimal
);
--That will work too. Pehaps a bit more intuitive construct?
Gradle 4.9+
gradle run --args='arg1 arg2'
This assumes your build.gradle
is configured with the Application plugin. Your build.gradle
should look similar to this:
plugins {
// Implicitly applies Java plugin
id: 'application'
}
application {
// URI of your main class/application's entry point (required)
mainClassName = 'org.gradle.sample.Main'
}
Pre-Gradle 4.9
Include the following in your build.gradle
:
run {
if (project.hasProperty("appArgs")) {
args Eval.me(appArgs)
}
}
Then to run: gradle run -PappArgs="['arg1', 'args2']"
I think the problem may be that you are not finding your element because of the "#" in your call to get it:
window.parent.document.getElementById('#target');
You only need the # if you are using jquery. Here it should be:
window.parent.document.getElementById('target');
Try this:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
switch (e.Key.ToString())
{
case "Return":
MessageBox.Show(" Enter pressed ");
break;
}
}
In js you can change zoom by
document.body.style.zoom="90%"
But it doesn't work in FF http://caniuse.com/#search=zoom
For ff you can try
-moz-transform: scale(0.9);
And check next topic How can I zoom an HTML element in Firefox and Opera?
update test1 t1, test2 t2
set t2.deptid = t1.deptid
where t2.employeeid = t1.employeeid
you can not use from keyword for the mysql
@RequestMapping("/op")
public ModelAndView method(Map<String, Object> model) {
model.put("att", "helloooo");
return new ModelAndView("dom/op");
}
In your .js
<script>
var valVar = [[${att}]];
</script>
Faced the same issue. To solve it,
$ sdk install gradle
using the package manager or $ brew install gradle
for mac. You might need to first install brew if not yet. When you define a server in server view, then it will create you a server runtime library with server libs (including servlet api), that can be assigned to your project. However, then everybody that uses your project, need to create the same type of runtime in his/her eclipse workspace even for compiling.
If you directly download the servlet api jar, than it could lead to problems, since it will be included into the artifacts of your projects, but will be also present in servlet container.
In Maven it is much nicer, since you can define the servlet api interfaces as a "provided" dependency, that means it is present in the "to be production" environment.
Answering to myself. From the RequireJS website:
//THIS WILL FAIL
define(['require'], function (require) {
var namedModule = require('name');
});
This fails because requirejs needs to be sure to load and execute all dependencies before calling the factory function above. [...] So, either do not pass in the dependency array, or if using the dependency array, list all the dependencies in it.
My solution:
// Modules configuration (modules that will be used as Jade helpers)
define(function () {
return {
'moment': 'path/to/moment',
'filesize': 'path/to/filesize',
'_': 'path/to/lodash',
'_s': 'path/to/underscore.string'
};
});
The loader:
define(['jade', 'lodash', 'config'], function (Jade, _, Config) {
var deps;
// Dynamic require
require(_.values(Config), function () {
deps = _.object(_.keys(Config), arguments);
// Use deps...
});
});
You first have to 'dot' source the script, so for you :
. .\Get-NetworkStatistics.ps1
The first 'dot' asks PowerShell to load the script file into your PowerShell environment, not to start it. You should also use set-ExecutionPolicy Unrestricted
or set-ExecutionPolicy AllSigned
see(the Execution Policy instructions).