The solution for my case is:
Although John Leidegren keeps shooting down the idea, Brian is correct. I've just got it working in Visual Studio.
To be clear a WPF application does not create a Console window by default.
You have to create a WPF Application and then change the OutputType to "Console Application". When you run the project you will see a console window with your WPF window in front of it.
It doesn't look very pretty, but I found it helpful as I wanted my app to be run from the command line with feedback in there, and then for certain command options I would display the WPF window.
I followed around five different answers as well as all the blog posts in the previous answers and still had problems. I was trying to add a listener to some existing code that was tracing using the TraceSource.TraceEvent(TraceEventType, Int32, String)
method where the TraceSource
object was initialised with a string making it a 'named source'.
For me the issue was not creating a valid combination of source and switch elements to target this source. Here is an example that will log to a file called tracelog.txt
. For the following code:
TraceSource source = new TraceSource("sourceName");
source.TraceEvent(TraceEventType.Verbose, 1, "Trace message");
I successfully managed to log with the following diagnostics configuration:
<system.diagnostics>
<sources>
<source name="sourceName" switchName="switchName">
<listeners>
<add
name="textWriterTraceListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="tracelog.txt" />
</listeners>
</source>
</sources>
<switches>
<add name="switchName" value="Verbose" />
</switches>
</system.diagnostics>
You can use code like this:
char *MyFunction(some arguments...)
{
char *pointer = malloc(size for the new array);
if (!pointer)
An error occurred, abort or do something about the error.
return pointer; // Return address of memory to the caller.
}
When you do this, the memory should later be freed, by passing the address to free.
There are other options. A routine might return a pointer to an array (or portion of an array) that is part of some existing structure. The caller might pass an array, and the routine merely writes into the array, rather than allocating space for a new array.
Duration in seconds using Python 2.7 and the YouTube API v3:
try:
dur = entry['contentDetails']['duration']
try:
minutes = int(dur[2:4]) * 60
except:
minutes = 0
try:
hours = int(dur[:2]) * 60 * 60
except:
hours = 0
secs = int(dur[5:7])
print hours, minutes, secs
video.duration = hours + minutes + secs
print video.duration
except Exception as e:
print "Couldnt extract time: %s" % e
pass
The .css()
method makes it super simple to find and set CSS properties and combined with other methods like .animate(), you can make some cool effects on your site.
In its simplest form, the .css()
method can set a single CSS property for a particular set of matched elements. You just pass the property and value as strings and the element’s CSS properties are changed.
$('.example').css('background-color', 'red');
This would set the ‘background-color’ property to ‘red’ for any element that had the class of ‘example’.
But you aren’t limited to just changing one property at a time. Sure, you could add a bunch of identical jQuery objects, each changing just one property at a time, but this is making several, unnecessary calls to the DOM and is a lot of repeated code.
Instead, you can pass the .css()
method a Javascript object that contains the properties and values as key/value pairs. This way, each property will then be set on the jQuery object all at once.
$('.example').css({
'background-color': 'red',
'border' : '1px solid red',
'color' : 'white',
'font-size': '32px',
'text-align' : 'center',
'display' : 'inline-block'
});
This will change all of these CSS properties on the ‘.example’ elements.
As you want to host all fonts (or some of them) at your own server, you a download fonts from this repo and use it the way you want: https://github.com/praisedpk/Local-Google-Fonts
If you just want to do this to fix the leverage browser caching issue that comes with Google Fonts, you can use alternative fonts CDN, and include fonts as:
<link href="https://pagecdn.io/lib/easyfonts/fonts.css" rel="stylesheet" />
Or a specific font, as:
<link href="https://pagecdn.io/lib/easyfonts/lato.css" rel="stylesheet" />
In Java, Dates are internally represented in UTC milliseconds since the epoch (so timezones are not taken into account, that's why you get the same results, as getTime()
gives you the mentioned milliseconds).
In your solution:
Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
long gmtTime = cSchedStartCal.getTime().getTime();
long timezoneAlteredTime = gmtTime + TimeZone.getTimeZone("Asia/Calcutta").getRawOffset();
Calendar cSchedStartCal1 = Calendar.getInstance(TimeZone.getTimeZone("Asia/Calcutta"));
cSchedStartCal1.setTimeInMillis(timezoneAlteredTime);
you just add the offset from GMT to the specified timezone ("Asia/Calcutta" in your example) in milliseconds, so this should work fine.
Another possible solution would be to utilise the static fields of the Calendar
class:
//instantiates a calendar using the current time in the specified timezone
Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
//change the timezone
cSchedStartCal.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
//get the current hour of the day in the new timezone
cSchedStartCal.get(Calendar.HOUR_OF_DAY);
Refer to stackoverflow.com/questions/7695859/ for a more in-depth explanation.
Quite simply:
You can set it as a no title bar theme in the activity's xml in the AndroidManifest
<activity
android:name=".AnActivity"
android:label="@string/a_string"
android:theme="@android:style/Theme.NoTitleBar">
</activity>
For Java 1.6 and lower, I believe the safest and cleanest API for this is Guava's Files.move.
Example:
File newFile = new File(oldFile.getParent(), "new-file-name.txt");
Files.move(oldFile.toPath(), newFile.toPath());
The first line makes sure that the location of the new file is the same directory, i.e. the parent directory of the old file.
EDIT: I wrote this before I started using Java 7, which introduced a very similar approach. So if you're using Java 7+, you should see and upvote kr37's answer.
The method MockMvcRequestBuilders.fileUpload
is deprecated use MockMvcRequestBuilders.multipart
instead.
This is an example:
import static org.hamcrest.CoreMatchers.containsString;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.multipart.MultipartFile;
/**
* Unit test New Controller.
*
*/
@RunWith(SpringRunner.class)
@WebMvcTest(NewController.class)
public class NewControllerTest {
private MockMvc mockMvc;
@Autowired
WebApplicationContext wContext;
@MockBean
private NewController newController;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(wContext)
.alwaysDo(MockMvcResultHandlers.print())
.build();
}
@Test
public void test() throws Exception {
// Mock Request
MockMultipartFile jsonFile = new MockMultipartFile("test.json", "", "application/json", "{\"key1\": \"value1\"}".getBytes());
// Mock Response
NewControllerResponseDto response = new NewControllerDto();
Mockito.when(newController.postV1(Mockito.any(Integer.class), Mockito.any(MultipartFile.class))).thenReturn(response);
mockMvc.perform(MockMvcRequestBuilders.multipart("/fileUpload")
.file("file", jsonFile.getBytes())
.characterEncoding("UTF-8"))
.andExpect(status().isOk());
}
}
If you want to take some shortcuts you can use Apache Commons IO:
import org.apache.commons.io.FileUtils;
String data = FileUtils.readFileToString(new File("..."), "UTF-8");
System.out.println(data);
:-)
Your virtualhost filename should be mysite.com.conf and should contain this info
<VirtualHost *:80>
# The ServerName directive sets the request scheme, hostname and port that
# the server uses to identify itself. This is used when creating
# redirection URLs. In the context of virtual hosts, the ServerName
# specifies what hostname must appear in the request's Host: header to
# match this virtual host. For the default virtual host (this file) this
# value is not decisive as it is used as a last resort host regardless.
# However, you must set it for any further virtual host explicitly.
ServerName mysite.com
ServerAlias www.mysite.com
ServerAdmin [email protected]
DocumentRoot /var/www/mysite
# Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
# error, crit, alert, emerg.
# It is also possible to configure the loglevel for particular
# modules, e.g.
#LogLevel info ssl:warn
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
<Directory "/var/www/mysite">
Options All
AllowOverride All
Require all granted
</Directory>
# For most configuration files from conf-available/, which are
# enabled or disabled at a global level, it is possible to
# include a line for only one particular virtual host. For example the
# following line enables the CGI configuration for this host only
# after it has been globally disabled with "a2disconf".
#Include conf-available/serve-cgi-bin.conf
</VirtualHost>
# vim: syntax=apache ts=4 sw=4 sts=4 sr noet
Add try this code .. Its working grt.......
<body>_x000D_
<?php_x000D_
if (isset($_POST['nav'])) {_x000D_
header("Location: $_POST[nav]");_x000D_
}_x000D_
?>_x000D_
<form id="page-changer" action="" method="post">_x000D_
<select name="nav">_x000D_
<option value="">Go to page...</option>_x000D_
<option value="http://css-tricks.com/">CSS-Tricks</option>_x000D_
<option value="http://digwp.com/">Digging Into WordPress</option>_x000D_
<option value="http://quotesondesign.com/">Quotes on Design</option>_x000D_
</select>_x000D_
<input type="submit" value="Go" id="submit" />_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
<html>_x000D_
<head>_x000D_
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>_x000D_
<script>_x000D_
$(function() {_x000D_
_x000D_
$("#submit").hide();_x000D_
_x000D_
$("#page-changer select").change(function() {_x000D_
window.location = $("#page-changer select option:selected").val();_x000D_
})_x000D_
_x000D_
});_x000D_
</script>_x000D_
</head>
_x000D_
I was totally lost on why my Gridview.Databind()
would not refresh.
My issue, I discovered, was my gridview was inside a UpdatePanel. To get my GridView to FINALLY refresh was this:
gvServerConfiguration.Databind()
uppServerConfiguration.Update()
uppServerConfiguration is the id associated with my UpdatePanel in my asp.net code.
Hope this helps someone.
I got similar error while working with datatable. What happens is when you use *ngFor inside another *ngFor datatable throw this error as it interepts angular change cycle. SO instead of using datatable inside datatable use one regular table or replace mf.data with the array name. This works fine.
Just in case someone wants to do that in PHP I posted a gist on Github
https://gist.github.com/redestructa/2a7691e7f3ae69ec5161220c99e2d1b3
simply call:
$output = $tablePrinter->printLinesIntoArray($items, ['title', 'chilProp2']);
you may need to adapt the code if you are using a php version older than 7.2
after that call echo or writeLine depending on your environment.
Go to Control Panel\All Control Panel Items\User Accounts using Explorer (not Internet Explorer!)
or
Change my environment variables
New...
(if you don't have enough permissions to add it in the System variables section, add it to the User variables section)
Add JAVA_HOME as Variable name and the JDK location as Variable value > OK
Test:
set JAVA_HOME
JAVA_HOME=C:\Program Files\Java\jdk1.8.0_60
To add view to a layout, you can use addView
method of the ViewGroup
class. For example,
TextView view = new TextView(getActivity());
view.setText("Hello World");
ViewGroup Layout = (LinearLayout) getActivity().findViewById(R.id.my_layout);
layout.addView(view);
There are also a number of remove methods. Check the documentation of ViewGroup. One simple way to remove view from a layout can be like,
layout.removeAllViews(); // then you will end up having a clean fresh layout
Found this...
bcp "SELECT top 1 BlobText FROM TableName" queryout "C:\DesinationFolder\FileName.txt" -T -c'
If you need to know about different options of bcp flags...
I finally found out how to do this! Basically you need to run adb shell
first and then while you're in the shell run su
, which will switch the shell to run as root!
$: adb shell
$: su
The one problem I still have is that sqlite3 is not installed so the command is not recognized.
For the latest versions it is needed to install libxml++2.6-dev like that:
apt-get install libxml++2.6-dev
There's a similar post here: http://techpad.co.uk/content.php?sid=137 which explains how to do it.
function file_get_contents_proxy($url,$proxy){
// Create context stream
$context_array = array('http'=>array('proxy'=>$proxy,'request_fulluri'=>true));
$context = stream_context_create($context_array);
// Use context stream with file_get_contents
$data = file_get_contents($url,false,$context);
// Return data via proxy
return $data;
}
I'll add my solution here as I couldn't find it mentioned here yet. I have a dynamic button whose image depends on the state of one control. The most simple solution for me was to set the image to nil
if the control was not present. The image was updated each time the control updated and thus, this was optimal for me. Just to be sure I also set the enabled
to NO
.
Setting the width to a minimal value did not work on iOS 7.
other solution:
In wp-includes/rewrite.php file, you'll see the code:
$this->category_structure = $this->front . 'category/';
just copy whole function, put in your functions.php and hook it. just change the above line with:
$this->category_structure = $this->front . '/';
What is a
when you call Ancestors('A',a)
? If a['A']
is None, or if a['A'][0]
is None, you'd receive that exception.
Click "File > New > Image Asset
"
Asset Type -> Choose -> Image
Browse your image
Set the other properties
Press Next
You will see the 4 different pixel-sizes of your images for use as a launcher-icon
Press Finish
!
Sybase :
% : Matches any string of zero or more characters.
_ : Matches a single character.
[specifier] : Brackets enclose ranges or sets, such as [a-f]
or [abcdef].Specifier can take two forms:
rangespec1-rangespec2:
rangespec1 indicates the start of a range of characters.
- is a special character, indicating a range.
rangespec2 indicates the end of a range of characters.
set:
can be composed of any discrete set of values, in any
order, such as [a2bR].The range [a-f], and the
sets [abcdef] and [fcbdae] return the same
set of values.
Specifiers are case-sensitive.
[^specifier] : A caret (^) preceding a specifier indicates
non-inclusion. [^a-f] means "not in the range
a-f"; [^a2bR] means "not a, 2, b, or R."
Here is how I got it to work if you just want to get it back to your first option e.g. "Choose an option" "Select_id_wrap" is obviously the div around the select, but I just want to make that clear just in case it has any bearing on how this works. Mine resets to a click function but I'm sure it will work inside of an on change as well...
$("#select_id_wrap").find("select option").prop("selected", false);
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd yyyy HH:mm:ss", Locale.ENGLISH);
//format as u want
try {
String dateStart = "June 14 2018 16:02:37";
cal.setTime(sdf.parse(dateStart));
//all done
} catch (ParseException e) {
e.printStackTrace();
}
The other answers show you how to make a list of data.frames when you already have a bunch of data.frames, e.g., d1
, d2
, .... Having sequentially named data frames is a problem, and putting them in a list is a good fix, but best practice is to avoid having a bunch of data.frames not in a list in the first place.
The other answers give plenty of detail of how to assign data frames to list elements, access them, etc. We'll cover that a little here too, but the Main Point is to say don't wait until you have a bunch of a data.frames
to add them to a list. Start with the list.
The rest of the this answer will cover some common cases where you might be tempted to create sequential variables, and show you how to go straight to lists. If you're new to lists in R, you might want to also read What's the difference between [[
and [
in accessing elements of a list?.
Don't ever create d1
d2
d3
, ..., dn
in the first place. Create a list d
with n
elements.
This is done pretty easily when reading in files. Maybe you've got files data1.csv, data2.csv, ...
in a directory. Your goal is a list of data.frames called mydata
. The first thing you need is a vector with all the file names. You can construct this with paste (e.g., my_files = paste0("data", 1:5, ".csv")
), but it's probably easier to use list.files
to grab all the appropriate files: my_files <- list.files(pattern = "\\.csv$")
. You can use regular expressions to match the files, read more about regular expressions in other questions if you need help there. This way you can grab all CSV files even if they don't follow a nice naming scheme. Or you can use a fancier regex pattern if you need to pick certain CSV files out from a bunch of them.
At this point, most R beginners will use a for
loop, and there's nothing wrong with that, it works just fine.
my_data <- list()
for (i in seq_along(my_files)) {
my_data[[i]] <- read.csv(file = my_files[i])
}
A more R-like way to do it is with lapply
, which is a shortcut for the above
my_data <- lapply(my_files, read.csv)
Of course, substitute other data import function for read.csv
as appropriate. readr::read_csv
or data.table::fread
will be faster, or you may also need a different function for a different file type.
Either way, it's handy to name the list elements to match the files
names(my_data) <- gsub("\\.csv$", "", my_files)
# or, if you prefer the consistent syntax of stringr
names(my_data) <- stringr::str_replace(my_files, pattern = ".csv", replacement = "")
This is super-easy, the base function split()
does it for you. You can split by a column (or columns) of the data, or by anything else you want
mt_list = split(mtcars, f = mtcars$cyl)
# This gives a list of three data frames, one for each value of cyl
This is also a nice way to break a data frame into pieces for cross-validation. Maybe you want to split mtcars
into training, test, and validation pieces.
groups = sample(c("train", "test", "validate"),
size = nrow(mtcars), replace = TRUE)
mt_split = split(mtcars, f = groups)
# and mt_split has appropriate names already!
Maybe you're simulating data, something like this:
my_sim_data = data.frame(x = rnorm(50), y = rnorm(50))
But who does only one simulation? You want to do this 100 times, 1000 times, more! But you don't want 10,000 data frames in your workspace. Use replicate
and put them in a list:
sim_list = replicate(n = 10,
expr = {data.frame(x = rnorm(50), y = rnorm(50))},
simplify = F)
In this case especially, you should also consider whether you really need separate data frames, or would a single data frame with a "group" column work just as well? Using data.table
or dplyr
it's quite easy to do things "by group" to a data frame.
If they're an odd assortment (which is unusual), you can simply assign them:
mylist <- list()
mylist[[1]] <- mtcars
mylist[[2]] <- data.frame(a = rnorm(50), b = runif(50))
...
If you have data frames named in a pattern, e.g., df1
, df2
, df3
, and you want them in a list, you can get
them if you can write a regular expression to match the names. Something like
df_list = mget(ls(pattern = "df[0-9]"))
# this would match any object with "df" followed by a digit in its name
# you can test what objects will be got by just running the
ls(pattern = "df[0-9]")
# part and adjusting the pattern until it gets the right objects.
Generally, mget
is used to get multiple objects and return them in a named list. Its counterpart get
is used to get a single object and return it (not in a list).
A common task is combining a list of data frames into one big data frame. If you want to stack them on top of each other, you would use rbind
for a pair of them, but for a list of data frames here are three good choices:
# base option - slower but not extra dependencies
big_data = do.call(what = rbind, args = df_list)
# data table and dplyr have nice functions for this that
# - are much faster
# - add id columns to identify the source
# - fill in missing values if some data frames have more columns than others
# see their help pages for details
big_data = data.table::rbindlist(df_list)
big_data = dplyr::bind_rows(df_list)
(Similarly using cbind
or dplyr::bind_cols
for columns.)
To merge (join) a list of data frames, you can see these answers. Often, the idea is to use Reduce
with merge
(or some other joining function) to get them together.
Put similar data in lists because you want to do similar things to each data frame, and functions like lapply
, sapply
do.call
, the purrr
package, and the old plyr
l*ply
functions make it easy to do that. Examples of people easily doing things with lists are all over SO.
Even if you use a lowly for loop, it's much easier to loop over the elements of a list than it is to construct variable names with paste
and access the objects with get
. Easier to debug, too.
Think of scalability. If you really only need three variables, it's fine to use d1
, d2
, d3
. But then if it turns out you really need 6, that's a lot more typing. And next time, when you need 10 or 20, you find yourself copying and pasting lines of code, maybe using find/replace to change d14
to d15
, and you're thinking this isn't how programming should be. If you use a list, the difference between 3 cases, 30 cases, and 300 cases is at most one line of code---no change at all if your number of cases is automatically detected by, e.g., how many .csv
files are in your directory.
You can name the elements of a list, in case you want to use something other than numeric indices to access your data frames (and you can use both, this isn't an XOR choice).
Overall, using lists will lead you to write cleaner, easier-to-read code, which will result in fewer bugs and less confusion.
For this task you can use already available plugins and bootstrap extensions. Or you can make your own confirmation popup with just 3 lines of code. Check it out.
Say we have this links (note data-href
instead of href
) or buttons that we want to have delete confirmation for:
<a href="#" data-href="delete.php?id=23" data-toggle="modal" data-target="#confirm-delete">Delete record #23</a>
<button class="btn btn-default" data-href="/delete.php?id=54" data-toggle="modal" data-target="#confirm-delete">
Delete record #54
</button>
Here #confirm-delete
points to a modal popup div in your HTML. It should have an "OK" button configured like this:
<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
...
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<a class="btn btn-danger btn-ok">Delete</a>
</div>
</div>
</div>
</div>
Now you only need this little javascript to make a delete action confirmable:
$('#confirm-delete').on('show.bs.modal', function(e) {
$(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));
});
So on show.bs.modal
event delete button href
is set to URL with corresponding record id.
Demo: http://plnkr.co/edit/NePR0BQf3VmKtuMmhVR7?p=preview
I realize that in some cases there might be needed to perform POST or DELETE request rather then GET. It it still pretty simple without too much code. Take a look at the demo below with this approach:
// Bind click to OK button within popup
$('#confirm-delete').on('click', '.btn-ok', function(e) {
var $modalDiv = $(e.delegateTarget);
var id = $(this).data('recordId');
$modalDiv.addClass('loading');
$.post('/api/record/' + id).then(function() {
$modalDiv.modal('hide').removeClass('loading');
});
});
// Bind to modal opening to set necessary data properties to be used to make request
$('#confirm-delete').on('show.bs.modal', function(e) {
var data = $(e.relatedTarget).data();
$('.title', this).text(data.recordTitle);
$('.btn-ok', this).data('recordId', data.recordId);
});
// Bind click to OK button within popup_x000D_
$('#confirm-delete').on('click', '.btn-ok', function(e) {_x000D_
_x000D_
var $modalDiv = $(e.delegateTarget);_x000D_
var id = $(this).data('recordId');_x000D_
_x000D_
$modalDiv.addClass('loading');_x000D_
setTimeout(function() {_x000D_
$modalDiv.modal('hide').removeClass('loading');_x000D_
}, 1000);_x000D_
_x000D_
// In reality would be something like this_x000D_
// $modalDiv.addClass('loading');_x000D_
// $.post('/api/record/' + id).then(function() {_x000D_
// $modalDiv.modal('hide').removeClass('loading');_x000D_
// });_x000D_
});_x000D_
_x000D_
// Bind to modal opening to set necessary data properties to be used to make request_x000D_
$('#confirm-delete').on('show.bs.modal', function(e) {_x000D_
var data = $(e.relatedTarget).data();_x000D_
$('.title', this).text(data.recordTitle);_x000D_
$('.btn-ok', this).data('recordId', data.recordId);_x000D_
});
_x000D_
.modal.loading .modal-content:before {_x000D_
content: 'Loading...';_x000D_
text-align: center;_x000D_
line-height: 155px;_x000D_
font-size: 20px;_x000D_
background: rgba(0, 0, 0, .8);_x000D_
position: absolute;_x000D_
top: 55px;_x000D_
bottom: 0;_x000D_
left: 0;_x000D_
right: 0;_x000D_
color: #EEE;_x000D_
z-index: 1000;_x000D_
}
_x000D_
<script data-require="jquery@*" data-semver="2.0.3" src="//code.jquery.com/jquery-2.0.3.min.js"></script>_x000D_
<script data-require="bootstrap@*" data-semver="3.1.1" src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>_x000D_
<link data-require="[email protected]" data-semver="3.1.1" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />_x000D_
_x000D_
<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">_x000D_
<div class="modal-dialog">_x000D_
<div class="modal-content">_x000D_
<div class="modal-header">_x000D_
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>_x000D_
<h4 class="modal-title" id="myModalLabel">Confirm Delete</h4>_x000D_
</div>_x000D_
<div class="modal-body">_x000D_
<p>You are about to delete <b><i class="title"></i></b> record, this procedure is irreversible.</p>_x000D_
<p>Do you want to proceed?</p>_x000D_
</div>_x000D_
<div class="modal-footer">_x000D_
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>_x000D_
<button type="button" class="btn btn-danger btn-ok">Delete</button>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<a href="#" data-record-id="23" data-record-title="The first one" data-toggle="modal" data-target="#confirm-delete">_x000D_
Delete "The first one", #23_x000D_
</a>_x000D_
<br />_x000D_
<button class="btn btn-default" data-record-id="54" data-record-title="Something cool" data-toggle="modal" data-target="#confirm-delete">_x000D_
Delete "Something cool", #54_x000D_
</button>
_x000D_
Demo: http://plnkr.co/edit/V4GUuSueuuxiGr4L9LmG?p=preview
Here is an original version of the code I made when I was answering this question for Bootstrap 2.3 modal.
$('#modal').on('show', function() {
var id = $(this).data('id'),
removeBtn = $(this).find('.danger');
removeBtn.attr('href', removeBtn.attr('href').replace(/(&|\?)ref=\d*/, '$1ref=' + id));
});
Interesting artcle...
I've had a quick hunt around on google and found nothing, but you might want to check some of the comments - plenty of people seem to have had a go at implementing a simple component demo, you might want to take a look at some of theirs for inspiration:
http://www.unseen-academy.de/componentSystem.html
http://www.mcshaffry.com/GameCode/thread.php?threadid=732
http://www.codeplex.com/Wikipage?ProjectName=elephant
Also, the comments themselves seem to have a fairly in-depth discussion on how you might code up such a system.
psutil provides a portable way that doesn't use environment variables like the getpass
solution. It is less prone to security issues, and should probably be the accepted answer as of today.
import psutil
def get_username():
return psutil.Process().username()
Under the hood, this combines the getpwuid
based method for unix and the GetTokenInformation
method for Windows.
You can replicate the functionality of touch with the following command:
$>>filename
What this does is attempts to execute a program called $
, but if $
does not exist (or is not an executable that produces output) then no output is produced by it. It is essentially a hack on the functionality, however you will get the following error message:
'$' is not recognized as an internal or external command, operable program or batch file.
If you don't want the error message then you can do one of two things:
type nul >> filename
Or:
$>>filename 2>nul
The type
command tries to display the contents of nul, which does nothing but returns an EOF (end of file) when read.
2>nul
sends error-output (output 2) to nul (which ignores all input when written to). Obviously the second command (with 2>nul
) is made redundant by the type
command since it is quicker to type. But at least you now have the option and the knowledge.
if (mysql_query("INSERT INTO PEOPLE (NAME ) VALUES ('COLE')")or die(mysql_error())) {
echo 'Success';
} else {
echo 'Fail';
}
Although since you have or die(mysql_error())
it will show the mysql_error() on the screen when it fails. You should probably remove that if it isnt the desired result
1st of all, when you declare a variable in java, you should declare it using Interfaces even if you specify the implementation when instantiating it
ArrayList<ArrayList<String>> listOfLists = new ArrayList<ArrayList<String>>();
should be written
List<List<String>> listOfLists = new ArrayList<List<String>>(size);
Then you will have to instantiate all columns of your 2d array
for(int i = 0; i < size; i++) {
listOfLists.add(new ArrayList<String>());
}
And you will use it like this :
listOfLists.get(0).add("foobar");
But if you really want to "create a 2D array that each cell is an ArrayList!"
Then you must go the dijkstra way.
Instead of <nav class="navbar ...
use <nav class="navbar navbar-xs...
and add these 3 line of css
.navbar-xs { min-height:28px; height: 28px; }
.navbar-xs .navbar-brand{ padding: 0px 12px;font-size: 16px;line-height: 28px; }
.navbar-xs .navbar-nav > li > a { padding-top: 0px; padding-bottom: 0px; line-height: 28px; }
Output :
You can specify it in your IDE. For example, for Eclipse in Run Configurations ? VM arguments. You can enter -Xmx800m -Xms500m
as
If you use Microsoft.Extensions.Hosting
(version 2.1.0+) to host your console app and asp.net core app, all your configurations are injected with HostBuilder
's ConfigureAppConfiguration
and ConfigureHostConfiguration
methods. Here's the demo about how to add the appsettings.json
and environment variables:
var hostBuilder = new HostBuilder()
.ConfigureHostConfiguration(config =>
{
config.AddEnvironmentVariables();
if (args != null)
{
// enviroment from command line
// e.g.: dotnet run --environment "Staging"
config.AddCommandLine(args);
}
})
.ConfigureAppConfiguration((context, builder) =>
{
var env = context.HostingEnvironment;
builder.SetBasePath(AppContext.BaseDirectory)
.AddJsonFile("appsettings.json", optional: false)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
// Override config by env, using like Logging:Level or Logging__Level
.AddEnvironmentVariables();
})
... // add others, logging, services
//;
In order to compile above code, you need to add these packages:
<PackageReference Include="Microsoft.Extensions.Configuration" Version="2.1.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.CommandLine" Version="2.1.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="2.1.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.1.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="2.1.0" />
Try moving your layout xml from res/layout-land
to res/layout
folder
The two forms are the same with one exception: temporarily, the new (Object *)
has an undefined value when the creation and assignment are separate. The compiler may combine them back together, since the undefined pointer is not particularly useful. This does not relate to global variables (unless the declaration is global, in which case it's still true for both forms).
Use In
instead of =
select * from dbo.books
where isbn in (select isbn from dbo.lending
where act between @fdate and @tdate
and stat ='close'
)
or you can use Exists
SELECT t1.*,t2.*
FROM books t1
WHERE EXISTS ( SELECT * FROM dbo.lending t2 WHERE t1.isbn = t2.isbn and
t2.act between @fdate and @tdate and t2.stat ='close' )
You use return false to prevent something from happening. So if you have a script running on submit then return false will prevent the submit from working.
This builds on the above answer from Gordon--not all of it is my original work. What I did was add a more generic method to my static utility class.
public static int MatchingRowIndex(DataGridView dgv, string columnName, string searchValue)
{
int rowIndex = -1;
bool tempAllowUserToAddRows = dgv.AllowUserToAddRows;
dgv.AllowUserToAddRows = false; // Turn off or .Value below will throw null exception
if (dgv.Rows.Count > 0 && dgv.Columns.Count > 0 && dgv.Columns[columnName] != null)
{
DataGridViewRow row = dgv.Rows
.Cast<DataGridViewRow>()
.FirstOrDefault(r => r.Cells[columnName].Value.ToString().Equals(searchValue));
rowIndex = row.Index;
}
dgv.AllowUserToAddRows = tempAllowUserToAddRows;
return rowIndex;
}
Then in whatever form I want to use it, I call the method passing the DataGridView, column name and search value. For simplicity I am converting everything to strings for the search, though it would be easy enough to add overloads for specifying the data types.
private void UndeleteSectionInGrid(string sectionLetter)
{
int sectionRowIndex = UtilityMethods.MatchingRowIndex(dgvSections, "SectionLetter", sectionLetter);
dgvSections.Rows[sectionRowIndex].Cells["DeleteSection"].Value = false;
}
My first guess is that LaTeX chokes on | outside a math environment. Missing $ inserted is usually a symptom of something like that.
If you are looking for a simple and free alternative to Google Feed API for your rss widget then rss2json.com could be a suitable solution for that.
You may try to see how it works on a sample code from the api documentation below:
google.load("feeds", "1");_x000D_
_x000D_
function initialize() {_x000D_
var feed = new google.feeds.Feed("https://news.ycombinator.com/rss");_x000D_
feed.load(function(result) {_x000D_
if (!result.error) {_x000D_
var container = document.getElementById("feed");_x000D_
for (var i = 0; i < result.feed.entries.length; i++) {_x000D_
var entry = result.feed.entries[i];_x000D_
var div = document.createElement("div");_x000D_
div.appendChild(document.createTextNode(entry.title));_x000D_
container.appendChild(div);_x000D_
}_x000D_
}_x000D_
});_x000D_
}_x000D_
google.setOnLoadCallback(initialize);
_x000D_
<html>_x000D_
<head> _x000D_
<script src="https://rss2json.com/gfapi.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
<p><b>Result from the API:</b></p>_x000D_
<div id="feed"></div>_x000D_
</body>_x000D_
</html>
_x000D_
If you are using Debian style virtual host configuration (sites-available/sites-enabled), one way to set a Default VirtualHost is to include the specific configuration file first in httpd.conf or apache.conf (or what ever is your main configuration file).
# To set default VirtualHost, include it before anything else.
IncludeOptional sites-enabled/my.site.com.conf
# Load config files in the "/etc/httpd/conf.d" directory, if any.
IncludeOptional conf.d/*.conf
# Load virtual host config files from "/etc/httpd/sites-enabled/".
IncludeOptional sites-enabled/*.conf
You can't have a link to SCSS File in your HTML page.You have to compile it down to CSS First. No there are lots of video tutorials you might want to check out. Lynda provides great video tutorials on SASS. there are also free screencasts you can google...
For official documentation visit this site http://sass-lang.com/documentation/file.SASS_REFERENCE.html And why have you chosen notepad to write Sass?? you can easily download some free text editors for better code handling.
I had a similar problem. In my case, I had accidentally included winuser.h
before windows.h
(actually, a buggy IDE extension had added it). Removing the winuser.h
solved the problem.
In JavaScript, the type of key/value store you are attempting to use is an object literal, rather than an array. You are mistakenly creating a composite array object, which happens to have other properties based on the key names you provided, but the array portion contains no elements.
Instead, declare valueToPush
as an object and push that onto cookie_value_add
:
// Create valueToPush as an object {} rather than an array []
var valueToPush = {};
// Add the properties to your object
// Note, you could also use the valueToPush["productID"] syntax you had
// above, but this is a more object-like syntax
valueToPush.productID = productID;
valueToPush.itemColorTitle = itemColorTitle;
valueToPush.itemColorPath = itemColorPath;
cookie_value_add.push(valueToPush);
// View the structure of cookie_value_add
console.dir(cookie_value_add);
The shortest and simpliest way here is to use
df.eval('e = a + b + d')
The getParent
method returns a ViewParent
, not a View
. You need to cast the first call to getParent()
also:
RelativeLayout r = (RelativeLayout) ((ViewGroup) this.getParent()).getParent();
As stated in the comments by the OP, this is causing a NPE
. To debug, split this up into multiple parts:
ViewParent parent = this.getParent();
RelativeLayout r;
if (parent == null) {
Log.d("TEST", "this.getParent() is null");
}
else {
if (parent instanceof ViewGroup) {
ViewParent grandparent = ((ViewGroup) parent).getParent();
if (grandparent == null) {
Log.d("TEST", "((ViewGroup) this.getParent()).getParent() is null");
}
else {
if (parent instanceof RelativeLayout) {
r = (RelativeLayout) grandparent;
}
else {
Log.d("TEST", "((ViewGroup) this.getParent()).getParent() is not a RelativeLayout");
}
}
}
else {
Log.d("TEST", "this.getParent() is not a ViewGroup");
}
}
//now r is set to the desired RelativeLayout.
I know I am quite late to post this, but I share similar experience when I learned the ropes of IAP model.
In-app purchase is one of the most comprehensive workflow in iOS implemented by Storekit framework. The entire documentation is quite clear if you patience to read it, but is somewhat advanced in nature of technicality.
To summarize:
1 - Request the products - use SKProductRequest & SKProductRequestDelegate classes to issue request for Product IDs and receive them back from your own itunesconnect store.
These SKProducts should be used to populate your store UI which the user can use to buy a specific product.
2 - Issue payment request - use SKPayment & SKPaymentQueue to add payment to the transaction queue.
3 - Monitor transaction queue for status update - use SKPaymentTransactionObserver Protocol's updatedTransactions method to monitor status:
SKPaymentTransactionStatePurchasing - don't do anything
SKPaymentTransactionStatePurchased - unlock product, finish the transaction
SKPaymentTransactionStateFailed - show error, finish the transaction
SKPaymentTransactionStateRestored - unlock product, finish the transaction
4 - Restore button flow - use SKPaymentQueue's restoreCompletedTransactions to accomplish this - step 3 will take care of the rest, along with SKPaymentTransactionObserver's following methods:
paymentQueueRestoreCompletedTransactionsFinished
restoreCompletedTransactionsFailedWithError
Here is a step by step tutorial (authored by me as a result of my own attempts to understand it) that explains it. At the end it also provides code sample that you can directly use.
Here is another one I created to explain certain things that only text could describe in better manner.
it is working when adding :
select { width:115% }
Here is an example:
I've an Order table with a DateTime field called OrderDate. I want to retrieve all orders where the order date is equals to 01/01/2006. there are next ways to do it:
1) WHERE DateDiff(dd, OrderDate, '01/01/2006') = 0
2) WHERE Convert(varchar(20), OrderDate, 101) = '01/01/2006'
3) WHERE Year(OrderDate) = 2006 AND Month(OrderDate) = 1 and Day(OrderDate)=1
4) WHERE OrderDate LIKE '01/01/2006%'
5) WHERE OrderDate >= '01/01/2006' AND OrderDate < '01/02/2006'
Is found here
You can take a look here for a longer list of screen sizes and respective media queries.
Or go for Bootstrap media queries:
/* Large desktop */
@media (min-width: 1200px) { ... }
/* Portrait tablet to landscape and desktop */
@media (min-width: 768px) and (max-width: 979px) { ... }
/* Landscape phone to portrait tablet */
@media (max-width: 767px) { ... }
/* Landscape phones and down */
@media (max-width: 480px) { ... }
Additionally you might wanty to take a look at Foundation's media queries with the following default settings:
// Media Queries
$screenSmall: 768px !default;
$screenMedium: 1279px !default;
$screenXlarge: 1441px !default;
Nc is a link to nmap-ncat.
It would be nice to use nmap-ncat in your puppet, because NC is a virtual name of nmap-ncat.
Puppet cannot understand the links/virtualnames
your puppet should be:
package {
'nmap-ncat':
ensure => installed;
}
The name of the public class within a file has to be the same as the name of that file.
So if your file declares class WeatherArray, it needs to be named WeatherArray.java
Google released In-App Updates for the Play Core library.
I implemented a lightweight library to easily implement in-app updates. You can find to the following link an example about how to force the user to perform the update.
https://github.com/dnKaratzas/android-inapp-update#forced-updates
How about doing it like this:
1) show popup with form
2) submit form using AJAX
3) in AJAX server side code, render response that will either:
Edit /etc/sudoers
file either manually or using the visudo application.
Remember: System reads /etc/sudoers
file from top to the bottom, so you could overwrite a particular setting by putting the next one below.
So to be on the safe side - define your access setting at the bottom.
Lets say we have a variable called x, as below:
var x;
following statement is valid,
x = 10;
x = "a";
x = 0;
x = undefined;
x = null;
1. Number:
x = 10;
if(x){
//True
}
and for x = undefined
or x = 0
(be careful here)
if(x){
//False
}
2. String x = null
, x = undefined
or x = ""
if(x){
//False
}
3 Boolean x = false
and x = undefined
,
if(x){
//False
}
By keeping above in mind we can easily check, whether variable is empty, null, 0 or undefined in Angular js. Angular js doest provide separate API to check variable values emptiness.
Try
document.location.host
or
document.location.hostname
I think what you want is this:
Html.ActionLink(article.Title,
"Login", // <-- Controller Name.
"Item", // <-- ActionMethod
new { id = article.ArticleID }, // <-- Route arguments.
null // <-- htmlArguments .. which are none. You need this value
// otherwise you call the WRONG method ...
// (refer to comments, below).
)
This uses the following method ActionLink signature:
public static string ActionLink(this HtmlHelper htmlHelper,
string linkText,
string controllerName,
string actionName,
object values,
object htmlAttributes)
two arguments have been switched around
Html.ActionLink(article.Title,
"Item", // <-- ActionMethod
"Login", // <-- Controller Name.
new { id = article.ArticleID }, // <-- Route arguments.
null // <-- htmlArguments .. which are none. You need this value
// otherwise you call the WRONG method ...
// (refer to comments, below).
)
This uses the following method ActionLink signature:
public static string ActionLink(this HtmlHelper htmlHelper,
string linkText,
string actionName,
string controllerName,
object values,
object htmlAttributes)
arguments are in the same order as MVC2, however the id value is no longer required:
Html.ActionLink(article.Title,
"Item", // <-- ActionMethod
"Login", // <-- Controller Name.
new { article.ArticleID }, // <-- Route arguments.
null // <-- htmlArguments .. which are none. You need this value
// otherwise you call the WRONG method ...
// (refer to comments, below).
)
This avoids hard-coding any routing logic into the link.
<a href="/Item/Login/5">Title</a>
This will give you the following html output, assuming:
article.Title = "Title"
article.ArticleID = 5
. .
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
Is it possible (work only online and load only your page or file): https://w3schools.com/xml/xml_http.asp Try my code:
function load_page(){
qr=new XMLHttpRequest();
qr.open('get','YOUR_file_or_page.htm');
qr.send();
qr.onload=function(){YOUR_div_id.innerHTML=qr.responseText}
};load_page();
qr.onreadystatechange instead qr.onload also use.
You can use kill-port. In firstly, kill exist port and in secondly create server and listen.
const kill = require('kill-port')
kill(port, 'tcp')
.then((d) => {
/**
* Create HTTP server.
*/
server = http.createServer(app);
server.listen(port, () => {
console.log(`api running on port:${port}`);
});
})
.catch((e) => {
console.error(e);
})
Visual Studio 2019 with CMake
Add the following to CMakeLists.txt
:
add_definitions(-D_CRT_SECURE_NO_WARNINGS)
Modify checkbox style with plain CSS3, don't required any JS&HTML manipulation.
.form input[type="checkbox"]:before {_x000D_
display: inline-block;_x000D_
font: normal normal normal 14px/1 FontAwesome;_x000D_
font-size: inherit;_x000D_
text-rendering: auto;_x000D_
-webkit-font-smoothing: antialiased;_x000D_
content: "\f096";_x000D_
opacity: 1 !important;_x000D_
margin-top: -25px;_x000D_
appearance: none;_x000D_
background: #fff;_x000D_
}_x000D_
_x000D_
.form input[type="checkbox"]:checked:before {_x000D_
content: "\f046";_x000D_
}_x000D_
_x000D_
.form input[type="checkbox"] {_x000D_
font-size: 22px;_x000D_
appearance: none;_x000D_
-webkit-appearance: none;_x000D_
-moz-appearance: none;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />_x000D_
_x000D_
<form class="form">_x000D_
<input type="checkbox" />_x000D_
</form>
_x000D_
For a dictionary speedup, there is one general transformation/process you can do to greatly reduce the dictionary comparisons ahead of time.
Given that the above grid contains only 16 characters, some of them duplicate, you can greatly reduce the number of total keys in your dictionary by simply filtering out entries that have unattainable characters.
I thought this was the obvious optimization but seeing nobody did it I'm mentioning it.
It reduced me from a dictionary of 200,000 keys to only 2,000 keys simply during the input pass. This at the very least reduces memory overhead, and that's sure to map to a speed increase somewhere as memory isn't infinitely fast.
My implementation is a bit top-heavy because I placed importance on being able to know the exact path of every extracted string, not just the validity therein.
I also have a few adaptions in there that would theoretically permit a grid with holes in it to function, and grids with different sized lines ( assuming you get the input right and it lines up somehow ).
The early-filter is by far the most significant bottleneck in my application, as suspected earlier, commenting out that line bloats it from 1.5s to 7.5s.
Upon execution it appears to think all the single digits are on their own valid words, but I'm pretty sure thats due to how the dictionary file works.
Its a bit bloated, but at least I reuse Tree::Trie from cpan
Some of it was inspired partially by the existing implementations, some of it I had in mind already.
Constructive Criticism and ways it could be improved welcome ( /me notes he never searched CPAN for a boggle solver, but this was more fun to work out )
updated for new criteria
#!/usr/bin/perl
use strict;
use warnings;
{
# this package manages a given path through the grid.
# Its an array of matrix-nodes in-order with
# Convenience functions for pretty-printing the paths
# and for extending paths as new paths.
# Usage:
# my $p = Prefix->new(path=>[ $startnode ]);
# my $c = $p->child( $extensionNode );
# print $c->current_word ;
package Prefix;
use Moose;
has path => (
isa => 'ArrayRef[MatrixNode]',
is => 'rw',
default => sub { [] },
);
has current_word => (
isa => 'Str',
is => 'rw',
lazy_build => 1,
);
# Create a clone of this object
# with a longer path
# $o->child( $successive-node-on-graph );
sub child {
my $self = shift;
my $newNode = shift;
my $f = Prefix->new();
# Have to do this manually or other recorded paths get modified
push @{ $f->{path} }, @{ $self->{path} }, $newNode;
return $f;
}
# Traverses $o->path left-to-right to get the string it represents.
sub _build_current_word {
my $self = shift;
return join q{}, map { $_->{value} } @{ $self->{path} };
}
# Returns the rightmost node on this path
sub tail {
my $self = shift;
return $self->{path}->[-1];
}
# pretty-format $o->path
sub pp_path {
my $self = shift;
my @path =
map { '[' . $_->{x_position} . ',' . $_->{y_position} . ']' }
@{ $self->{path} };
return "[" . join( ",", @path ) . "]";
}
# pretty-format $o
sub pp {
my $self = shift;
return $self->current_word . ' => ' . $self->pp_path;
}
__PACKAGE__->meta->make_immutable;
}
{
# Basic package for tracking node data
# without having to look on the grid.
# I could have just used an array or a hash, but that got ugly.
# Once the matrix is up and running it doesn't really care so much about rows/columns,
# Its just a sea of points and each point has adjacent points.
# Relative positioning is only really useful to map it back to userspace
package MatrixNode;
use Moose;
has x_position => ( isa => 'Int', is => 'rw', required => 1 );
has y_position => ( isa => 'Int', is => 'rw', required => 1 );
has value => ( isa => 'Str', is => 'rw', required => 1 );
has siblings => (
isa => 'ArrayRef[MatrixNode]',
is => 'rw',
default => sub { [] }
);
# Its not implicitly uni-directional joins. It would be more effient in therory
# to make the link go both ways at the same time, but thats too hard to program around.
# and besides, this isn't slow enough to bother caring about.
sub add_sibling {
my $self = shift;
my $sibling = shift;
push @{ $self->siblings }, $sibling;
}
# Convenience method to derive a path starting at this node
sub to_path {
my $self = shift;
return Prefix->new( path => [$self] );
}
__PACKAGE__->meta->make_immutable;
}
{
package Matrix;
use Moose;
has rows => (
isa => 'ArrayRef',
is => 'rw',
default => sub { [] },
);
has regex => (
isa => 'Regexp',
is => 'rw',
lazy_build => 1,
);
has cells => (
isa => 'ArrayRef',
is => 'rw',
lazy_build => 1,
);
sub add_row {
my $self = shift;
push @{ $self->rows }, [@_];
}
# Most of these functions from here down are just builder functions,
# or utilities to help build things.
# Some just broken out to make it easier for me to process.
# All thats really useful is add_row
# The rest will generally be computed, stored, and ready to go
# from ->cells by the time either ->cells or ->regex are called.
# traverse all cells and make a regex that covers them.
sub _build_regex {
my $self = shift;
my $chars = q{};
for my $cell ( @{ $self->cells } ) {
$chars .= $cell->value();
}
$chars = "[^$chars]";
return qr/$chars/i;
}
# convert a plain cell ( ie: [x][y] = 0 )
# to an intelligent cell ie: [x][y] = object( x, y )
# we only really keep them in this format temporarily
# so we can go through and tie in neighbouring information.
# after the neigbouring is done, the grid should be considered inoperative.
sub _convert {
my $self = shift;
my $x = shift;
my $y = shift;
my $v = $self->_read( $x, $y );
my $n = MatrixNode->new(
x_position => $x,
y_position => $y,
value => $v,
);
$self->_write( $x, $y, $n );
return $n;
}
# go through the rows/collums presently available and freeze them into objects.
sub _build_cells {
my $self = shift;
my @out = ();
my @rows = @{ $self->{rows} };
for my $x ( 0 .. $#rows ) {
next unless defined $self->{rows}->[$x];
my @col = @{ $self->{rows}->[$x] };
for my $y ( 0 .. $#col ) {
next unless defined $self->{rows}->[$x]->[$y];
push @out, $self->_convert( $x, $y );
}
}
for my $c (@out) {
for my $n ( $self->_neighbours( $c->x_position, $c->y_position ) ) {
$c->add_sibling( $self->{rows}->[ $n->[0] ]->[ $n->[1] ] );
}
}
return \@out;
}
# given x,y , return array of points that refer to valid neighbours.
sub _neighbours {
my $self = shift;
my $x = shift;
my $y = shift;
my @out = ();
for my $sx ( -1, 0, 1 ) {
next if $sx + $x < 0;
next if not defined $self->{rows}->[ $sx + $x ];
for my $sy ( -1, 0, 1 ) {
next if $sx == 0 && $sy == 0;
next if $sy + $y < 0;
next if not defined $self->{rows}->[ $sx + $x ]->[ $sy + $y ];
push @out, [ $sx + $x, $sy + $y ];
}
}
return @out;
}
sub _has_row {
my $self = shift;
my $x = shift;
return defined $self->{rows}->[$x];
}
sub _has_cell {
my $self = shift;
my $x = shift;
my $y = shift;
return defined $self->{rows}->[$x]->[$y];
}
sub _read {
my $self = shift;
my $x = shift;
my $y = shift;
return $self->{rows}->[$x]->[$y];
}
sub _write {
my $self = shift;
my $x = shift;
my $y = shift;
my $v = shift;
$self->{rows}->[$x]->[$y] = $v;
return $v;
}
__PACKAGE__->meta->make_immutable;
}
use Tree::Trie;
sub readDict {
my $fn = shift;
my $re = shift;
my $d = Tree::Trie->new();
# Dictionary Loading
open my $fh, '<', $fn;
while ( my $line = <$fh> ) {
chomp($line);
# Commenting the next line makes it go from 1.5 seconds to 7.5 seconds. EPIC.
next if $line =~ $re; # Early Filter
$d->add( uc($line) );
}
return $d;
}
sub traverseGraph {
my $d = shift;
my $m = shift;
my $min = shift;
my $max = shift;
my @words = ();
# Inject all grid nodes into the processing queue.
my @queue =
grep { $d->lookup( $_->current_word ) }
map { $_->to_path } @{ $m->cells };
while (@queue) {
my $item = shift @queue;
# put the dictionary into "exact match" mode.
$d->deepsearch('exact');
my $cword = $item->current_word;
my $l = length($cword);
if ( $l >= $min && $d->lookup($cword) ) {
push @words,
$item; # push current path into "words" if it exactly matches.
}
next if $l > $max;
# put the dictionary into "is-a-prefix" mode.
$d->deepsearch('boolean');
siblingloop: foreach my $sibling ( @{ $item->tail->siblings } ) {
foreach my $visited ( @{ $item->{path} } ) {
next siblingloop if $sibling == $visited;
}
# given path y , iterate for all its end points
my $subpath = $item->child($sibling);
# create a new path for each end-point
if ( $d->lookup( $subpath->current_word ) ) {
# if the new path is a prefix, add it to the bottom of the queue.
push @queue, $subpath;
}
}
}
return \@words;
}
sub setup_predetermined {
my $m = shift;
my $gameNo = shift;
if( $gameNo == 0 ){
$m->add_row(qw( F X I E ));
$m->add_row(qw( A M L O ));
$m->add_row(qw( E W B X ));
$m->add_row(qw( A S T U ));
return $m;
}
if( $gameNo == 1 ){
$m->add_row(qw( D G H I ));
$m->add_row(qw( K L P S ));
$m->add_row(qw( Y E U T ));
$m->add_row(qw( E O R N ));
return $m;
}
}
sub setup_random {
my $m = shift;
my $seed = shift;
srand $seed;
my @letters = 'A' .. 'Z' ;
for( 1 .. 4 ){
my @r = ();
for( 1 .. 4 ){
push @r , $letters[int(rand(25))];
}
$m->add_row( @r );
}
}
# Here is where the real work starts.
my $m = Matrix->new();
setup_predetermined( $m, 0 );
#setup_random( $m, 5 );
my $d = readDict( 'dict.txt', $m->regex );
my $c = scalar @{ $m->cells }; # get the max, as per spec
print join ",\n", map { $_->pp } @{
traverseGraph( $d, $m, 3, $c ) ;
};
Arch/execution info for comparison:
model name : Intel(R) Core(TM)2 Duo CPU T9300 @ 2.50GHz
cache size : 6144 KB
Memory usage summary: heap total: 77057577, heap peak: 11446200, stack peak: 26448
total calls total memory failed calls
malloc| 947212 68763684 0
realloc| 11191 1045641 0 (nomove:9063, dec:4731, free:0)
calloc| 121001 7248252 0
free| 973159 65854762
Histogram for block sizes:
0-15 392633 36% ==================================================
16-31 43530 4% =====
32-47 50048 4% ======
48-63 70701 6% =========
64-79 18831 1% ==
80-95 19271 1% ==
96-111 238398 22% ==============================
112-127 3007 <1%
128-143 236727 21% ==============================
The regex optimization I use is useless for multi-solve dictionaries, and for multi-solve you'll want a full dictionary, not a pre-trimmed one.
However, that said, for one-off solves, its really fast. ( Perl regex are in C! :) )
Here is some varying code additions:
sub readDict_nofilter {
my $fn = shift;
my $re = shift;
my $d = Tree::Trie->new();
# Dictionary Loading
open my $fh, '<', $fn;
while ( my $line = <$fh> ) {
chomp($line);
$d->add( uc($line) );
}
return $d;
}
sub benchmark_io {
use Benchmark qw( cmpthese :hireswallclock );
# generate a random 16 character string
# to simulate there being an input grid.
my $regexen = sub {
my @letters = 'A' .. 'Z' ;
my @lo = ();
for( 1..16 ){
push @lo , $_ ;
}
my $c = join '', @lo;
$c = "[^$c]";
return qr/$c/i;
};
cmpthese( 200 , {
filtered => sub {
readDict('dict.txt', $regexen->() );
},
unfiltered => sub {
readDict_nofilter('dict.txt');
}
});
}
s/iter unfiltered filtered unfiltered 8.16 -- -94% filtered 0.464 1658% --
ps: 8.16 * 200 = 27 minutes.
These are the steps I took to correct this:
Back up your my.cnf file in /etc/mysql and remove or rename it
sudo mv /etc/mysql/my.cnf /etc/mysql/my.cnf.bak
Remove the folder /etc/mysql/mysql.conf.d/ using
sudo rm -r /etc/mysql/mysql.conf.d/
Verify you don't have a my.cnf file stashed somewhere else (I did in my home dir!) or in /etc/alternatives/my.cnf use
sudo find / -name my.cnf
Now reinstall every thing
sudo apt purge mysql-server mysql-server-5.7 mysql-server-core-5.7
sudo apt install mysql-server
In case your syslog shows an error like "mysqld: Can't read dir of '/etc/mysql/conf.d/'" create a symbolic link:
sudo ln -s /etc/mysql/mysql.conf.d /etc/mysql/conf.d
Then the service should be able to start with sudo service mysql start.
I hope it work
For those of you that run ZShell with Iterm2, add this to your ~/.zshrc
file.
alias code="/Applications/Visual\ Studio\ Code.app/Contents/Resources/app/bin/code"
Mac OS: On Terminal:
vim <your jar location>
after jar gets opened, press / and pass your class name and hit enter
Assuming your ints are 0, 375, 668,5 and 6:
{
"Id": "610",
"Name": "15",
"Description": "1.99",
"ItemModList": [
0,
375,
668,
5,
6
]
}
I suggest that you change "Id": "610" to "Id": 610 since it is a integer/long and not a string. You can read more about the JSON format and examples here http://json.org/
Sometimes (not often!) you do truly know more about past, current and future memory usage then the run time does. This does not happen very often, and I would claim never in a web application while normal pages are being served.
Many year ago I work on a report generator, that
Firstly as it was not real time and the users expected to wait for a report, a delay while the GC run was not an issue, but we needed to produce reports at a rate that was faster than they were requested.
Looking at the above outline of the process, it is clear that.
Therefore clearly it was well worth while doing a GC run whenever the request queue was empty; there was no downside to this.
It may be worth doing a GC run after each report is emailed, as we know this is a good time for a GC run. However if the computer had enough ram, better results would be obtained by delaying the GC run.
This behaviour was configured on a per installation bases, for some customers enabling a forced GC after each report greatly speeded up the protection of reports. (I expect this was due to low memory on their server and it running lots of other processes, so hence a well time forced GC reduced paging.)
We never detected an installation that did not benefit was a forced GC run every time the work queue was empty.
You can use -O-
(uppercase o) to redirect content to the stdout (standard output) or to a file (even special files like /dev/null
/dev/stderr
/dev/stdout
)
wget -O- http://yourdomain.com
Or:
wget -O- http://yourdomain.com > /dev/null
Or: (same result as last command)
wget -O/dev/null http://yourdomain.com
I might be wrong but "find -name __" works fine for me. (Maybe it's just my phone.) If you just want to list all files, you can try
adb shell ls -R /
You probably need the root permission though.
Edit:
As other answers suggest, use ls
with grep
like this:
adb shell ls -Ral yourDirectory | grep -i yourString
eg.
adb shell ls -Ral / | grep -i myfile
-i
is for ignore-case. and /
is the root directory.
There is a slightly simpler workaround that works with LINQ to Entities:
var result = from entry in table
where entry.something == value || (value == null && entry.something == null)
select entry;
This works becasuse, as AZ noticed, LINQ to Entities special cases x == null (i.e. an equality comparison against the null constant) and translates it to x IS NULL.
We are currently considering changing this behavior to introduce the compensating comparisons automatically if both sides of the equality are nullable. There are a couple of challenges though:
In any case, whether we get to work on this is going to depend greatly on the relative priority our customers assign to it. If you care about the issue, I encourage you to vote for it in our new Feature Suggestion site: https://data.uservoice.com.
public static LocalTime time() {
LocalTime ldt = java.time.LocalTime.now();
ldt = ldt.truncatedTo(ChronoUnit.MINUTES);
System.out.println(ldt);
return ldt;
}
This works for me
Update: 19 -11-2019
The below answer is no more relevant to present day.
So for any one looking for answers you should look at the documentation linked below
https://developer.android.com/training/articles/user-data-ids
Old Answer - Not relevant now. You check this blog in the link below
http://android-developers.blogspot.in/2011/03/identifying-app-installations.html
ANDROID_ID
import android.provider.Settings.Secure;
private String android_id = Secure.getString(getContext().getContentResolver(),
Secure.ANDROID_ID);
The above is from the link @ Is there a unique Android device ID?
More specifically, Settings.Secure.ANDROID_ID. This is a 64-bit quantity that is generated and stored when the device first boots. It is reset when the device is wiped.
ANDROID_ID seems a good choice for a unique device identifier. There are downsides: First, it is not 100% reliable on releases of Android prior to 2.2 (“Froyo”). Also, there has been at least one widely-observed bug in a popular handset from a major manufacturer, where every instance has the same ANDROID_ID.
The below solution is not a good one coz the value survives device wipes (“Factory resets”) and thus you could end up making a nasty mistake when one of your customers wipes their device and passes it on to another person.
You get the imei number of the device using the below
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.getDeviceId();
http://developer.android.com/reference/android/telephony/TelephonyManager.html#getDeviceId%28%29
Add this is manifest
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
In this course(https://www.codeschool.com/courses/shaping-up-with-angular-js) they explain how to use "this" and many other stuff.
If you add method to the controller through "this" method, you have to call it in the view with controller's name "dot" your property or method.
For example using your controller in the view you may have code like this:
<div data-ng-controller="YourController as aliasOfYourController">
Your first pane is {{aliasOfYourController.panes[0]}}
</div>
/// <summary>
/// Returns a string With count chars Left or Right value
/// </summary>
/// <param name="val"></param>
/// <param name="count"></param>
/// <param name="space"></param>
/// <param name="right"></param>
/// <returns></returns>
public static string Formating(object val, int count, char space = ' ', bool right = false)
{
var value = val.ToString();
for (int i = 0; i < count - value.Length; i++) value = right ? value + space : space + value;
return value;
}
A simple InputStream will do
byte[] fileToBytes(File file){
byte[] bytes = new byte[0];
try(FileInputStream inputStream = new FileInputStream(file)) {
bytes = new byte[inputStream.available()];
//noinspection ResultOfMethodCallIgnored
inputStream.read(bytes);
} catch (IOException e) {
e.printStackTrace();
}
return bytes;
}
Just to be different:
MOREF=$(sudo run command against $VAR1 | grep name | cut -c7-)
Here's a clean solution:
private byte[] downloadUrl(URL toDownload) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
byte[] chunk = new byte[4096];
int bytesRead;
InputStream stream = toDownload.openStream();
while ((bytesRead = stream.read(chunk)) > 0) {
outputStream.write(chunk, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
return outputStream.toByteArray();
}
in the above i need a small change which i am trying to place but i am not able to do that, your output will look like this
<ul>
<li id="menu-item-13" class="depth0 parent"><a href="#">About Us</a>
<ul class="children level-0">
<li id="menu-item-17" class="depth1"><a href="#">Sample Page</a></li>
<li id="menu-item-16" class="depth1"><a href="#">About Us</a></li>
</ul>
</li>
</ul>
what i am looking for
<ul>
<li id="menu-item-13" class="depth0"><a class="parent" href="#">About Us</a>
<ul class="children level-0">
<li id="menu-item-17" class="depth1"><a href="#">Sample Page</a></li>
<li id="menu-item-16" class="depth1"><a href="#">About Us</a></li>
</ul>
</li>
</ul>
in the above one i have placed the parent class inside the parent anchor link that <li id="menu-item-13" class="depth0"><a class="parent" href="#">About Us</a>
You don't show us the declaration of carBootSaleList
. However from the exception message I can see that it is of type CarBootSaleList
. This type doesn't implement the IEnumerable
interface and therefore cannot be used in a foreach.
Your CarBootSaleList
class should implement IEnumerable<CarBootSale>
:
public class CarBootSaleList : IEnumerable<CarBootSale>
{
private List<CarBootSale> carbootsales;
...
public IEnumerator<CarBootSale> GetEnumerator()
{
return carbootsales.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return carbootsales.GetEnumerator();
}
}
Yes you can...
PDFs have Javascript support. I needed to have auto print capabilities when a PHP-generated PDF was created and I was able to use FPDF to get it to work:
Extending @nevermind's answer, one can use DateTime::createFromFormat: like,
// use - instead of _. replace _ by - if needed.
$format = "d-m-y";
$date1 = DateTime::createFromFormat($format, date('d-m-y'));
$date2 = DateTime::createFromFormat($format, str_replace("_", "-",$date2));
var_dump($date1 > $date2);
Assuming that your implementation meaningfully supports SEEK_END:
fseek(f, 0, SEEK_END); // seek to end of file
size = ftell(f); // get current file pointer
fseek(f, 0, SEEK_SET); // seek back to beginning of file
// proceed with allocating memory and reading the file
You can use stat
(if you know the filename), or fstat
(if you have the file descriptor).
Here is an example for stat:
#include <sys/stat.h>
struct stat st;
stat(filename, &st);
size = st.st_size;
You can use GetFileSize or GetFileSizeEx.
Enabling the legacy from app.config didn't work for me. For unknown reasons, my application wasn't activating V2 runtime policy. I found a work around here.
Enabling the legacy from app.config is a recommended approach but in some cases it doesn't work as expected. Use the following code with in your main application to force Legacy V2 policy:
public static class RuntimePolicyHelper
{
public static bool LegacyV2RuntimeEnabledSuccessfully { get; private set; }
static RuntimePolicyHelper()
{
ICLRRuntimeInfo clrRuntimeInfo =
(ICLRRuntimeInfo)RuntimeEnvironment.GetRuntimeInterfaceAsObject(
Guid.Empty,
typeof(ICLRRuntimeInfo).GUID);
try
{
clrRuntimeInfo.BindAsLegacyV2Runtime();
LegacyV2RuntimeEnabledSuccessfully = true;
}
catch (COMException)
{
// This occurs with an HRESULT meaning
// "A different runtime was already bound to the legacy CLR version 2 activation policy."
LegacyV2RuntimeEnabledSuccessfully = false;
}
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("BD39D1D2-BA2F-486A-89B0-B4B0CB466891")]
private interface ICLRRuntimeInfo
{
void xGetVersionString();
void xGetRuntimeDirectory();
void xIsLoaded();
void xIsLoadable();
void xLoadErrorString();
void xLoadLibrary();
void xGetProcAddress();
void xGetInterface();
void xSetDefaultStartupFlags();
void xGetDefaultStartupFlags();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void BindAsLegacyV2Runtime();
}
}
If you want nice validation popups and images when an error occurs you can use the setError
method of the EditText
class as I describe here
A scrolling comes from a box with class pre-scrollable
<div class="pre-scrollable"></div>
There's more examples: http://getbootstrap.com/css/#code-block
Wish it helps.
I can change the rows by following the accepted answer and associated example on jsFiddle. But due to some unknown reasons, I couldn't get the ids after "stop or change" actions. But the example posted in the JQuery UI page works fine for me. You can check that link here.
Building on Luiz's answer, but satisfying the "in case of draws the item with the lowest index should be returned" condition:
from statistics import mode, StatisticsError
def most_common(l):
try:
return mode(l)
except StatisticsError as e:
# will only return the first element if no unique mode found
if 'no unique mode' in e.args[0]:
return l[0]
# this is for "StatisticsError: no mode for empty data"
# after calling mode([])
raise
Example:
>>> most_common(['a', 'b', 'b'])
'b'
>>> most_common([1, 2])
1
>>> most_common([])
StatisticsError: no mode for empty data
<TextBlock Text="Stuff on line1
Stuff on line 2"/>
You can use any hexadecimally encoded value to represent a literal. In this case, I used the line feed (char 10). If you want to do "classic" vbCrLf
, then you can use 

By the way, note the syntax: It's the ampersand, a pound, the letter x, then the hex value of the character you want, and then finally a semi-colon.
ALSO: For completeness, you can bind to a text that already has the line feeds embedded in it like a constant in your code behind, or a variable constructed at runtime.
I find that psql.exe is quite picky with the slash direction, at least on windows (which the above looks like).
Here's an example. In a cmd window:
C:\Program Files\PostgreSQL\9.2\bin>psql.exe -U postgres
psql (9.2.4)
Type "help" for help.
postgres=# \i c:\temp\try1.sql
c:: Permission denied
postgres=# \i c:/temp/try1.sql
CREATE TABLE
postgres=#
You can see it fails when I use "normal" windows slashes in a \i
call.
However both slash styles work if you pass them as input params to psql.exe
, for example:
C:\Program Files\PostgreSQL\9.2\bin>psql.exe -U postgres -f c:\TEMP\try1.sql
CREATE TABLE
C:\Program Files\PostgreSQL\9.2\bin>psql.exe -U postgres -f c:/TEMP/try1.sql
CREATE TABLE
C:\Program Files\PostgreSQL\9.2\bin>
The Philippe solution but cleaner:
My subtraction data is: '2018-09-22T11:05:00.000Z'
import datetime
import pandas as pd
df_modified = pd.to_datetime(df_reference.index.values) - datetime.datetime(2018, 9, 22, 11, 5, 0)
Python already call by ref..
let's take example:
def foo(var):
print(hex(id(var)))
x = 1 # any value
print(hex(id(x))) # I think the id() give the ref...
foo(x)
OutPut
0x50d43700 #with you might give another hex number deppend on your memory
0x50d43700
Why for
? What do you want to iterate? Try this.
call :cpy pc-name-1
call :cpy pc-name-2
...
:cpy
net use \\%1\{destfolder} {password} /user:{username}
copy {file} \\%1\{destfolder}
goto :EOF
When the user enters his/her username
, check for valid entry also.
java.util.Scanner input = new java.util.Scanner(System.in);
String userName;
final int validLength = 6; // This is the valid length of an user name
System.out.print("Please enter the username: ");
userName = input.nextLine();
while(userName.length() < validLength) {
// If the user enters less than validLength characters
// ask for entering again
System.out.println(
"\nUsername needs to be " + validLength + " character long");
System.out.print("\nPlease enter the username again: ");
userName = input.nextLine();
}
System.out.println("Username is: " + userName);
var arrayCount = [1,2,3,2,5,6,2,8];_x000D_
var co = 0;_x000D_
function findElement(){_x000D_
arrayCount.find(function(value, index) {_x000D_
if(value == 2)_x000D_
co++;_x000D_
});_x000D_
console.log( 'found' + ' ' + co + ' element with value 2');_x000D_
}
_x000D_
I would do something like that:
var arrayCount = [1,2,3,4,5,6,7,8];_x000D_
_x000D_
function countarr(){_x000D_
var dd = 0;_x000D_
arrayCount.forEach( function(s){_x000D_
dd++;_x000D_
});_x000D_
_x000D_
console.log(dd);_x000D_
}
_x000D_
Corresponding to INSERT (Transact-SQL) (SQL Server 2005) you can't omit INSERT INTO dbo.Blah
and have to specify it every time or use another syntax/approach,
Grep has an option called Context Line Control
, you can use the --context
in that, simply,
| grep -C 5
or
| grep -5
Should do the trick
display:inline;
OR
float:left;
OR
display:inline-block;
-- Might not work on all browsers.
What is the purpose of using a div
here? I'd suggest a span
, as it is an inline-level element, whereas a div
is a block-level element.
Do note that each option above will work differently.
display:inline;
will turn the div
into the equivalent of a span
. It will be unaffected by margin-top
, margin-bottom
, padding-top
, padding-bottom
, height
, etc.
float:left;
keeps the div
as a block-level element. It will still take up space as if it were a block, however the width will be fitted to the content (assuming width:auto;
). It can require a clear:left;
for certain effects.
display:inline-block;
is the "best of both worlds" option. The div
is treated as a block element. It responds to all of the margin
, padding
, and height
rules as expected for a block element. However, it is treated as an inline element for the purpose of placement within other elements.
Read this for more information.
It is similar to your table
<table border=1 width=50%>
<tr>
<td rowspan="2">x</td>
<td colspan="4">y</td>
</tr>
<tr>
<td bgcolor=#FFFF00 >I</td>
<td>II</td>
<td bgcolor=#FFFF00>III</td>
<td>IV</td>
</tr>
<tr>
<td>empty</td>
<td bgcolor=#FFFF00>1</td>
<td>2</td>
<td bgcolor=#FFFF00>3</td>
<td>4</td>
</tr>
Update: I noticed that my answer was just a poor duplicate of a well explained question on https://unix.stackexchange.com/... by BryKKan
Here is an extract from it:
openssl pkcs12 -in <filename.pfx> -nocerts -nodes | sed -ne '/-BEGIN PRIVATE KEY-/,/-END PRIVATE KEY-/p' > <clientcert.key>
openssl pkcs12 -in <filename.pfx> -clcerts -nokeys | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > <clientcert.cer>
openssl pkcs12 -in <filename.pfx> -cacerts -nokeys -chain | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > <cacerts.cer>
Use .find()
method
$(t).find("td:eq(1)");
td:eq(x) // x is index of child you want to retrieve. eq(1) means equal to 1.
//1 denote second element
I know I am replying too late but for anyone else who needs this, run following command from your local machine
cat ~/.ssh/id_rsa.pub | ssh [email protected] "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"
this has worked perfectly fine. All you need to do is just to replace
with your own user for that particular host
$adsi = [ADSI]"WinNT://$env:COMPUTERNAME"
$adsi.Children | where {$_.SchemaClassName -eq 'user'} | Foreach-Object {
$groups = $_.Groups() | Foreach-Object {$_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)}
$_ | Select-Object @{n='UserName';e={$_.Name}},@{n='Groups';e={$groups -join ';'}}
}
You can either do 1 of the following:
Change:
SET @UserId
= 0 to SELECT @UserId
This will return the value in the same way your 2nd part of the IF statement is.
Or, seeing as @UserId is set as an Output, change:
SELECT SCOPE_IDENTITY()
to SET @UserId = SCOPE_IDENTITY()
It depends on how you want to access the data afterwards. If you want the value to be in your result set, use SELECT
. If you want to access the new value of the @UserId parameter afterwards, then use SET @UserId
Seeing as you're accepting the 2nd condition as correct, the query you could write (without having to change anything outside of this query) is:
@EmailAddress varchar(200),
@NickName varchar(100),
@Password varchar(150),
@Sex varchar(50),
@Age int,
@EmailUpdates int,
@UserId int OUTPUT
IF
(SELECT COUNT(UserId) FROM RegUsers WHERE EmailAddress = @EmailAddress) > 0
BEGIN
SELECT 0
END
ELSE
BEGIN
INSERT INTO RegUsers (EmailAddress,NickName,PassWord,Sex,Age,EmailUpdates) VALUES (@EmailAddress,@NickName,@Password,@Sex,@Age,@EmailUpdates)
SELECT SCOPE_IDENTITY()
END
END
I think you need to use Expr
with ->set()
(However THIS IS NOT SAFE and you shouldn't do it):
$qb = $this->em->createQueryBuilder();
$q = $qb->update('models\User', 'u')
->set('u.username', $qb->expr()->literal($username))
->set('u.email', $qb->expr()->literal($email))
->where('u.id = ?1')
->setParameter(1, $editId)
->getQuery();
$p = $q->execute();
It's much safer to make all your values parameters instead:
$qb = $this->em->createQueryBuilder();
$q = $qb->update('models\User', 'u')
->set('u.username', '?1')
->set('u.email', '?2')
->where('u.id = ?3')
->setParameter(1, $username)
->setParameter(2, $email)
->setParameter(3, $editId)
->getQuery();
$p = $q->execute();
Answers here tell you how to achieve multiline button title programmatically.
I just wanted to add that if you are using storyboards, you can type [Ctrl+Enter] to force a newline on a button title field.
HTH
Use this easy method
$a='Link1';
$b='Link2';
echo "<a href=\"pass.php?link=$a\">Link 1</a>";
echo '<br/>';
echo "<a href=\"pass.php?link=$b\">Link 2</a>";
I have written a very simple tool that does exactly that - it's called PE Deconstructor.
Simply fire it up and load your DLL file:
In the example above, the loaded DLL is 32-bit.
You can download it here (I only have the 64-bit version compiled ATM):
http://files.quickmediasolutions.com/exe/pedeconstructor_0.1_amd64.exe
An older 32-bit version is available here:
http://dl.dropbox.com/u/31080052/pedeconstructor.zip
I really wanted to avoid hard resets, this is what I came up with.
A -> B -> C -> D -> HEAD
To go back to A (which is 4 steps back):
git pull # Get latest changes
git reset --soft HEAD~4 # Set back 4 steps
git stash # Stash the reset
git pull # Go back to head
git stash pop # Pop the reset
git commit -m "Revert" # Commit the changes
SCAN doesn't require the client to load all the keys into memory like KEYS does. SCAN gives you an iterator you can use. I had a 1B records in my redis and I could never get enough memory to return all the keys at once.
Here is a python snippet to get all keys from the store matching a pattern and delete them:
import redis
r = redis.StrictRedis(host='localhost', port=6379, db=0)
for key in r.scan_iter("key_pattern*"):
print key
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
//to prevent double click
button.setOnClickListener(null);
}
});
If you want to use location.href
to avoid popup problems, you can use an empty <a>
ref and then use javascript to click it.
something like in HTML
<a id="anchorID" href="mynewurl" target="_blank"></a>
Then javascript click it as follows
document.getElementById("anchorID").click();
Python IndentationError unindent does not match any outer indentation level
# usr/bin/bash -tt
or
# usr/bin/python -tt
I think you need str.contains
, if you need rows where values of column date
contains string 07311954
:
print df[df['date'].astype(str).str.contains('07311954')]
Or if type
of date
column is string
:
print df[df['date'].str.contains('07311954')]
If you want check last 4 digits for string
1954
in column date
:
print df[df['date'].astype(str).str[-4:].str.contains('1954')]
Sample:
print df['date']
0 8152007
1 9262007
2 7311954
3 2252011
4 2012011
5 2012011
6 2222011
7 2282011
Name: date, dtype: int64
print df['date'].astype(str).str[-4:].str.contains('1954')
0 False
1 False
2 True
3 False
4 False
5 False
6 False
7 False
Name: date, dtype: bool
print df[df['date'].astype(str).str[-4:].str.contains('1954')]
cmte_id trans_typ entity_typ state employer occupation date \
2 C00119040 24K CCM MD NaN NaN 7311954
amount fec_id cand_id
2 1000 C00140715 H2MD05155
Appears to have moved again in the latest version of GH for windows to:
%USERPROFILE%\AppData\Local\GitHubDesktop\app-[gfw-version]\resources\app\git\cmd\git.exe
Given it now has the version in the folder structure i think it will move every time it auto-updates. This makes it impossible to put into path. I think the best option is to install git separately.
You can do smth like this for 1D arrays. Here we use int*& because we want our pointer to be changeable.
#include<algorithm> // for copy
void resize(int*& a, size_t& n)
{
size_t new_n = 2 * n;
int* new_a = new int[new_n];
copy(a, a + n, new_a);
delete[] a;
a = new_a;
n = new_n;
}
For 2D arrays:
#include<algorithm> // for copy
void resize(int**& a, size_t& n)
{
size_t new_n = 2 * n, i = 0;
int** new_a = new int* [new_n];
for (i = 0; i != new_n; ++i)
new_a[i] = new int[100];
for (i = 0; i != n; ++i)
{
copy(a[i], a[i] + 100, new_a[i]);
delete[] a[i];
}
delete[] a;
a = new_a;
n = new_n;
}
Invoking of 1D array:
void myfn(int*& a, size_t& n)
{
// do smth
resize(a, n);
}
Invoking of 2D array:
void myfn(int**& a, size_t& n)
{
// do smth
resize(a, n);
}
The VCS files can have its information coded in Quoted printable which is a nightmare. The above solution recommending "VCS to ICS Calendar Converter" is the way to go.
function getIndexByAttribute(list, attr, val){
var result = null;
$.each(list, function(index, item){
if(item[attr].toString() == val.toString()){
result = index;
return false; // breaks the $.each() loop
}
});
return result;
}
Here is another way without extra modules:
I needed to guess the environment from the task name, I have a 'dev' task and a 'prod' task.
When I run gulp prod
it should be set to prod environment.
When I run gulp dev
or anything else it should be set to dev environment.
For that I just check the running task name:
devEnv = process.argv[process.argv.length-1] !== 'prod';
This will do the trick :-
new Date().valueOf()
In my case, I have Java 14 and need Java 8.
I'm in a Arch Linux and has installed jdk8-openjdk jre8-openjdk
https://www.archlinux.org/packages/extra/x86_64/java8-openjdk/
For Debian users https://wiki.debian.org/Java, or Fedora https://docs.fedoraproject.org/en-US/quick-docs/installing-java/.
Install Java 8 (or desired version, in this case jdk8-openjdk jre8-openjdk
) using your package manager before doing the following steps.
# which java
/usr/bin/java
I can see all java files here are links to /usr/lib/jvm/default[something]
. This means that the java
command is linked to some specific version of java
executable.
# ls -l /usr/bin/java*
lrwxrwxrwx 1 root root 37 May 16 06:30 /usr/bin/java -> /usr/lib/jvm/default-runtime/bin/java
lrwxrwxrwx 1 root root 30 May 16 06:30 /usr/bin/javac -> /usr/lib/jvm/default/bin/javac
lrwxrwxrwx 1 root root 32 May 16 06:30 /usr/bin/javadoc -> /usr/lib/jvm/default/bin/javadoc
lrwxrwxrwx 1 root root 30 May 16 06:30 /usr/bin/javah -> /usr/lib/jvm/default/bin/javah
lrwxrwxrwx 1 root root 30 May 16 06:30 /usr/bin/javap -> /usr/lib/jvm/default/bin/javap
default
and default-runtime
Here I could see the default version was linked to 14 (unique installed version).
# cd /usr/lib/jvm
# ls -l
lrwxrwxrwx 1 root root 14 Aug 8 20:44 default -> java-14-openjdk
lrwxrwxrwx 1 root root 14 Aug 8 20:44 default-runtime -> java-14-openjdk
drwxr-xr-x 7 root root 4096 Jul 19 22:38 java-14-openjdk
drwxr-xr-x 6 root root 4096 Aug 8 20:42 java-8-openjdk
First, remove the existing default
and default-runtime
which linked to java-14 version.
# rm default default-runtime
Then, create new links to the desired version (in this case, java-8).
# link -s java-8-openjdk default
# link -s java-8-openjdk default-runtime
The strategy is to make links to the desired version of software (java8 in this case) using ln -s
above. Then, this links are linked to the binaries inside the java bin directory (without changing the $PATH
environment variable!)
Or you might be wanted to change the Java version using archlinux-java
command instead with more safely approach: https://wiki.archlinux.org/index.php/Java
You can use a tool I wrote that bypasses the limit.
It saves the Tweets in a JSON format.
It depends on what runs cron on your system, but all you have to do to run a php script from cron is to do call the location of the php installation followed by the script location. An example with crontab running every hour:
# crontab -e
00 * * * * /usr/local/bin/php /home/path/script.php
On my system, I don't even have to put the path to the php installation:
00 * * * * php /home/path/script.php
On another note, you should not be using mysql extension because it is deprecated, unless you are using an older installation of php. Read here for a comparison.
If you need access to the index as you iterate through the string, use enumerate()
:
>>> for i, c in enumerate('test'):
... print i, c
...
0 t
1 e
2 s
3 t
Generically, do
/while
is good for any sort of loop construct where one must execute the loop at least once. It is possible to emulate this sort of looping through either a straight while
or even a for
loop, but often the result is a little less elegant. I'll admit that specific applications of this pattern are fairly rare, but they do exist. One which springs to mind is a menu-based console application:
do {
char c = read_input();
process_input(c);
} while (c != 'Q');
this works for me, sudo apt-get install libx11-dev
List<"classname"> getreport = cs.getcompletionreport();
var getreported = getreport.Select(c => new { demographic = c.rName);
where cs.getcompletionreport()
reference class file is Business Layer for App
I hope this helps.
requests
has built-in .json()
method
import requests
requests.get(url).json()
Depending on if you want it to automatically update or not, you can just save the excel spreadsheet as a PDF then embed the PDF as an object -
It appears you don't have a PDF plugin for this browser, but you can click here to download the PDF file.
It's the best way I have found for uploading.
How about something like this.
function objectToArray( $object ){
if( !is_object( $object ) && !is_array( $object ) ){
return $object;
}
if( is_object( $object ) ){
$object = get_object_vars( $object );
}
return array_map( 'objectToArray', $object );
}
and call this function with your object
$array = objectToArray( $yourObject );
if still not working for you then just close all of your command prompts and then again open and run mongo, mongoimport, mongodb from anywhere it ll work because after setting the path variable command prompt should be restarted.
I think this is the most widely supported version (requiring only POSIX defined tr
and od
behavior):
cat "$file" | od -v -t x1 -A n | tr -d ' \n'
This uses od
to print each byte as hex without address without skipping repeated bytes and tr
to delete all spaces and linefeeds in the output. Note that not even the trailing linefeed is emitted here. (The cat
is intentional to allow multicore processing where cat
can wait for filesystem while od
is still processing previously read part. Single core users may want replace that with < "$file" od ...
to save starting one additional process.)
You should do
alert(data[0].name); //Take the property name of the first array
and not
alert(data.myName)
jQuery should be able to sniff the dataType for you even if you don't set it so no need for JSON.parse.
fiddle here
I noticed something else about your coding.... look
INSERT INTO reports_services (id,title,description,cost) VALUES (0, 'test title', 'test decription ', '3.80')
in your "CREATE TABLE" code you have the id set to "AUTO_INCREMENT" which means it's automatically generating a result for that field.... but in your above code you include it as one of the insertions and in the "VALUES" you have a 0 there... idk if that's your way of telling us you left it blank because it's set to AUTO_INC. or if that's the actual code you have... if it's the code you have not only should you not be trying to send data to a field set to generate it automatically, but the RIGHT WAY to do it WRONG would be
'0',
you put
0,
lol....so that might be causing some of the problem... I also just noticed in the code after "test description" you have a space before the '.... that might be throwing something off too.... idk.. I hope this helps n maybe resolves some other problem you might be pulling your hair out about now.... speaking of which.... I need to figure out my problem before I tear all my hair out..... good luck.. :)
UPDATE.....
I almost forgot... if you have the 0 there to show that it's blank... you could be entering "test title" as the id and "test description" as the title then "3.whatever cents" for the description leaving "cost" empty...... which could be why it maxed out because if I'm not mistaking you have it set to NOT NULL.... and you left it null... so it forced something... maybe.... lol
This version displays the schema, the table name and an ordered, comma separated list of primary keys. Object_Id() does not work for link servers so we filter by the table name.
Without the REPLACE(Si1.Column_Name, '', '') it would show the xml opening and closing tags for Column_Name on the database I was testing on. I am not sure why the database required a replace for 'Column_Name' so if someone knows then please comment.
DECLARE @TableName VARCHAR(100) = '';
WITH Sysinfo
AS (SELECT Kcu.Table_Name
, Kcu.Table_Schema AS Schema_Name
, Kcu.Column_Name
, Kcu.Ordinal_Position
FROM [LinkServer].Information_Schema.Key_Column_Usage Kcu
JOIN [LinkServer].Information_Schema.Table_Constraints AS Tc ON Tc.Constraint_Name = Kcu.Constraint_Name
WHERE Tc.Constraint_Type = 'Primary Key')
SELECT Schema_Name
,Table_Name
, STUFF(
(
SELECT ', '
, REPLACE(Si1.Column_Name, '', '')
FROM Sysinfo Si1
WHERE Si1.Table_Name = Si2.Table_Name
ORDER BY Si1.Table_Name
, Si1.Ordinal_Position
FOR XML PATH('')
), 1, 2, '') AS Primary_Keys
FROM Sysinfo Si2
WHERE Table_Name = CASE
WHEN @TableName NOT IN( '', 'All')
THEN @TableName
ELSE Table_Name
END
GROUP BY Si2.Table_Name, Si2.Schema_Name;
And the same pattern using George's query:
DECLARE @TableName VARCHAR(100) = '';
WITH Sysinfo
AS (SELECT S.Name AS Schema_Name
, T.Name AS Table_Name
, Tc.Name AS Column_Name
, Ic.Key_Ordinal AS Ordinal_Position
FROM [LinkServer].Sys.Schemas S
JOIN [LinkServer].Sys.Tables T ON S.Schema_Id = T.Schema_Id
JOIN [LinkServer].Sys.Indexes I ON T.Object_Id = I.Object_Id
JOIN [LinkServer].Sys.Index_Columns Ic ON I.Object_Id = Ic.Object_Id
AND I.Index_Id = Ic.Index_Id
JOIN [LinkServer].Sys.Columns Tc ON Ic.Object_Id = Tc.Object_Id
AND Ic.Column_Id = Tc.Column_Id
WHERE I.Is_Primary_Key = 1)
SELECT Schema_Name
,Table_Name
, STUFF(
(
SELECT ', '
, REPLACE(Si1.Column_Name, '', '')
FROM Sysinfo Si1
WHERE Si1.Table_Name = Si2.Table_Name
ORDER BY Si1.Table_Name
, Si1.Ordinal_Position
FOR XML PATH('')
), 1, 2, '') AS Primary_Keys
FROM Sysinfo Si2
WHERE Table_Name = CASE
WHEN @TableName NOT IN('', 'All')
THEN @TableName
ELSE Table_Name
END
GROUP BY Si2.Table_Name, Si2.Schema_Name;
I had the same problem, my database log file size was about 39 gigabyte, and after shrinking (both database and files) it reduced to 37 gigabyte that was not enough, so I did this solution: (I did not need the ldf file (log file) anymore)
(**Important) : Get a full backup of your database before the process.
Run "checkpoint" on that database.
Detach that database (right click on the database and chose tasks >> Detach...) {if you see an error, do the steps in the end of this text}
Move MyDatabase.ldf to another folder, you can find it in your hard disk in the same folder as your database (Just in case you need it in the future for some reason such as what user did some task).
Attach the database (right click on Databases and chose Attach...)
On attach dialog remove the .ldf file (which shows 'file not found' comment) and click Ok. (don`t worry the ldf file will be created after the attachment process.)
After that, a new log file create with a size of 504 KB!!!.
In step 2, if you faced an error that database is used by another user, you can:
1.run this command on master database "sp_who2" and see what process using your database.
2.read the process number, for example it is 52 and type "kill 52", now your database is free and ready to detach.
If the number of processes using your database is too much:
1.Open services (type services in windows start) find SQL Server ... process and reset it (right click and chose reset).
You need to add query.addEntity(SwitcherServiceSource.class) before calling the .list() on query.
Following script will help you out
for file in *.jar
do
# do something on "$file"
echo "$file"
/usr/local/jdk/bin/jar -tvf "$file" | grep '$CLASSNAME'
done
lable value $('#lablel_id').html(value);
If you want to do this in jQuery instead of CSS, you basically follow the same process.
Assuming you have some <div id="target"></div>
, you can use the following code:
$("#target").hover(function() {
$(this).css('cursor','pointer');
}, function() {
$(this).css('cursor','auto');
});
and that should do it.
I've found that the solution the works best for me is to just perform the merge and abort it if there are conflicts. This particular syntax feels clean and simple to me. This is Strategy 2 below.
However, if you want to ensure you don't mess up your current branch, or you're just not ready to merge regardless of the existence of conflicts, simply create a new sub-branch off of it and merge that:
git checkout mybranch
git checkout -b mynew-temporary-branch
git merge some-other-branch
That way you can simply throw away the temporary branch if you just want to see what the conflicts are. You don't need to bother "aborting" the merge, and you can go back to your work -- simply checkout 'mybranch' again and you won't have any merged code or merge conflicts in your branch.
This is basically a dry-run.
git checkout mybranch
git merge some-other-branch
If git reports conflicts (and ONLY IF THERE ARE conflicts) you can then do:
git merge --abort
If the merge is successful, you cannot abort it (only reset).
If you're not ready to merge, use the safer way above.
[EDIT: 2016-Nov - I swapped strategy 1 for 2, because it seems to be that most people are looking for "the safe way". Strategy 2 is now more of a note that you can simply abort the merge if the merge has conflicts that you're not ready to deal with. Keep in mind if reading comments!]
let nietos = [];
function nieto(aData) {
let o = {};
for ( let i = 0; i < aData.length; i++ ) {
let key = "0" + (i + 1);
o[key] = aData[i];
}
nietos.push(o);
}
nieto( ["Band", "Ramones"] );
nieto( ["Style", "RockPunk"] );
nieto( ["", "", "", "Another String"] );
/* convert array of object into string json */
var jsonString = JSON.stringify(nietos);
document.write(jsonString);
_x000D_
You can also use the non-standard IE-only css attribute writing-mode
div.page {
writing-mode: tb-rl;
}
I like Tom Faust's answer the best. Here's a C# version of his solution, but simplifying things a bit.
var codecs = ImageCodecInfo.GetImageEncoders();
var codecFilter = "Image Files|";
foreach (var codec in codecs)
{
codecFilter += codec.FilenameExtension + ";";
}
dialog.Filter = codecFilter;
Sorry to post answer for very old thread. my answer may help other in future.
string[] TobeDistinct = {"Name","City","State"};
DataTable dtDistinct = GetDistinctRecords(DTwithDuplicate, TobeDistinct);
//Following function will return Distinct records for Name, City and State column.
public static DataTable GetDistinctRecords(DataTable dt, string[] Columns)
{
DataTable dtUniqRecords = new DataTable();
dtUniqRecords = dt.DefaultView.ToTable(true, Columns);
return dtUniqRecords;
}
Following worked for me..
for a table say, 'test_update_cmd', source value column col2, target value column col1 and condition column col3: -
UPDATE test_update_cmd SET col1=col2 WHERE col3='value';
Good Luck!
With version 3 of the Google Maps API, the easiest way to do this may be by grabbing a custom icon set, like the one that Benjamin Keen has created here:
http://www.benjaminkeen.com/?p=105
If you put all of those icons at the same place as your map page, you can colorize a Marker simply by using the appropriate icon option when creating it:
var beachMarker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: 'brown_markerA.png'
});
This is super-easy, and is the approach I'm using for the project I'm working on currently.
Use Assembly.GetTypes
. For example:
Assembly mscorlib = typeof(string).Assembly;
foreach (Type type in mscorlib.GetTypes())
{
Console.WriteLine(type.FullName);
}
On Ubuntu :
Try
$ cat /usr/local/cuda/version.txt
or
$ cat /usr/local/cuda-8.0/version.txt
Sometimes the folder is named "Cuda-version".
If none of above works, try going to
$ /usr/local/
And find the correct name of your Cuda folder.
Output should be similar to:
CUDA Version 8.0.61
Try this query.. It uses the Analytic function SUM:
SELECT * FROM
(
SELECT SUM(1) OVER(PARTITION BY ctn_no) cnt, A.*
FROM table1 a
WHERE s_ind ='Y'
)
WHERE cnt > 2
Am not sure why you are identifying a record as a duplicate if the ctn_no repeats more than 2 times. FOr me it repeats more than once it is a duplicate. In this case change the las part of the query to WHERE cnt > 1
You would need also to import the HttpClientModule
from Angular '@angular/common/http'
into your main AppModule for making HTTP requests.
app.module.ts
import { HttpClientModule } from '@angular/common/http';
import { ServiceService } from '../../../services/service.service';
@NgModule({
imports: [
HttpClientModule
],
providers: [
ServiceService
]
})
export class AppModule {...}
Try something like this:
awk -vc=1 'NR%1000000==0{++c}{print $0 > c".txt"}' Datafile.txt
for filename in *.txt; do mv "$filename" "Prefix_$filename"; done;
No it doesn't wait and the way you are doing it in that sample is not good practice.
dispatch_async
is always asynchronous. It's just that you are enqueueing all the UI blocks to the same queue so the different blocks will run in sequence but parallel with your data processing code.
If you want the update to wait you can use dispatch_sync
instead.
// This will wait to finish
dispatch_sync(dispatch_get_main_queue(), ^{
// Update the UI on the main thread.
});
Another approach would be to nest enqueueing the block. I wouldn't recommend it for multiple levels though.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Background work
dispatch_async(dispatch_get_main_queue(), ^{
// Update UI
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Background work
dispatch_async(dispatch_get_main_queue(), ^{
// Update UI
});
});
});
});
If you need the UI updated to wait then you should use the synchronous versions. It's quite okay to have a background thread wait for the main thread. UI updates should be very quick.
I have used
str.replace("'", "");
to replace the single quote in my string. Its working fine for me.
The app is stored in %LocalAppData%
in your %UserProfile%
. So the full path could be:
C:\Users\username\AppData\Local\GitHub
If they are .NET created services you can use the installutil.exe with the /u switch its in the .net framework folder like C:\Windows\Microsoft.NET\Framework64\v2.0.50727
I was getting this error and just could not see where the problem was. I double checked all of my aliases and syntax and nothing looked out of place. The query was similar to ones I write all the time.
I decided to just re-write the query (I originally had copied it from a report .rdl file) below, over again, and it ran fine. Looking at the queries now, they look the same to me, but my re-written one works.
Just wanted to say that it might be worth a shot if nothing else works.
Code counts the unique/distinct combination of Tag & Entry ID when [Entry Id]>0
select count(distinct(concat(tag,entryId)))
from customers
where id>0
In the output it will display the count of unique values Hope this helps
If your vector look like this std::vector<MyClass*> vecType_pt
you have to explicitly release memory ,Or if your vector look like : std::vector<MyClass> vecType_obj
, constructor will be called by vector.Please execute example given below , and understand the difference :
class MyClass
{
public:
MyClass()
{
cout<<"MyClass"<<endl;
}
~MyClass()
{
cout<<"~MyClass"<<endl;
}
};
int main()
{
typedef std::vector<MyClass*> vecType_ptr;
typedef std::vector<MyClass> vecType_obj;
vecType_ptr myVec_ptr;
vecType_obj myVec_obj;
MyClass obj;
for(int i=0;i<5;i++)
{
MyClass *ptr=new MyClass();
myVec_ptr.push_back(ptr);
myVec_obj.push_back(obj);
}
cout<<"\n\n---------------------If pointer stored---------------------"<<endl;
myVec_ptr.erase (myVec_ptr.begin(),myVec_ptr.end());
cout<<"\n\n---------------------If object stored---------------------"<<endl;
myVec_obj.erase (myVec_obj.begin(),myVec_obj.end());
return 0;
}
I have used below code in my SpringBoot application.
MimeMessage message = sender.createMimeMessage();
message.setContent(message, "text/html");
MimeMessageHelper helper = new MimeMessageHelper(message);
helper.setFrom(fromAddress);
helper.setTo(toAddress);
helper.setSubject(mailSubject);
helper.setText(mailText, true);
sender.send(message);
- Where does
user.id
go afterpassport.serializeUser
has been called?
The user id (you provide as the second argument of the done
function) is saved in the session and is later used to retrieve the whole object via the deserializeUser
function.
serializeUser
determines which data of the user object should be stored in the session. The result of the serializeUser method is attached to the session as req.session.passport.user = {}
. Here for instance, it would be (as we provide the user id as the key) req.session.passport.user = {id: 'xyz'}
- We are calling
passport.deserializeUser
right after it where does it fit in the workflow?
The first argument of deserializeUser
corresponds to the key of the user object that was given to the done
function (see 1.). So your whole object is retrieved with help of that key. That key here is the user id (key can be any key of the user object i.e. name,email etc).
In deserializeUser
that key is matched with the in memory array / database or any data resource.
The fetched object is attached to the request object as req.user
Visual Flow
passport.serializeUser(function(user, done) {
done(null, user.id);
}); ¦
¦
¦
+--------------------? saved to session
¦ req.session.passport.user = {id: '..'}
¦
?
passport.deserializeUser(function(id, done) {
+---------------+
¦
?
User.findById(id, function(err, user) {
done(err, user);
}); +--------------? user object attaches to the request as req.user
});
Try LINQPad, it works for SQL Server, MySQL, SQLite and also SDF (SQL CE 4.0). Best of all it's free!
Steps with version 4.35.1:
click 'Add Connection'
Click Next with 'Build data context automatically' and 'Default(LINQ to SQL)' selected.
Under 'Provider' choose 'SQL CE 4.0'.
Under 'Database' with 'Attach database file' selected, choose 'Browse' to select your .sdf file.
Click 'OK'.
Voila! It should show the tables in .sdf and be able to query it via right clicking the table or writing LINQ code in your favorite .NET language or even SQL. How cool is that?
Actually the coded modules and the Global.asax examples shown above only work for valid requests.
For example, add < on the end of your URL and you will get a "Bad request" page which still exposes the server header. A lot of developers overlook this.
The registry settings shown do not work either. URLScan is the ONLY way to remove the "server" header (at least in IIS 7.5).
There is one more way, i got the same situation in my project. i solved this way
List<Object[]> list = HQL.list();
In above hibernate query language i know at which place what are my objects so what i did is :
for(Object[] obj : list){
String val = String.valueOf(obj[1]);
int code =Integer.parseint(String.valueof(obj[0]));
}
this way you can get the mixed objects with ease, but you should know in advance at which place what value you are getting or you can just check by printing the values to know. sorry for the bad english I hope this help
You can use updateMany()
methods of mongodb to update multiple document
Simple query is like this
db.collection.updateMany(filter, update, options)
For more doc of uppdateMany read here
As per your requirement the update code will be like this:
User.updateMany({"created": false}, {"$set":{"created": true}});
here you need to use $set because you just want to change created from true to false. For ref. If you want to change entire doc then you don't need to use $set
Variables in Javascript don't have a type. Non-zero, non-null, non-empty and true
are "true". Zero, null, undefined, empty string and false
are "false".
There's a Boolean type though, as are literals true
and false
.
The way to reinstall Homebrew is completely remove it and start over. The Homebrew FAQ has a link to a shell script to uninstall homebrew.
If the only thing you've installed in /usr/local
is homebrew itself, you can just rm -rf /usr/local/* /usr/local/.git
to clear it out. But /usr/local/
is the standard Unix directory for all extra binaries, not just Homebrew, so you may have other things installed there. In that case uninstall_homebrew.sh
is a better bet. It is careful to only remove homebrew's files and leave the rest alone.
A new operator is currently being added to the browsers, ??=
. This combines the null coalescing operator ??
with the assignment operator =
.
NOTE: This is not common in public browser versions yet. Will update as availability changes.
??=
checks if the variable is undefined or null, short-circuiting if already defined. If not, the right-side value is assigned to the variable.
let a // undefined
let b = null
let c = false
a ??= true // true
b ??= true // true
c ??= true // false
let x = ["foo"]
let y = { foo: "fizz" }
x[0] ??= "bar" // "foo"
x[1] ??= "bar" // "bar"
y.foo ??= "buzz" // "fizz"
y.bar ??= "buzz" // "buzz"
x // Array [ "foo", "bar" ]
y // Object { foo: "fizz", bar: "buzz" }
Browser Support Sept 2020 - 3.7%
Why dont you take the string and split it
Example on the url
var url = "http://www.youtube.com/watch?p=DB852818BF378DAC&v=1q-k-uN73Gk"
you can do a split as
var params = url.split("?")[1].split("&");
You will get array of strings with params as name value pairs with "=" as the delimiter.
You can select the "Runnable JAR File" after you click on "Export".
You can specify your main driver in "Launch Configuration"
I could be wrong because I've never used Angular, but I believe you are probably using ng-bind
, which will create just a TextNode.
You will want to use ng-bind-html
instead.
http://docs.angularjs.org/api/ngSanitize.directive:ngBindHtml
Update: It looks like you'll need to use ng-bind-html-unsafe='q.category'
http://docs.angularjs.org/api/ng.directive:ngBindHtmlUnsafe
Here's a demo:
You cannot directly save a Python file as an exe and expect it to work -- the computer cannot automatically understand whatever code you happened to type in a text file. Instead, you need to use another program to transform your Python code into an exe.
I recommend using a program like Pyinstaller. It essentially takes the Python interpreter and bundles it with your script to turn it into a standalone exe that can be run on arbitrary computers that don't have Python installed (typically Windows computers, since Linux tends to come pre-installed with Python).
To install it, you can either download it from the linked website or use the command:
pip install pyinstaller
...from the command line. Then, for the most part, you simply navigate to the folder containing your source code via the command line and run:
pyinstaller myscript.py
You can find more information about how to use Pyinstaller and customize the build process via the documentation.
You don't necessarily have to use Pyinstaller, though. Here's a comparison of different programs that can be used to turn your Python code into an executable.
You're interested in the collation. You could build something based on this snippet:
SELECT DATABASEPROPERTYEX('master', 'Collation');
Update
Based on your edit — If @test
and @TEST
can ever refer to two different variables, it's not SQL Server. If you see problems where the same variable is not equal to itself, check if that variable is NULL
, because NULL = NULL
returns `false.
df = pd.DataFrame({'$a': [1], '$b': [1], '$c': [1], '$d': [1], '$e': [1]})
If your new list of columns is in the same order as the existing columns, the assignment is simple:
new_cols = ['a', 'b', 'c', 'd', 'e']
df.columns = new_cols
>>> df
a b c d e
0 1 1 1 1 1
If you had a dictionary keyed on old column names to new column names, you could do the following:
d = {'$a': 'a', '$b': 'b', '$c': 'c', '$d': 'd', '$e': 'e'}
df.columns = df.columns.map(lambda col: d[col]) # Or `.map(d.get)` as pointed out by @PiRSquared.
>>> df
a b c d e
0 1 1 1 1 1
If you don't have a list or dictionary mapping, you could strip the leading $
symbol via a list comprehension:
df.columns = [col[1:] if col[0] == '$' else col for col in df]
if cacert.pem from above links doesn't working try this one worked for me
If you define operator<<
as a member function it will have a different decomposed syntax than if you used a non-member operator<<
. A non-member operator<<
is a binary operator, where a member operator<<
is a unary operator.
// Declarations
struct MyObj;
std::ostream& operator<<(std::ostream& os, const MyObj& myObj);
struct MyObj
{
// This is a member unary-operator, hence one argument
MyObj& operator<<(std::ostream& os) { os << *this; return *this; }
int value = 8;
};
// This is a non-member binary-operator, 2 arguments
std::ostream& operator<<(std::ostream& os, const MyObj& myObj)
{
return os << myObj.value;
}
So.... how do you really call them? Operators are odd in some ways, I'll challenge you to write the operator<<(...)
syntax in your head to make things make sense.
MyObj mo;
// Calling the unary operator
mo << std::cout;
// which decomposes to...
mo.operator<<(std::cout);
Or you could attempt to call the non-member binary operator:
MyObj mo;
// Calling the binary operator
std::cout << mo;
// which decomposes to...
operator<<(std::cout, mo);
You have no obligation to make these operators behave intuitively when you make them into member functions, you could define operator<<(int)
to left shift some member variable if you wanted to, understand that people may be a bit caught off guard, no matter how many comments you may write.
Almost lastly, there may be times where both decompositions for an operator call are valid, you may get into trouble here and we'll defer that conversation.
Lastly, note how odd it might be to write a unary member operator that is supposed to look like a binary operator (as you can make member operators virtual..... also attempting to not devolve and run down this path....)
struct MyObj
{
// Note that we now return the ostream
std::ostream& operator<<(std::ostream& os) { os << *this; return os; }
int value = 8;
};
This syntax will irritate many coders now....
MyObj mo;
mo << std::cout << "Words words words";
// this decomposes to...
mo.operator<<(std::cout) << "Words words words";
// ... or even further ...
operator<<(mo.operator<<(std::cout), "Words words words");
Note how the cout
is the second argument in the chain here.... odd right?
There are several possible catches. I think that the most common error is in this part of the connection string:
res://xxx/yyy.csdl|res://xxx/yyy.ssdl|res://xxx/yyy.msl;
This is no magic. Once you understand what is stands for you'll get the connection string right.
First the xxx part. That's nothing else than an assembly name where you defined you EF context clas. Usually it would be something like MyProject.Data. Default value is * which stands for all loaded assemblies. It's always better to specify a particular assembly name.
Now the yyy part. That's a resource name in the xxx assembly. It will usually be something like a relative path to your .edmx file with dots instead of slashes. E.g. Models/Catalog - Models.Catalog The easiest way to get the correct string for your application is to build the xxx assembly. Then open the assembly dll file in a text editor (I prefer the Total Commander's default viewer) and search for ".csdl". Usually there won't be more than 1 occurence of that string.
Your final EF connection string may look like this:
res://MyProject.Data/Models.Catalog.DataContext.csdl|res://MyProject.Data/Models.Catalog.DataContext.ssdl|res://MyProject.Data/Models.Catalog.DataContext.msl;
It can be a mathematical convention in the definition of an interval where square brackets mean "extremal inclusive" and round brackets "extremal exclusive".
Simply type conda update pandas
in your preferred shell (on Windows, use cmd; if Anaconda is not added to your PATH use the Anaconda prompt). You can of course use Eclipse together with Anaconda, but you need to specify the Python-Path (the one in the Anaconda-Directory).
See this document for a detailed instruction.
On my linux box, I use the following code. This is similar to code I've seen elsewhere (in the old python FAQs for instance) but that code spins in a tight loop where this code doesn't and there are lots of odd corner cases that code doesn't account for that this code does.
def read_single_keypress():
"""Waits for a single keypress on stdin.
This is a silly function to call if you need to do it a lot because it has
to store stdin's current setup, setup stdin for reading single keystrokes
then read the single keystroke then revert stdin back after reading the
keystroke.
Returns a tuple of characters of the key that was pressed - on Linux,
pressing keys like up arrow results in a sequence of characters. Returns
('\x03',) on KeyboardInterrupt which can happen when a signal gets
handled.
"""
import termios, fcntl, sys, os
fd = sys.stdin.fileno()
# save old state
flags_save = fcntl.fcntl(fd, fcntl.F_GETFL)
attrs_save = termios.tcgetattr(fd)
# make raw - the way to do this comes from the termios(3) man page.
attrs = list(attrs_save) # copy the stored version to update
# iflag
attrs[0] &= ~(termios.IGNBRK | termios.BRKINT | termios.PARMRK
| termios.ISTRIP | termios.INLCR | termios. IGNCR
| termios.ICRNL | termios.IXON )
# oflag
attrs[1] &= ~termios.OPOST
# cflag
attrs[2] &= ~(termios.CSIZE | termios. PARENB)
attrs[2] |= termios.CS8
# lflag
attrs[3] &= ~(termios.ECHONL | termios.ECHO | termios.ICANON
| termios.ISIG | termios.IEXTEN)
termios.tcsetattr(fd, termios.TCSANOW, attrs)
# turn off non-blocking
fcntl.fcntl(fd, fcntl.F_SETFL, flags_save & ~os.O_NONBLOCK)
# read a single keystroke
ret = []
try:
ret.append(sys.stdin.read(1)) # returns a single character
fcntl.fcntl(fd, fcntl.F_SETFL, flags_save | os.O_NONBLOCK)
c = sys.stdin.read(1) # returns a single character
while len(c) > 0:
ret.append(c)
c = sys.stdin.read(1)
except KeyboardInterrupt:
ret.append('\x03')
finally:
# restore old state
termios.tcsetattr(fd, termios.TCSAFLUSH, attrs_save)
fcntl.fcntl(fd, fcntl.F_SETFL, flags_save)
return tuple(ret)
You can also do like this:
template <typename T>
class make_vector {
public:
typedef make_vector<T> my_type;
my_type& operator<< (const T& val) {
data_.push_back(val);
return *this;
}
operator std::vector<T>() const {
return data_;
}
private:
std::vector<T> data_;
};
And use it like this:
std::vector<int> v = make_vector<int>() << 1 << 2 << 3;
The causes of this error are many so first locate your log file and check it for clues. It might be at /usr/local/var/log/postgres.log
or /usr/local/var/postgres/server.log
or possibly elsewhere. If you installed with Homebrew you can find the location in ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
.
According the w3c spec height refers to the height of the viewable area e.g. on a 1280x1024 pixel resolution monitor 100% height = 1024 pixels.
min-height refers to the total height of the page including content so on a page where the content is bigger than 1024px min-height:100% will stretch to include all of the content.
The other problem then is that padding and border are added to the height and width in most modern browsers except ie6(ie6 is actually quite logical but does not conform to the spec). This is called the box model. So if you specify
min-height: 100%;
padding: 5px;
It will actually give you 100% + 5px + 5px for the height. To get around this you need a wrapper container.
<style>
.FullHeight {
height: auto !important; /* ie 6 will ignore this */
height: 100%; /* ie 6 will use this instead of min-height */
min-height: 100%; /* ie 6 will ignore this */
}
.Padded {
padding: 5px;
}
</style>
<div class="FullHeight">
<div class="Padded">
Hello i am padded.
</div
</div>
Pass by value, except when
const
reference,const
lvalue reference,const
reference or not.)Passing by pointer is virtually never advised. Optional parameters are best expressed as a std::optional
(boost::optional
for older std libs), and aliasing is done fine by reference.
C++11's move semantics make passing and returning by value much more attractive even for complex objects.
Pass arguments by const
reference, except when
const
referenceNULL
/0
/nullptr
instead; apply the previous rule to determine whether you should pass by a pointer to a const
argument(here, "pass by value" is called "pass by copy", because passing by value always creates a copy in C++03)
There's more to this, but these few beginner's rules will get you quite far.
In my case I have multiple test projects in the same solution, and only one of the projects was not displaying the "Test Explorer"
I went to the "Manage Nuget Package for Solution" by right-clicking on the solution.
I noticed under the "Consolidate" tab there was some "Test" nuget packages that were out of sync between the projects. I clicked on "Install" and my missing tests showed up.
This error message appears if the Windows service launcher has quit immediately after being started. This problem usually happens because the license key has not been correctly deployed(license.txt file in the license folder). If service is not strtign with correct key, just put incorrect key and try to start. Once started, place the correct key, it will work.
You should only need to do a single join:
SELECT e.Grade, v.Score, e.CaseNum, e.FileNum, e.ActivityNum
FROM Evaluation e
INNER JOIN Value v ON e.CaseNum = v.CaseNum AND e.FileNum = v.FileNum AND e.ActivityNum = v.ActivityNum
You can just turn on Github Pages. ^_^
Click on "Settings", than go to "GitHub Pages" and click on dropdown under "Source" and choose branch which you want to public (where main html file is located) aaaand vualaa. ^_^
<?php
$content='<table width="100%" border="1">';
$content.='<tr><th>name</th><th>email</th><th>contact</th><th>address</th><th>city</th><th>country</th><th>postcode</th></tr>';
for ($index = 0; $index < 10; $index++) {
$content.='<tr><td>nadim</td><td>[email protected]</td><td>7737033665</td><td>247 dehligate</td><td>udaipur</td><td>india</td><td>313001</td></tr>';
}
$content.='</table>';
//$html = file_get_contents('pdf.php');
if(isset($_POST['pdf'])){
require_once('./dompdf/dompdf_config.inc.php');
$dompdf = new DOMPDF;
$dompdf->load_html($content);
$dompdf->render();
$dompdf->stream("hello.pdf");
}
?>
<html>
<body>
<form action="#" method="post">
<button name="pdf" type="submit">export</button>
<table width="100%" border="1">
<tr><th>name</th><th>email</th><th>contact</th><th>address</th><th>city</th><th>country</th><th>postcode</th></tr>
<?php for ($index = 0; $index < 10; $index++) { ?>
<tr><td>nadim</td><td>[email protected]</td><td>7737033665</td><td>247 dehligate</td><td>udaipur</td><td>india</td><td>313001</td></tr>
<?php } ?>
</table>
</form>
</body>
</html>
This might be a little late. But here is one of the usage. This to get the count of the number of files.
Create a pointer to memory (a new obj in this case) and have the property of the object modified. Java 8 stream doesn't allow to modify the pointer itself and hence if you declare just count as a variable and try to increment within the stream it will never work and throw a compiler exception in the first place
Path path = Paths.get("/Users/XXXX/static/test.txt");
Count c = new Count();
c.setCount(0);
Files.lines(path).forEach(item -> {
c.setCount(c.getCount()+1);
System.out.println(item);});
System.out.println("line count,"+c);
public static class Count{
private int count;
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
@Override
public String toString() {
return "Count [count=" + count + "]";
}
}
If you don't reference the imageBytes to carry bytes in the stream, the method won't return anything. Make sure you reference imageBytes = m.ToArray();
public static byte[] SerializeImage() {
MemoryStream m;
string PicPath = pathToImage";
byte[] imageBytes;
using (Image image = Image.FromFile(PicPath)) {
using ( m = new MemoryStream()) {
image.Save(m, image.RawFormat);
imageBytes = new byte[m.Length];
//Very Important
imageBytes = m.ToArray();
}//end using
}//end using
return imageBytes;
}//SerializeImage
i use anonymous objects for calling new Threads..
new Thread(new Runnable() {
public void run() {
// you code
}
}).start();