Removing and adding DOM element is slower than modification of existing one.
If your option sets have same length, you may do something like this:
$('#my-select option')
.each(function(index) {
$(this).text('someNewText').val('someNewValue');
});
In case your new option set has different length, you may delete/add empty options you really need, using some technique described above.
<Grid >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Button Command="{Binding ClickCommand}" Width="100" Height="100" Content="wefwfwef"/>
</Grid>
the code behind for the window:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModelBase();
}
}
The ViewModel:
public class ViewModelBase
{
private ICommand _clickCommand;
public ICommand ClickCommand
{
get
{
return _clickCommand ?? (_clickCommand = new CommandHandler(() => MyAction(), ()=> CanExecute));
}
}
public bool CanExecute
{
get
{
// check if executing is allowed, i.e., validate, check if a process is running, etc.
return true/false;
}
}
public void MyAction()
{
}
}
Command Handler:
public class CommandHandler : ICommand
{
private Action _action;
private Func<bool> _canExecute;
/// <summary>
/// Creates instance of the command handler
/// </summary>
/// <param name="action">Action to be executed by the command</param>
/// <param name="canExecute">A bolean property to containing current permissions to execute the command</param>
public CommandHandler(Action action, Func<bool> canExecute)
{
_action = action;
_canExecute = canExecute;
}
/// <summary>
/// Wires CanExecuteChanged event
/// </summary>
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
/// <summary>
/// Forcess checking if execute is allowed
/// </summary>
/// <param name="parameter"></param>
/// <returns></returns>
public bool CanExecute(object parameter)
{
return _canExecute.Invoke();
}
public void Execute(object parameter)
{
_action();
}
}
I hope this will give you the idea.
Simple, use absolute positioning, and instead of specifying a top and a left, specify a top and a right!
For example:
#logo_image {
width:80px;
height:80px;
top:10px;
right:10px;
z-index: 3;
position:absolute;
}
You are loading an entire HTML page into your div, including the html, head and body tags. What happens if you do the load and just have the opening script, closing script, and JavaScript code in the HTML that you load?
Here is the driver page:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery Load of Script</title>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", "1.3.2");
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#myButton").click(function() {
$("#myDiv").load("trackingCode.html");
});
});
</script>
</head>
<body>
<button id="myButton">Click Me</button>
<div id="myDiv"></div>
</body>
</html>
Here is the contents of trackingCode.html:
<script type="text/javascript">
alert("Outside the jQuery ready");
$(function() {
alert("Inside the jQuery ready");
});
</script>
This works for me in Safari 4.
Update: Added DOCTYPE and html namespace to match the code on my test environment. Tested with Firefox 3.6.13 and example code works.
I use this query in order to retrieve the server name of my Oracle database.
SELECT program FROM v$session WHERE program LIKE '%(PMON)%';
The Facebook "Graph API Rate Limiting" docs says that an error with code #4
is an app level rate limit, which is different than user level rate limits. Although it doesn't give any exact numbers, it describes their app level rate-limit as:
This rate limiting is applied globally at the app level. Ads api calls are excluded.
- Rate limiting happens real time on sliding window for past one hour.
- Stats is collected for number of calls and queries made, cpu time spent, memory used for each app.
- There is a limit for each resource multiplied by monthly active users of a given app.
- When the app uses more than its allowed resources the error is thrown.
- Error, Code: 4, Message: Application request limit reached
The docs also give recommendations for avoiding the rate limits. For app level limits, they are:
Recommendations:
- Verify the error code (4) to confirm the throttling type.
- Do not make burst of calls, spread out the calls throughout the day.
- Do smart fetching of data (important data, non duplicated data, etc).
- Real-time insights, make sure API calls are structured in a way that you can read insights for as many as Page posts as possible, with minimum number of requests.
- Don't fetch users feed twice (in the case that two App users have a specific friend in common)
- Don't fetch all user's friends feed in a row if the number of friends is more than 250. Separate the fetches over different days. As an option, fetch first the app user's news feed (me/home) in order to detect which friends are more important to the App user. Then, fetch those friends feeds first.
- Consider to limit/filter the requests by using the following parameters: "since", "until", "limit"
- For page related calls use realtime updates to subscribe to changes in data.
- Field expansion allows ton "join" multiple graph queries into a single call.
- Etags to check if the data querying has changed since the last check.
- For page management developers who does not have massive user base, have the admins of the page to accept the app to increase the number of users.
Finally, the docs give the following informational tips:
- Batching calls will not reduce the number of api calls.
- Making parallel calls will not reduce the number of api calls.
If you want to pass two values, you can use this approach
<asp:LinkButton ID="RemoveFroRole" Text="Remove From Role" runat="server"
CommandName='<%# Eval("UserName") %>' CommandArgument='<%# Eval("RoleName") %>'
OnClick="RemoveFromRole_Click" />
Basically I am treating {CommmandName,CommandArgument} as key value. Set both from database field. You will have to use OnClick event and use OnCommand
event in this case, which I think is more clean code.
I know the question talking about eclipse but i got the similar issue many times with Intellij as well and the solution for it was easy .. Just run the 64 bit exe not the 32 one which is always the default one.
A restart of the machine worked for me. None of the solutions provided so far worked for me.
Env Windows 10 + Git Bash
EDIT: I see the same solution was here: git index.lock File exists when I try to commit, but cannot delete the file
I noticed a posting that say that it does not matter if you call a __stdcall
from a __cdecl
or visa versa. It does.
The reason: with __cdecl
the arguments that are passed to the called functions are removed form the stack by the calling function, in __stdcall
, the arguments are removed from the stack by the called function. If you call a __cdecl
function with a __stdcall
, the stack is not cleaned up at all, so eventually when the __cdecl
uses a stacked based reference for arguments or return address will use the old data at the current stack pointer. If you call a __stdcall
function from a __cdecl
, the __stdcall
function cleans up the arguments on the stack, and then the __cdecl
function does it again, possibly removing the calling functions return information.
The Microsoft convention for C tries to circumvent this by mangling the names. A __cdecl
function is prefixed with an underscore. A __stdcall
function prefixes with an underscore and suffixed with an at sign “@” and the number of bytes to be removed. Eg __cdecl
f(x) is linked as _f
, __stdcall f(int x)
is linked as _f@4
where sizeof(int)
is 4 bytes)
If you manage to get past the linker, enjoy the debugging mess.
I recommend you to try Netbeans Profiler.It has rich set of tools for real time analysis. Tools from IbM are worth a try for offline analysis
RSS is Resident Set Size (physically resident memory - this is currently occupying space in the machine's physical memory), and VSZ is Virtual Memory Size (address space allocated - this has addresses allocated in the process's memory map, but there isn't necessarily any actual memory behind it all right now).
Note that in these days of commonplace virtual machines, physical memory from the machine's view point may not really be actual physical memory.
I only had to change one line of the file config.inc.php
located in C:\wamp\apps\phpmyadmin4.1.14
.
Put the right password here ...
$cfg['Servers'][$i]['password'] = 'Put_Password_Here';
If you want tho have a normal string infront of the greek letter make sure that you have the right order:
plt.ylabel(r'Microstrain [$\mu \epsilon$]')
I think you'd be better off with a CASE statement, which works a lot more like IF/ELSEIF
DECLARE @this int, @value varchar(10)
SET @this = 200
SET @value = (
SELECT
CASE
WHEN @this between 5 and 10 THEN 'foo'
WHEN @this between 10 and 15 THEN 'bar'
WHEN @this < 0 THEN 'barfoo'
ELSE 'foofoo'
END
)
More info: http://technet.microsoft.com/en-us/library/ms181765.aspx
From the answer of @Vicent, I already restore MySQL database as below:
Step 1. Shutdown Mysql server
Step 2. Copy database in your database folder (in linux, the default location is /var/lib/mysql). Keep same name of the database, and same name of database in mysql mode.
sudo cp -rf /mnt/ubuntu_426/var/lib/mysql/database1 /var/lib/mysql/
Step 3: Change own and change mode the folder:
sudo chown -R mysql:mysql /var/lib/mysql/database1
sudo chmod -R 660 /var/lib/mysql/database1
sudo chown mysql:mysql /var/lib/mysql/database1
sudo chmod 700 /var/lib/mysql/database1
Step 4: Copy ibdata1 in your database folder
sudo cp /mnt/ubuntu_426/var/lib/mysql/ibdata1 /var/lib/mysql/
sudo chown mysql:mysql /var/lib/mysql/ibdata1
Step 5: copy ib_logfile0 and ib_logfile1 files in your database folder.
sudo cp /mnt/ubuntu_426/var/lib/mysql/ib_logfile0 /var/lib/mysql/
sudo cp /mnt/ubuntu_426/var/lib/mysql/ib_logfile1 /var/lib/mysql/
Remember change own and change root of those files:
sudo chown -R mysql:mysql /var/lib/mysql/ib_logfile0
sudo chown -R mysql:mysql /var/lib/mysql/ib_logfile1
or
sudo chown -R mysql:mysql /var/lib/mysql
Step 6 (Optional): My site has configuration to store files in a specific location, then I copy those to corresponding location, exactly.
Step 7: Start your Mysql server. Everything come back and enjoy it.
That is it.
See more info at: https://biolinh.wordpress.com/2017/04/01/restoring-mysql-database-from-physical-files-debianubuntu/
I've found that the easiest way to have non-standard fonts on a website is to use sIFR
It does involve the use of a Flash object that contains the font, but it degrades nicely to standard text / font if Flash is not installed.
The style is set in your CSS, and JavaScript sets up the Flash replacement for your text.
Edit: (I still recommend using images for non-standard fonts as sIFR adds time to a project and can require maintenance).
Beyond select(-one_of(drop.cols))
there are a couple other options for dropping columns using select()
that do not involve defining all the specific column names (using the dplyr starwars sample data for some more variety in column names):
starwars %>%
select(-(name:mass)) %>% # the range of columns from 'name' to 'mass'
select(-contains('color')) %>% # any column name that contains 'color'
select(-starts_with('bi')) %>% # any column name that starts with 'bi'
select(-ends_with('er')) %>% # any column name that ends with 'er'
select(-matches('^f.+s$')) %>% # any column name matching the regex pattern
select_if(~!is.list(.)) %>% # not by column name but by data type
head(2)
# A tibble: 2 x 2
homeworld species
<chr> <chr>
1 Tatooine Human
2 Tatooine Droid
In my opinion, directories should not be considered targets of your makefile, either in technical or in design sense. You should create files and if a file creation needs a new directory then quietly create the directory within the rule for the relevant file.
If you're targeting a usual or "patterned" file, just use make
's internal variable $(@D)
, that means "the directory the current target resides in" (cmp. with $@
for the target). For example,
$(OUT_O_DIR)/%.o: %.cpp
@mkdir -p $(@D)
@$(CC) -c $< -o $@
title: $(OBJS)
Then, you're effectively doing the same: create directories for all $(OBJS)
, but you'll do it in a less complicated way.
The same policy (files are targets, directories never are) is used in various applications. For example, git
revision control system doesn't store directories.
Note: If you're going to use it, it might be useful to introduce a convenience variable and utilize make
's expansion rules.
dir_guard=@mkdir -p $(@D)
$(OUT_O_DIR)/%.o: %.cpp
$(dir_guard)
@$(CC) -c $< -o $@
$(OUT_O_DIR_DEBUG)/%.o: %.cpp
$(dir_guard)
@$(CC) -g -c $< -o $@
title: $(OBJS)
Just add one more block to Ozzy's code so the thing looks like this:
public static Dimension getScaledDimension(Dimension imgSize,Dimension boundary) {
int original_width = imgSize.width;
int original_height = imgSize.height;
int bound_width = boundary.width;
int bound_height = boundary.height;
int new_width = original_width;
int new_height = original_height;
// first check if we need to scale width
if (original_width > bound_width) {
//scale width to fit
new_width = bound_width;
//scale height to maintain aspect ratio
new_height = (new_width * original_height) / original_width;
}
// then check if we need to scale even with the new height
if (new_height > bound_height) {
//scale height to fit instead
new_height = bound_height;
//scale width to maintain aspect ratio
new_width = (new_height * original_width) / original_height;
}
// upscale if original is smaller
if (original_width < bound_width) {
//scale width to fit
new_width = bound_width;
//scale height to maintain aspect ratio
new_height = (new_width * original_height) / original_width;
}
return new Dimension(new_width, new_height);
}
Place this css in your page:
<style>
#client_logos {
display: inline-block;
width:100%;
}
</style>
Replace
<p><img class="alignnone" style="display: inline; margin: 0 10px;" title="heartica_logo" src="https://s3.amazonaws.com/rainleader/assets/heartica_logo.png" alt="" width="150" height="50" /><img class="alignnone" style="display: inline; margin: 0 10px;" title="mouseflow_logo" src="https://s3.amazonaws.com/rainleader/assets/mouseflow_logo.png" alt="" width="150" height="50" /><img class="alignnone" style="display: inline; margin: 0 10px;" title="mouseflow_logo" src="https://s3.amazonaws.com/rainleader/assets/piiholo_logo.png" alt="" width="150" height="50" /></p>
To
<div id="client_logos">
<img style="display: inline; margin: 0 5px;" title="heartica_logo" src="https://s3.amazonaws.com/rainleader/assets/heartica_logo.png" alt="" width="150" height="50" />
<img style="display: inline; margin: 0 5px;" title="mouseflow_logo" src="https://s3.amazonaws.com/rainleader/assets/mouseflow_logo.png" alt="" width="150" height="50" />
<img style="display: inline; margin: 0 5px;" title="piiholo_logo" src="https://s3.amazonaws.com/rainleader/assets/piiholo_logo.png" alt="" width="150" height="50" />
</div>
I presume you are trying to compile the application and run it without using an IDE. I also presume you have maven installed and correctly added maven to your environment variable.
To install and add maven to environment variable visit Install maven if you are under a proxy check out add proxy to maven
Navigate to the root of the project via command line and execute the command
mvn spring-boot:run
The CLI will run your application on the configured port and you can access it just like you would if you start the app in an IDE.
Note: This will work only if you have maven added to your pom.xml
I managed to lock myself out of a file in svn - don't know how - but when I tried (re)-getting the lock (Tortoise was showing the "Get Lock" option for the file), it complained that already had the lock. I tried deleting the file and committing the directory change - same result. I tried CleanUp (including refreshing the overlay), but that failed too.
The solution was to go into the Tortoise repo-browser, find the file and use the break lock function.
You can use a TYPE
command instead of COPY
. Try this:
TYPE File1.txt>File2.txt
Where File1.txt
is empty.
Force popen
to not continue until all output is read by doing:
os.popen(command).read()
In my case I had relocated Web Deploy to another port, which was also the IIS port (not 80). I didn't realize at first, but even though there were no errors running both under the same port, seems Web Deploy was most likely responding first instead of IIS for some reason, causing this error. I just moved my IIS binding to another port and all is well. ;)
Although it does not directly answers your question, I would like to mention Apple recentely had this talk:
https://developer.apple.com/videos/play/wwdc2018/714/
At around 09:55 he talks about doing this stuff you are asking about:
However, this has a few pitfalls:
The following points are some best practices according to Apple:
waitsForConnectivity
to true (https://developer.apple.com/documentation/foundation/urlsessionconfiguration/2908812-waitsforconnectivity)taskIsWaitingForConnectivity
(https://developer.apple.com/documentation/foundation/urlsessiontaskdelegate/2908819-urlsession). This is Apple's recommended way to check for connectivity, as mentioned in the video at 33:25.According to the talk, there shouldn't be any reason to pre-check whetever you got internet connection or not, since it may not be accurate at the time you send your request to the server.
I realized that I wasn't passing $objPage into page_properties(). It works fine now.
your_list = [None]*size_required
Or, once it's already in SSIS, you could create a derived column (as part of some data flow task) with:
(DT_I8)FLOOR((DT_R8)systemDateTime)
But you'd have to test to doublecheck.
If you're like me and prone to silly mistakes, also check your package.json if it contains your babel preset:
"babel": {
"presets": [
"env",
"react",
"stage-2"
]
},
Warning: the following is not very nice but it does the job.
#include <stdio.h>
#include <stdlib.h>
typedef struct {
unsigned int id;
char *name;
char *msg;
} error;
#define _printerr(e, s, ...) fprintf(stderr, "\033[1m\033[37m" "%s:%d: " "\033[1m\033[31m" e ":" "\033[1m\033[37m" " ‘%s_error’ " "\033[0m" s "\n", __FILE__, __LINE__, (*__err)->name, ##__VA_ARGS__)
#define printerr(s, ...) _printerr("error", s, ##__VA_ARGS__)
#define printuncaughterr() _printerr("uncaught error", "%s", (*__err)->msg)
#define _errordef(n, _id) \
error* new_##n##_error_msg(char* msg) { \
error* self = malloc(sizeof(error)); \
self->id = _id; \
self->name = #n; \
self->msg = msg; \
return self; \
} \
error* new_##n##_error() { return new_##n##_error_msg(""); }
#define errordef(n) _errordef(n, __COUNTER__ +1)
#define try(try_block, err, err_name, catch_block) { \
error * err_name = NULL; \
error ** __err = & err_name; \
void __try_fn() try_block \
__try_fn(); \
void __catch_fn() { \
if (err_name == NULL) return; \
unsigned int __##err_name##_id = new_##err##_error()->id; \
if (__##err_name##_id != 0 && __##err_name##_id != err_name->id) \
printuncaughterr(); \
else if (__##err_name##_id != 0 || __##err_name##_id != err_name->id) \
catch_block \
} \
__catch_fn(); \
}
#define throw(e) { *__err = e; return; }
_errordef(any, 0)
Usage:
errordef(my_err1)
errordef(my_err2)
try ({
printf("Helloo\n");
throw(new_my_err1_error_msg("hiiiii!"));
printf("This will not be printed!\n");
}, /*catch*/ any, e, {
printf("My lovely error: %s %s\n", e->name, e->msg);
})
printf("\n");
try ({
printf("Helloo\n");
throw(new_my_err2_error_msg("my msg!"));
printf("This will not be printed!\n");
}, /*catch*/ my_err2, e, {
printerr("%s", e->msg);
})
printf("\n");
try ({
printf("Helloo\n");
throw(new_my_err1_error());
printf("This will not be printed!\n");
}, /*catch*/ my_err2, e, {
printf("Catch %s if you can!\n", e->name);
})
Output:
Helloo
My lovely error: my_err1 hiiiii!
Helloo
/home/naheel/Desktop/aa.c:28: error: ‘my_err2_error’ my msg!
Helloo
/home/naheel/Desktop/aa.c:38: uncaught error: ‘my_err1_error’
Keep on mind that this is using nested functions and __COUNTER__
. You'll be on the safe side if you're using gcc.
I use this:
public static long sum(int[] i_arr)
{
long sum;
int i;
for(sum= 0, i= i_arr.length - 1; 0 <= i; sum+= i_arr[i--]);
return sum;
}
Configuration hibConfiguration = new Configuration()
.addResource("wp4core/hibernate/config/table.hbm.xml")
.configure();
serviceRegistry = new ServiceRegistryBuilder()
.applySettings(hibConfiguration.getProperties())
.buildServiceRegistry();
sessionFactory = hibConfiguration.buildSessionFactory(serviceRegistry);
session = sessionFactory.withOptions().openSession();
Generate environment variables from script (Unix script) :
echo "BUILD_DATE=$(date +%F-%T)"
Sure you can:
SELECT * FROM table
WHERE DateStamp > DATE_ADD(NOW(), INTERVAL -1 DAY)
Whatever you want to use from another module, just put it in the export array. Like this-
@NgModule({
declarations: [TaskCardComponent],
exports: [TaskCardComponent],
imports: [MdCardModule]
})
I think the problem is with the way you designed your data. To me in terms of semantics, it just doesn't make sense. What exactly is steps for?
Does it store the information of one company?
If that's the case steps should be an object (see KayakDave's answer) and each "step" should be an object property.
Does it store the information of multiple companies?
If that's the case, steps should be an array of objects.
$scope.steps=[{companyName: true, businessType: true},{companyName: false}]
In either case you can easily iterate through the data with one (two for 2nd case) ng-repeats.
The list method index
will return -1
if the item is not present, and will return the index of the item in the list if it is present. Alternatively in an if
statement you can do the following:
if myItem in list:
#do things
You can also check if an element is not in a list with the following if statement:
if myItem not in list:
#do things
From the comp.lang.c FAQ: http://c-faq.com/null/varieties.html
In essence: NULL
(the preprocessor macro for the null pointer) is not the same as NUL
(the null character).
You have to placed this code in application.rb
config.action_dispatch.default_headers = {
'Access-Control-Allow-Origin' => '*',
'Access-Control-Request-Method' => %w{GET POST OPTIONS}.join(",")
}
If you want to support more browsers than the CSS3 fancy, you can look at the open source library cufon javascript library
And here is the API, if you want to do more funky stuff.
Major Pro: Allows you to do what you want / need.
Major Con: Disallows text selection in some browsers, so use is appropiate on header texts (but you can use it in all your site if you want)
I just found a way that allow you not directly access the status bar height, but calculate it.
Navigation Bar height - topLayoutGuide length = status bar height
Swift:
let statusBarHeight = self.topLayoutGuide.length-self.navigationController?.navigationBar.frame.height
self.topLayoutGuide.length
is the top area that's covered by the translucent bar, and self.navigationController?.navigationBar.frame.height
is the translucent bar excluding status bar, which is usually 44pt. So by using this method you can easily calculate the status bar height without worring about status bar height change due to phone calls.
It is called the Card Security Code (CSC) according to Wikipedia, but has also been known as other things, such as the Card Verification Value (CVV) or Card Verfication Code (CVC).
The second code, and the most cited, is CVV2 or CVC2. This CSC (also known as a CCID or Credit Card ID) is often asked for by merchants for them to secure "card not present" transactions occurring over the Internet, by mail, fax or over the phone. In many countries in Western Europe, due to increased attempts at card fraud, it is now mandatory to provide this code when the cardholder is not present in person.
Because this seems to be known by multiple names, and its name doesn't seem to be printed on the card itself, you'll probably (unfortunately) still need to tell your users how to find the code - ie by describing it as the "3 digit code on back of card".
2018 update
The situation has not improved, and is now worse - there are even more different names now. However, you can if you like use different terms depending on the card type:
Note that some American Express and Discover cards use a 4-digit code on the front of the card. See the above linked Wikipedia article for more.
please try with below query
select id,numbers_from,created_date,amount_numbers,SMS_text
from Test_Table
where
convert(datetime, convert(varchar(10), created_date, 102)) <= convert(datetime,'2013-04-12')
FFMpeg can do this by seeking to the given timestamp and extracting exactly one frame as an image, see for instance:
ffmpeg -i input_file.mp4 -ss 01:23:45 -vframes 1 output.jpg
Let's explain the options:
-i input file the path to the input file
-ss 01:23:45 seek the position to the specified timestamp
-vframes 1 only handle one video frame
output.jpg output filename, should have a well-known extension
The -ss
parameter accepts a value in the form HH:MM:SS[.xxx]
or as a number in seconds. If you need a percentage, you need to compute the video duration beforehand.
for better readability you can convert the object to a json string as below:
console.log(obj, JSON.stringify(obj));
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
Highlight "B1" and press F4. This will lock the cell.
Now you can drag it around and it will not change. The principle is simple. It adds a dollar sign before both coordinates. A dollar sign in front of a coordinate will lock it when you copy the formula around. You can have partially locked coordinates and fully locked coordinates.
I would recommend separating out all of the foreign-key constraints from your CREATE TABLE
statements. Create all the tables first without FK constraints, and then create all the FK constraints once you have created the tables.
You can add an FK constraint to a table using SQL like the following:
ALTER TABLE orders ADD CONSTRAINT orders_FK
FOREIGN KEY (m_p_unique_id) REFERENCES library (m_p_unique_id);
In particular, your formats
and library
tables both have foreign-key constraints on one another. The two CREATE TABLE
statements to create these two tables can never run successfully, as each will only work when the other table has already been created.
Separating out the constraint creation allows you to create tables with FK constraints on one another. Also, if you have an error with a constraint, only that constraint fails to be created. At present, because you have errors in the constraints in your CREATE TABLE
statements, then entire table creation fails and you get various knock-on errors because FK constraints may depend on these tables that failed to create.
First of all, you aren't forced to use an SMTP on your localhost, if you change that localhost entry into the DNS name of the MTA from your ISP provider (who will let you relay mail) it will work right away, so no messing about with your own email service. Just try to use your providers SMTP servers, it will work right away.
If you want to use geonames.org then use this code. (But geonames.org is very slow sometimes)
String get_time_zone_time_geonames(GeoPoint gp){
String erg = "";
double Longitude = gp.getLongitudeE6()/1E6;
double Latitude = gp.getLatitudeE6()/1E6;
String request = "http://ws.geonames.org/timezone?lat="+Latitude+"&lng="+ Longitude+ "&style=full";
URL time_zone_time = null;
InputStream input;
// final StringBuilder sBuf = new StringBuilder();
try {
time_zone_time = new URL(request);
try {
input = time_zone_time.openConnection().getInputStream();
final BufferedReader reader = new BufferedReader(new InputStreamReader(input));
final StringBuilder sBuf = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sBuf.append(line);
}
} catch (IOException e) {
Log.e(e.getMessage(), "XML parser, stream2string 1");
} finally {
try {
input.close();
} catch (IOException e) {
Log.e(e.getMessage(), "XML parser, stream2string 2");
}
}
String xmltext = sBuf.toString();
int startpos = xmltext.indexOf("<geonames");
xmltext = xmltext.substring(startpos);
XmlPullParser parser;
try {
parser = XmlPullParserFactory.newInstance().newPullParser();
parser.setInput(new StringReader (xmltext));
int eventType = parser.getEventType();
String tagName = "";
while(eventType != XmlPullParser.END_DOCUMENT) {
switch(eventType) {
case XmlPullParser.START_TAG:
tagName = parser.getName();
break;
case XmlPullParser.TEXT :
if (tagName.equalsIgnoreCase("time"))
erg = parser.getText();
break;
}
try {
eventType = parser.next();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (XmlPullParserException e) {
e.printStackTrace();
erg += e.toString();
}
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
return erg;
}
And use it with:
GeoPoint gp = new GeoPoint(39.6034810,-119.6822510);
String Current_TimeZone_Time = get_time_zone_time_geonames(gp);
<input type="text" id="txtCode" name="name" class="text_cs">
and js:
<script type="text/javascript">
$('.text_cs').on('change', function () {
var pid = $(this).val();
console.log("Value text: " + pid);
});
</script>
One more way:
CREATE OR REPLACE TYPE TYPE_TABLE_OF_VARCHAR2 AS TABLE OF VARCHAR(100);
-- ...
SELECT field1, field2, field3
FROM table1
WHERE name IN (
SELECT * FROM table (SELECT CAST(? AS TYPE_TABLE_OF_VARCHAR2) FROM dual)
);
I don't consider it's optimal, but it works. The hint /*+ CARDINALITY(...) */
would be very useful because Oracle does not understand cardinality of the array passed and can't estimate optimal execution plan.
As another alternative - batch insert into temporary table and using the last in subquery for IN
predicate.
You can have a look at the source code (here it is v1.7.2).
Except for the animation that we can set, this also keep in memory the old display style (which is not in all cases block
, it can also be inline
, table-cell
, ...).
pgmagick is a GraphicsMagick(Magick++)
binding for Python.
It's is a Python wrapper for for ImageMagick (or GraphicsMagick).
import os
from os import listdir
from os.path import isfile, join
from pgmagick import Image
mypath = "\Images" # path to your Image directory
for each_file in listdir(mypath):
if isfile(join(mypath,each_file)):
image_path = os.path.join(mypath,each_file)
pdf_path = os.path.join(mypath,each_file.rsplit('.', 1)[0]+'.pdf')
img = Image(image_path)
img.write(pdf_path)
Sample input Image:
PDF looks like this:
pgmagick iinstallation instruction for windows:
1) Download precompiled binary packages from the Unofficial Windows Binaries for Python Extension Packages (as mentioned in the pgmagick web page) and install it.
Note: Try to download correct version corresponding to your python version installed in your machine and whether its 32bit installation or 64bit.
You can check whether you have 32bit or 64bit python by just typing python at your terminal and press Enter..
D:\>python
ActivePython 2.7.2.5 (ActiveState Software Inc.) based on
Python 2.7.2 (default, Jun 24 2011, 12:21:10) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
So it has python version 2.7
and its of 32 bit (Intel)] on win32
so you have to downlad and install pgmagick-0.5.8.win32-py2.7.exe
.
These are the following available Python Extension Packages for pgmagick:
2) Then you can follow installation instruction from here.
pip install pgmagick
An then try to import it.
>>> from pgmagick import gminfo
>>> gminfo.version
'1.3.x'
>>> gminfo.library
'GraphicsMagick'
>>>
I had the error after trying to select a subset of rows:
df = df.reindex(index=my_index)
Turns out that my_index
contained values that were not contained in df.index
, so the reindex function inserted some new rows and filled them with nan
.
Add addToBackStack() to fragment transaction and then use below code for Implementing Back Navigation for Fragments
getSupportFragmentManager().addOnBackStackChangedListener(
new FragmentManager.OnBackStackChangedListener() {
public void onBackStackChanged() {
// Update your UI here.
}
});
You are not actually changing the function.
onClick
is assigned to a function (Which is a reference to something, a function pointer in this case). The values passed to it don't matter and cannot be utilised in any manner.
Another problem is your variable color
seems out of nowhere.
Ideally, inside the function you should put this logic and let it figure out what to write. (on/off etc etc)
The Jenkins EnvInject Plugin might be able to help you. It allows injecting environment variables into the build environment.
I know it has some ability to do scripting, so it might be able to do what you want. I have only used it to set simple properties (e.g. "LOG_PATH=${WORKSPACE}\logs").
I had this problem in some solutions on VS 2015 (not MVC though), and even in the same solution on one workstation but not on another. The errors started appeared after changing .NET version to 4.6 and referencing PCL.
The solution is simple: Close the solution and delete the hidden .vs folder in the same folder as the solution.
Adding the missing references as suggested in other answers also solves the problem, but the error remains solved even after you remove the references again.
As for TeamCity, I cannot say since my configuration never had a problem. But make sure that you reset the working catalog as a part of your debugging effort.
If you want to do something like the following example, you'd have to use nested if
s.
If percentage is greater than or equal to 93%, then corresponding value in B should be 4 and if the percentage is greater than or equal to 90% and less than 92%, then corresponding value in B to be 3.7, etc.
Here's how you'd do it:
=IF(A2>=93%, 4, IF(A2>=90%, 3.7,IF(A2>=87%,3.3,0)))
The gdi32 library is already installed on your computer, few programs will run without it. Your compiler will (if installed properly) normally come with an import library, which is what the linker uses to make a binding between your program and the file in the system. (In the unlikely case that your compiler does not come with import libraries for the system libs, you will need to download the Microsoft Windows Platform SDK.)
To link with gdi32:
This will reliably work with MinGW-gcc for all system libraries (it should work if you use any other compiler too, but I can't talk about things I've not tried). You can also write the library's full name, but writing libgdi32.a
has no advantage over gdi32
other than being more type work.
If it does not work for some reason, you may have to provide a different name (for example the library is named gdi32.lib
for MSVC).
For libraries in some odd locations or project subfolders, you will need to provide a proper pathname (click on the "..." button for a file select dialog).
You can use tandem of MemoryStream
and StreamReader
classes:
void Main()
{
string myString;
using (var stream = new MemoryStream())
{
Print(stream);
stream.Position = 0;
using (var reader = new StreamReader(stream))
{
myString = reader.ReadToEnd();
}
}
}
In one line :
HashMap<String, Integer> map = (HashMap<String, Integer>) Arrays.asList(str.split(",")).stream().map(s -> s.split(":")).collect(Collectors.toMap(e -> e[0], e -> Integer.parseInt(e[1])));
Details:
1) Split entry pairs and convert string array to List<String>
in order to use java.lang.Collection.Stream
API from Java 1.8
Arrays.asList(str.split(","))
2) Map the resulting string list "key:value"
to a string array with [0] as key and [1] as value
map(s -> s.split(":"))
3) Use collect
terminal method from stream API to mutate
collect(Collector<? super String, Object, Map<Object, Object>> collector)
4) Use the Collectors.toMap()
static method which take two Function to perform mutation from input type to key and value type.
toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper)
where T is the input type, K the key type and U the value type.
5) Following lambda mutate String
to String
key and String
to Integer
value
toMap(e -> e[0], e -> Integer.parseInt(e[1]))
Enjoy the stream and lambda style with Java 8
. No more loops !
I created this test case: http://jsfiddle.net/ccQnK/1/ , I used the Javascript replace function with regular expressions to get the results that you want.
$(document).ready(function() {
var myContent = '<div id="test">Hello <span>world!</span></div>';
alert(myContent.replace(/(<([^>]+)>)/ig,""));
});
The output which you showed in problem statement is not the tuple but list
list_c = [(1,5), (2,6), (3,7), (4,8)]
check for
type(list_c)
considering you want the result as tuple out of list_a and list_b, do
tuple(zip(list_a,list_b))
You probably do not have a keyframe at the 3 second mark. Because non-keyframes encode differences from other frames, they require all of the data starting with the previous keyframe.
With the mp4 container it is possible to cut at a non-keyframe without re-encoding using an edit list. In other words, if the closest keyframe before 3s is at 0s then it will copy the video starting at 0s and use an edit list to tell the player to start playing 3 seconds in.
If you are using the latest ffmpeg from git master it will do this using an edit list when invoked using the command that you provided. If this is not working for you then you are probably either using an older version of ffmpeg, or your player does not support edit lists. Some players will ignore the edit list and always play all of the media in the file from beginning to end.
If you want to cut precisely starting at a non-keyframe and want it to play starting at the desired point on a player that does not support edit lists, or want to ensure that the cut portion is not actually in the output file (for example if it contains confidential information), then you can do that by re-encoding so that there will be a keyframe precisely at the desired start time. Re-encoding is the default if you do not specify copy
. For example:
ffmpeg -i movie.mp4 -ss 00:00:03 -t 00:00:08 -async 1 cut.mp4
When re-encoding you may also wish to include additional quality-related options or a particular AAC encoder. For details, see ffmpeg's x264 Encoding Guide for video and AAC Encoding Guide for audio.
Also, the -t
option specifies a duration, not an end time. The above command will encode 8s of video starting at 3s. To start at 3s and end at 8s use -t 5
. If you are using a current version of ffmpeg you can also replace -t
with -to
in the above command to end at the specified time.
If you still haven't resolved this issue - like me - here is what caused this error for me. As @jkyoutsey suggested, I was indeed trying to create a modal component. I spent considerable time following his suggestions by moving my component to a service and injecting it into the page component. Also changing providedIn: 'root' to MyModule, which of course had to be moved at least one level up to avoid a circular reference. I'm not all together sure any of that actually was necessary.
What finally solved the 8-hour long puzzle was to NOT implement ngOnInit in my component. I had blindly implemented ngOnInit even though the function was empty. I tend to do that. It's probably a bad practice.
Anyway, if someone could shed light on why an empty ngOnInit would have caused this error, I'd love to read the comments.
Possibly one of the better examples of 'There's More Than One Way To Do It", with or without the help of CPAN.
If you have control over what you get passed as a 'date/time', I'd suggest going the DateTime route, either by using a specific Date::Time::Format subclass, or using DateTime::Format::Strptime if there isn't one supporting your wacky date format (see the datetime FAQ for more details). In general, Date::Time is the way to go if you want to do anything serious with the result: few classes on CPAN are quite as anal-retentive and obsessively accurate.
If you're expecting weird freeform stuff, throw it at Date::Parse's str2time() method, which'll get you a seconds-since-epoch value you can then have your wicked way with, without the overhead of Date::Manip.
on windows 8, it worked for me using :
npm install -g node-gyp -msvs_version=2012
then
npm install -g restify
Either your data is bad, or it's not structured the way you think it is. Possibly both.
To prove/disprove this hypothesis, run this query:
SELECT * from
(
SELECT count(*) as c, Supplier_Item.SKU
FROM Supplier_Item
INNER JOIN orderdetails
ON Supplier_Item.sku = orderdetails.sku
INNER JOIN Supplier
ON Supplier_item.supplierID = Supplier.SupplierID
GROUP BY Supplier_Item.SKU
) x
WHERE c > 1
ORDER BY c DESC
If this returns just a few rows, then your data is bad. If it returns lots of rows, then your data is not structured the way you think it is. (If it returns zero rows, I'm wrong.)
I'm guessing that you have orders containing the same SKU
multiple times (two separate line items, both ordering the same SKU
).
Here is the question: Is it possible that I can set the default value without using attribute 'value'?
Nope: value
is the only way to set the default attribute.
Why don't you want to use it?
Without function here it is...it works fine with listArrays filled with Objects
example `
al.add(new Student(101,"Jack",23,'C'));//adding Student class object
al.add(new Student(102,"Evan",21,'A'));
al.add(new Student(103,"Berton",25,'B'));
al.add(0, new Student(104,"Brian",20,'D'));
al.add(0, new Student(105,"Lance",24,'D'));
for(int i = 101; i< 101+al.size(); i++) {
al.get(i-101).rollno = i;//rollno is 101, 102 , 103, ....
}
Search it for a long time, and finally, I found how to do it:)
Please check this image which illustrates steps. enter image description here
From the official documentation, does it not seem that the sample() method is appropriate for this purpose?
import random
def random_digits(n):
num = range(0, 10)
lst = random.sample(num, n)
print str(lst).strip('[]')
Output:
>>>random_digits(5)
2, 5, 1, 0, 4
You are correct in that it's not "right" to add files to the tags folder.
You've correctly guessed that copy
is the operation to use; it lets Subversion keep track of the history of these files, and also (I assume) store them much more efficiently.
In my experience, it's best to do copies ("snapshots") of entire projects, i.e. all files from the root check-out location. That way the snapshot can stand on its own, as a true representation of the entire project's state at a particular point in time.
This part of "the book" shows how the command is typically used.
Did you include a reference to System.Web.Extensions
? If you click on your first link it says which assembly it's in.
Use OLEDB Connection to communicate with excel files. it gives better result
using System.Data.OleDb;
string physicalPath = "Your Excel file physical path";
OleDbCommand cmd = new OleDbCommand();
OleDbDataAdapter da = new OleDbDataAdapter();
DataSet ds = new DataSet();
String strNewPath = physicalPath;
String connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strNewPath + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
String query = "SELECT * FROM [Sheet1$]"; // You can use any different queries to get the data from the excel sheet
OleDbConnection conn = new OleDbConnection(connString);
if (conn.State == ConnectionState.Closed) conn.Open();
try
{
cmd = new OleDbCommand(query, conn);
da = new OleDbDataAdapter(cmd);
da.Fill(ds);
}
catch
{
// Exception Msg
}
finally
{
da.Dispose();
conn.Close();
}
The Output data will be stored in dataset, using the dataset object you can easily access the datas. Hope this may helpful
You can also create a new jsp file sayng that form is submited and in your main action file just write its file name
Eg. Your form is submited is in a file succes.jsp Then your action file will have
Request.sendRedirect("success.jsp")
There's the short tag version of your code, which is now completely acceptable to use despite antiquated recommendations otherwise:
<input type="hidden" name="type" value="<?= $var ?>" >
which (prior to PHP 5.4) requires short tags be enabled in your php configuration. It functions exactly as the code you typed; these lines are literally identical in their internal implementation:
<?= $var1, $var2 ?>
<?php echo $var1, $var2 ?>
That's about it for built-in solutions. There are plenty of 3rd party template libraries that make it easier to embed data in your output, smarty is a good place to start.
Java implementations typically use a two-step compilation process. Java source code is compiled down to bytecode by the Java compiler. The bytecode is executed by a Java Virtual Machine (JVM). Modern JVMs use a technique called Just-in-Time (JIT) compilation to compile the bytecode to native instructions understood by hardware CPU on the fly at runtime.
Some implementations of JVM may choose to interpret the bytecode instead of JIT compiling it to machine code, and running it directly. While this is still considered an "interpreter," It's quite different from interpreters that read and execute the high level source code (i.e. in this case, Java source code is not interpreted directly, the bytecode, output of Java compiler, is.)
It is technically possible to compile Java down to native code ahead-of-time and run the resulting binary. It is also possible to interpret the Java code directly.
To summarize, depending on the execution environment, bytecode can be:
for the latest Chrome version, this works for me :
var win = window.open("", "Title", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=780,height=200,top="+(screen.height-400)+",left="+(screen.width-840));
win.document.body.innerHTML = 'iframe width="100%" height="100%" src="data:application/pdf;base64,"+base64+"></iframe>';
Thanks
Apache MPM prefork with modphp is used because it is easy to configure/install. Performance-wise it is fairly inefficient. My preferred way to do the stack, FastCGI/PHP-FPM. That way you can use the much faster MPM Worker. The whole PHP remains non-threaded, but Apache serves threaded (like it should).
So basically, from bottom to top
Linux
Apache + MPM Worker + ModFastCGI (NOT FCGI) |(or)| Cherokee |(or)| Nginx
PHP-FPM + APC
ModFCGI does not correctly support PHP-FPM, or any external FastCGI applications. It only supports non-process managed FastCGI scripts. PHP-FPM is the PHP FastCGI process manager.
The function I used:
function cutAfter($string, $len = 30, $append = '...') {
return (strlen($string) > $len) ?
substr($string, 0, $len - strlen($append)) . $append :
$string;
}
See it in action.
Another way would be to define an interface IThing and then implement it in both classes here's the snipet:
public interface IThing
{
void Move();
}
public class ThingA : IThing
{
public void Move()
{
Hop();
}
public void Hop(){
//Implementation of Hop
}
}
public class ThingA : IThing
{
public void Move()
{
Skip();
}
public void Skip(){
//Implementation of Skip
}
}
public class Foo
{
static void Main(String[] args)
{
}
private void Foo(IThing a)
{
a.Move();
}
}
I fixed same issue. Solution for me:
xmlns:tools="http://schemas.android.com/tools"
line in the manifest tagtools:replace=..
in the manifest tagandroid:label=...
in the manifest tagExample:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:replace="allowBackup, label"
android:allowBackup="false"
android:label="@string/all_app_name"/>
:: savevars.bat
:: Use $ to prefix any important variable to save it for future runs.
@ECHO OFF
SETLOCAL
REM Load variables
IF EXIST config.txt FOR /F "delims=" %%A IN (config.txt) DO SET "%%A"
REM Change variables
IF NOT DEFINED $RunCount (
SET $RunCount=1
) ELSE SET /A $RunCount+=1
REM Display variables
SET $
REM Save variables
SET $>config.txt
ENDLOCAL
PAUSE
EXIT /B
Output:
$RunCount=1
$RunCount=2
$RunCount=3
The technique outlined above can also be used to share variables among multiple batch files.
You may at times need to get different values from URL.
Below example shows different ways of extracting different parts of URL
EXAMPLE: (Sample URL)
http://localhost:60527/WebSite1test/Default2.aspx?QueryString1=1&QueryString2=2
CODE
Response.Write("<br/> " + HttpContext.Current.Request.Url.Host);
Response.Write("<br/> " + HttpContext.Current.Request.Url.Authority);
Response.Write("<br/> " + HttpContext.Current.Request.Url.Port);
Response.Write("<br/> " + HttpContext.Current.Request.Url.AbsolutePath);
Response.Write("<br/> " + HttpContext.Current.Request.ApplicationPath);
Response.Write("<br/> " + HttpContext.Current.Request.Url.AbsoluteUri);
Response.Write("<br/> " + HttpContext.Current.Request.Url.PathAndQuery);
OUTPUT
localhost
localhost:60527
60527
/WebSite1test/Default2.aspx
/WebSite1test
http://localhost:60527/WebSite1test/Default2.aspx?QueryString1=1&QueryString1=2
/WebSite1test/Default2.aspx?QueryString1=1&QueryString2=2
You can copy paste above sample code & run it in asp.net web form application with different URL.
I also recommend reading ASP.Net Routing in case you may use ASP Routing then you don't need to use traditional URL with query string.
http://msdn.microsoft.com/en-us/library/cc668201%28v=vs.100%29.aspx
The easiest way for me to understand is to talk about whether you are calculating a statistic for each column (axis = 0
) or each row (axis = 1
). If you calculate a statistic, say a mean, with axis = 0
you will get that statistic for each column. So if each observation is a row and each variable is in a column, you would get the mean of each variable. If you set axis = 1
then you will calculate your statistic for each row. In our example, you would get the mean for each observation across all of your variables (perhaps you want the average of related measures).
axis = 0
: by column = column-wise = along the rows
axis = 1
: by row = row-wise = along the columns
1) Launch Android Studio application
2) Choose File -> Settings (For Mac Preference )
3) Search for Plugins
In Android Studio 3.4.2
you can convert any SVG to a component and make it reusable.
here is my answer for the easiest way you can do it
A given ID can be only used once in a page. It's invalid HTML to have multiple objects with the same ID, even if they are in different parts of the page.
You could change your HTML to this:
<div id="div1" >
<input type="text" class="edit1" />
<input type="text" class="edit2" />
</div>
<div id="div2" >
<input type="text" class="edit1" />
<input type="text" class="edit2" />
</div>
Then, you could get the first item in div1 with a CSS selector like this:
#div1 .edit1
On in jQuery:
$("#div1 .edit1")
Or, if you want to iterate the items in one of your divs, you can do it like this:
$("#div1 input").each(function(index) {
// do something with one of the input objects
});
If I couldn't use a framework like jQuery or YUI, I'd go get Sizzle and include that for it's selector logic (it's the same selector engine as is inside of jQuery) because DOM manipulation is massively easier with a good selector library.
If I couldn't use even Sizzle (which would be a massive drop in developer productivity), you could use plain DOM functions to traverse the children of a given element.
You would use DOM functions like childNodes or firstChild and nextSibling and you'd have to check the nodeType to make sure you only got the kind of elements you wanted. I never write code that way because it's so much less productive than using a selector library.
This is fairly close to an XY problem. That is, the question being asked is essentially how to mutate a captured local variable from a lambda. But the actual task at hand is how to number the elements of a list.
In my experience, upward of 80% of the time there is a question of how to mutate a captured local from within a lambda, there's a better way to proceed. Usually this involves reduction, but in this case the technique of running a stream over the list indexes applies well:
IntStream.range(0, list.size())
.forEach(i -> list.get(i).setOrdinal(i));
select year(current_timestamp)
As referred to in the first answer, there are 32/64 bit scenarios which introduce build and runtime pitfalls for developers.
The solution is always to try to get right: What kind of software and OS you have installed.
For a small list of scenarios with the Oracle driver and the solution, you can visit this post.
For example,
package main
import (
"flag"
"fmt"
"os"
"strconv"
)
func main() {
flag.Parse()
s := flag.Arg(0)
// string to int
i, err := strconv.Atoi(s)
if err != nil {
// handle error
fmt.Println(err)
os.Exit(2)
}
fmt.Println(s, i)
}
an EXE
file is created as long as you build the project. you can usually find this on the debug folder of you project.
C:\Users\username\Documents\Visual Studio 2012\Projects\ProjectName\bin\Debug
checkout this article :http://www.morgantechspace.com/2013/08/convert-object-to-byte-array-and-vice.html
Use the below code
// Convert an object to a byte array
private byte[] ObjectToByteArray(Object obj)
{
if(obj == null)
return null;
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, obj);
return ms.ToArray();
}
// Convert a byte array to an Object
private Object ByteArrayToObject(byte[] arrBytes)
{
MemoryStream memStream = new MemoryStream();
BinaryFormatter binForm = new BinaryFormatter();
memStream.Write(arrBytes, 0, arrBytes.Length);
memStream.Seek(0, SeekOrigin.Begin);
Object obj = (Object) binForm.Deserialize(memStream);
return obj;
}
I had the same problem when i have trying to read xml that was extracted from archive to memory stream.
MemoryStream SubSetupStream = new MemoryStream();
using (ZipFile archive = ZipFile.Read(zipPath))
{
archive.Password = "SomePass";
foreach (ZipEntry file in archive)
{
file.Extract(SubSetupStream);
}
}
Problem was in these lines:
XmlDocument doc = new XmlDocument();
doc.Load(SubSetupStream);
And solution is (Thanks to @Phil):
if (SubSetupStream.Position>0)
{
SubSetupStream.Position = 0;
}
The legend is part of the default options of the ChartJs library. So you do not need to explicitly add it as an option.
The library generates the HTML. It is merely a matter of adding that to the your page. For example, add it to the innerHTML of a given DIV. (Edit the default options if you are editing the colors, etc)
<div>
<canvas id="chartDiv" height="400" width="600"></canvas>
<div id="legendDiv"></div>
</div>
<script>
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "The Flash's Speed",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [65, 59, 80, 81, 56, 55, 40]
},
{
label: "Superman's Speed",
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(151,187,205,1)",
data: [28, 48, 40, 19, 86, 27, 90]
}
]
};
var myLineChart = new Chart(document.getElementById("chartDiv").getContext("2d")).Line(data);
document.getElementById("legendDiv").innerHTML = myLineChart.generateLegend();
</script>
From this excellent article on query locks in Postgres, one can get blocked query and blocker query and their information from the following query.
CREATE VIEW lock_monitor AS(
SELECT
COALESCE(blockingl.relation::regclass::text,blockingl.locktype) as locked_item,
now() - blockeda.query_start AS waiting_duration, blockeda.pid AS blocked_pid,
blockeda.query as blocked_query, blockedl.mode as blocked_mode,
blockinga.pid AS blocking_pid, blockinga.query as blocking_query,
blockingl.mode as blocking_mode
FROM pg_catalog.pg_locks blockedl
JOIN pg_stat_activity blockeda ON blockedl.pid = blockeda.pid
JOIN pg_catalog.pg_locks blockingl ON(
( (blockingl.transactionid=blockedl.transactionid) OR
(blockingl.relation=blockedl.relation AND blockingl.locktype=blockedl.locktype)
) AND blockedl.pid != blockingl.pid)
JOIN pg_stat_activity blockinga ON blockingl.pid = blockinga.pid
AND blockinga.datid = blockeda.datid
WHERE NOT blockedl.granted
AND blockinga.datname = current_database()
);
SELECT * from lock_monitor;
As the query is long but useful, the article author has created a view for it to simplify it's usage.
I use Weinre, part of Apache Cordova.
With Weinre, I get Google Chrome's debug console in my desktop browser, and can connect Android to that debug console, and debug HTML and CSS. I can execute Javascript commands in the console, and they affect the Web page in the Android browser. Log messages from Android appear in the desktop debug console.
However I think it's not possible to view or step through the actual Javascript code. So I combine Weinre with log messages.
(I don't know much about JConsole but it seems to me that HTML and CSS inspection isn't possible with JConsole, only Javascript commands and logging (?).)
In the __init__
method, self refers to the newly created object; in other class methods, it refers to the instance whose method was called.
self, as a name, is just a convention, call it as you want ! but when using it, for example to delete the object, you have to use the same name: __del__(var)
, where var
was used in the __init__(var,[...])
You should take a look at cls
too, to have the bigger picture. This post could be helpful.
Use the target
attribute on your anchor
tag with the _blank
value.
Example:
<a href="http://google.com" target="_blank">Click Me!</a>
Instead of selecting all the columns in count count(*) you can limit count for one column count(UserName).
You can limit the whole search to one row by using Limit 0,1
SELECT COUNT(UserName)
FROM TableName
WHERE UserName = 'User' AND
Password = 'Pass'
LIMIT 0, 1
Another project to have a look at: http://readthedocs.org/docs/django-private-files/en/latest/usage.html Looks promissing, haven't tested it myself yet tho.
Basically the project abstracts the mod_xsendfile configuration and allows you to do things like:
from django.db import models
from django.contrib.auth.models import User
from private_files import PrivateFileField
def is_owner(request, instance):
return (not request.user.is_anonymous()) and request.user.is_authenticated and
instance.owner.pk = request.user.pk
class FileSubmission(models.Model):
description = models.CharField("description", max_length = 200)
owner = models.ForeignKey(User)
uploaded_file = PrivateFileField("file", upload_to = 'uploads', condition = is_owner)
I had the same issue and i had it formatted into JSON as a String instead. Might be a bit of a hack but it's easy to implement.
private BigDecimal myValue = new BigDecimal("25.50");
...
public String getMyValue() {
return myValue.setScale(2, BigDecimal.ROUND_HALF_UP).toString();
}
I just learnt this myself the other day: the this keyword defines that method has being an extension of the class that proceeds it. So for your example, MyClass will have a new extension method called Foo (which doesn't accept any parameter and returns an int; it can be used as with any other public method).
Simple and best code:
def max_occ(lst,x):
count=0
for i in lst:
if (i==x):
count=count+1
return count
lst=[1, 2, 45, 55, 5, 4, 4, 4, 4, 4, 4, 5456, 56, 6, 7, 67]
x=max(lst,key=lst.count)
print(x,"occurs ",max_occ(lst,x),"times")
Output: 4 occurs 6 times
I'm debugging an issue I'm having with SSL connecting to a database (MySQL RDS) using an ORM called, Prisma. The database connection string requires a PKCS12 (.p12) file (if interested, described here), which brought me here.
I know the question has been answered, but I found the following steps (in Github Issue#2676) to be helpful for creating a .p12 file and wanted to share. Good luck!
Generate 2048-bit RSA private key:
openssl genrsa -out key.pem 2048
Generate a Certificate Signing Request:
openssl req -new -sha256 -key key.pem -out csr.csr
Generate a self-signed x509 certificate suitable for use on web servers.
openssl req -x509 -sha256 -days 365 -key key.pem -in csr.csr -out certificate.pem
Create SSL identity file in PKCS12 as mentioned here
openssl pkcs12 -export -out client-identity.p12 -inkey key.pem -in certificate.pem
As of TypeScript 0.9 (currently an alpha release) you can use the enum definition like this:
enum TShirtSize {
Small,
Medium,
Large
}
var mySize = TShirtSize.Large;
By default, these enumerations will be assigned 0, 1 and 2 respectively. If you want to explicitly set these numbers, you can do so as part of the enum declaration.
Listing 6.2 Enumerations with explicit members
enum TShirtSize {
Small = 3,
Medium = 5,
Large = 8
}
var mySize = TShirtSize.Large;
Both of these examples lifted directly out of TypeScript for JavaScript Programmers.
Note that this is different to the 0.8 specification. The 0.8 specification looked like this - but it was marked as experimental and likely to change, so you'll have to update any old code:
Disclaimer - this 0.8 example would be broken in newer versions of the TypeScript compiler.
enum TShirtSize {
Small: 3,
Medium: 5,
Large: 8
}
var mySize = TShirtSize.Large;
I think all of the answers here cover the core of what the lambda function does in the context of sorted() quite nicely, however I still feel like a description that leads to an intuitive understanding is lacking, so here is my two cents.
For the sake of completeness, I'll state the obvious up front: sorted() returns a list of sorted elements and if we want to sort in a particular way or if we want to sort a complex list of elements (e.g. nested lists or a list of tuples) we can invoke the key argument.
For me, the intuitive understanding of the key argument, why it has to be callable, and the use of lambda as the (anonymous) callable function to accomplish this comes in two parts.
Lambda syntax is as follows:
lambda input_variable(s): tasty one liner
e.g.
In [1]: f00 = lambda x: x/2
In [2]: f00(10)
Out[2]: 5.0
In [3]: (lambda x: x/2)(10)
Out[3]: 5.0
In [4]: (lambda x, y: x / y)(10, 2)
Out[4]: 5.0
In [5]: (lambda: 'amazing lambda')() # func with no args!
Out[5]: 'amazing lambda'
key
argument is that it should take in a set of instructions that will essentially point the 'sorted()' function at those list elements which should used to sort by. When it says key=
, what it really means is: As I iterate through the list one element at a time (i.e. for e in list), I'm going to pass the current element to the function I provide in the key argument and use that to create a transformed list which will inform me on the order of final sorted list. Check it out:
mylist = [3,6,3,2,4,8,23]
sorted(mylist, key=WhatToSortBy)
Base example:
sorted(mylist)
[2, 3, 3, 4, 6, 8, 23] # all numbers are in order from small to large.
Example 1:
mylist = [3,6,3,2,4,8,23]
sorted(mylist, key=lambda x: x%2==0)
[3, 3, 23, 6, 2, 4, 8] # Does this sorted result make intuitive sense to you?
Notice that my lambda function told sorted to check if (e) was even or odd before sorting.
BUT WAIT! You may (or perhaps should) be wondering two things - first, why are my odds coming before my evens (since my key value seems to be telling my sorted function to prioritize evens by using the mod operator in x%2==0
). Second, why are my evens out of order? 2 comes before 6 right? By analyzing this result, we'll learn something deeper about how the sorted() 'key' argument works, especially in conjunction with the anonymous lambda function.
Firstly, you'll notice that while the odds come before the evens, the evens themselves are not sorted. Why is this?? Lets read the docs:
Key Functions Starting with Python 2.4, both list.sort() and sorted() added a key parameter to specify a function to be called on each list element prior to making comparisons.
We have to do a little bit of reading between the lines here, but what this tells us is that the sort function is only called once, and if we specify the key argument, then we sort by the value that key function points us to.
So what does the example using a modulo return? A boolean value: True == 1
, False == 0
. So how does sorted deal with this key? It basically transforms the original list to a sequence of 1s and 0s.
[3,6,3,2,4,8,23] becomes [0,1,0,1,1,1,0]
Now we're getting somewhere. What do you get when you sort the transformed list?
[0,0,0,1,1,1,1]
Okay, so now we know why the odds come before the evens. But the next question is: Why does the 6 still come before the 2 in my final list? Well that's easy - its because sorting only happens once! i.e. Those 1s still represent the original list values, which are in their original positions relative to each other. Since sorting only happens once, and we don't call any kind of sort function to order the original even values from low to high, those values remain in their original order relative to one another.
The final question is then this: How do I think conceptually about how the order of my boolean values get transformed back in to the original values when I print out the final sorted list?
Sorted() is a built-in method that (fun fact) uses a hybrid sorting algorithm called Timsort that combines aspects of merge sort and insertion sort. It seems clear to me that when you call it, there is a mechanic that holds these values in memory and bundles them with their boolean identity (mask) determined by (...!) the lambda function. The order is determined by their boolean identity calculated from the lambda function, but keep in mind that these sublists (of one's and zeros) are not themselves sorted by their original values. Hence, the final list, while organized by Odds and Evens, is not sorted by sublist (the evens in this case are out of order). The fact that the odds are ordered is because they were already in order by coincidence in the original list. The takeaway from all this is that when lambda does that transformation, the original order of the sublists are retained.
So how does this all relate back to the original question, and more importantly, our intuition on how we should implement sorted() with its key argument and lambda?
That lambda function can be thought of as a pointer that points to the values we need to sort by, whether its a pointer mapping a value to its boolean transformed by the lambda function, or if its a particular element in a nested list, tuple, dict, etc., again determined by the lambda function.
Lets try and predict what happens when I run the following code.
mylist = [(3, 5, 8), (6, 2, 8), ( 2, 9, 4), (6, 8, 5)]
sorted(mylist, key=lambda x: x[1])
My sorted
call obviously says, "Please sort this list". The key argument makes that a little more specific by saying, for each element (x) in mylist, return index 1 of that element, then sort all of the elements of the original list 'mylist' by the sorted order of the list calculated by the lambda function. Since we have a list of tuples, we can return an indexed element from that tuple. So we get:
[(6, 2, 8), (3, 5, 8), (6, 8, 5), (2, 9, 4)]
Run that code, and you'll find that this is the order. Try indexing a list of integers and you'll find that the code breaks.
This was a long winded explanation, but I hope this helps to 'sort' your intuition on the use of lambda functions as the key argument in sorted() and beyond.
To summarize a few items here: There are some pixel-by-pixel options that, while being simple just aren't fast.
@Luis' comment linking to: (archived) https://web.archive.org/web/20110827032809/http://www.switchonthecode.com/tutorials/csharp-tutorial-convert-a-color-image-to-grayscale is superb.
He runs through three different options and includes timings for each.
In Swift, You can get the locale using.
let locale = Locale.current.identifier
In my case, I named a column name type
and tried to set its value as UNPREPARED
. And I got an error message like this:
Caused by: api_1 | NameError: uninitialized constant UNPREPARED
In rails, column type
is reserved:
ActiveRecord::SubclassNotFound: The single-table inheritance mechanism failed to locate the subclass: 'UNPREPARED'. This error is raised because the column 'type' is reserved for storing the class in case of inheritance. Pl ease rename this column if you didn't intend it to be used for storing the inheritance class or overwrite Food.inheritance_column to use another column for that information
If you want to change anything else instead of 'default', then just add these additional lines to your Vagrantfile:
config.vm.define "tendo" do |tendo|
end
Where "tendo" will be the name that will appear instead of default
import itertools
a = [['a','b'], ['c']]
print(list(itertools.chain.from_iterable(a)))
I also encountered the same issue. The best way to resolve is (for windows):
Go to the Task Manager.
Scroll and find a task process named. Node.js: Server-side JavaScript
End this particular task.
There you go! Now do npm start and it will work as before!
Based on @Sailesh and @DavidCulp:
(on branch development)
$ git fetch origin master
$ git merge FETCH_HEAD
(resolve any merge conflicts if there are any)
$ git checkout master
$ git merge --no-ff development (there won't be any conflicts now)
The first command will make sure you have all upstream commits made to remote master, with Sailesh response that would not happen.
The second will perform a merge and create conflicts that you can then resolve.
After doing so, you can finally checkout master to switch to master.
Then you merge the development branch onto the local master. The no-ff flag will create a commit node in master for the whole merge to be trackable.
After that you can commit and push your merge.
This procedure will make sure there's a merge commit from development to master that people can see, then if they go look at the development branch they can see the individual commits you've made to that branch during its development.
Optionally, you can amend your merge commit before you push it, if you want to add a summary of what was done in the development branch.
EDIT: my original answer suggested a git merge master
which didn't do anything, it's better to do git merge FETCH_HEAD
after fetching the origin/master
Sometimes we need a single way to check it. typeof not working for date etc. So I made it easy by
Date.prototype.getType() { return "date"; }
Also for Number
, String
, Boolean
etc. we often need to check the type in a single way...
The problem in my case was that I entered a value IN THE LAST NOT DISABLED ELEMENT of the site and used tab to raise the onChange-Event. After that there is no next element to get the focus, so the "browser"-Focus switches to the browser-functionality (tabs, menu, and so on) and is not any longer inside the html-content.
To understand that, place a displayed, not disabled dummy-textbox at the end of your html-code. In that you can "park" the focus for later replacing. Should work. In my case. All other tries didnt work, also the setTimeout-Version.
Checked this out for about an hour, because it made me insane :)
Mätes
You can use the CSS property max-width
and use it with ch
unit.
And, as this is a <span>
, use a display: inline-block;
(or block).
Here is an example:
<span style="
display:inline-block;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 13ch;">
Lorem ipsum dolor sit amet
</span>
Which outputs:
Lorem ipsum...
<span style="_x000D_
display:inline-block;_x000D_
white-space: nowrap;_x000D_
overflow: hidden;_x000D_
text-overflow: ellipsis;_x000D_
max-width: 13ch;">_x000D_
Lorem ipsum dolor sit amet_x000D_
</span>
_x000D_
The problem is, os.path.join
doesn't take a list
as argument, it has to be separate arguments.
This is where *
, the 'splat' operator comes into play...
I can do
>>> s = "c:/,home,foo,bar,some.txt".split(",")
>>> os.path.join(*s)
'c:/home\\foo\\bar\\some.txt'
I know that there are accepted answer but still, I want to share my scenario that maybe help someone to solve their problem TOOLS
SCENARIO
i was loading the dataset which's in CSV format which was later to be shown on the View
i tried to use the bulk load but I's unable to load as BULK LOAD
was using
FIELDTERMINATOR = ','
and Excel cell was also using ,
however, I also couldn't use Flat file source
directly because I was using Code-First Approach
and doing that only made model in SSMS DB, not in the model from which I had to use the properties later.
SOLUTION
Add-Migration
in NuGet package console (magento 2 example provided below)
sectionName, groupName and fieldName are present in etc/system.xml file of the module.
PHP Syntax:
Mage::getStoreConfig('sectionName/groupName/fieldName');
From within an editor in the admin, such as the content of a CMS Page or Static Block; the description/short description of a Catalog Category, Catalog Product, etc.
{{config path="sectionName/groupName/fieldName"}}
For the "Within an editor" approach to work, the field value must be passed through a filter for the {{ ... }} contents to be parsed out. Out of the box, Magento will do this for Category and Product descriptions, as well as CMS Pages and Static Blocks. However, if you are outputting the content within your own custom view script and want these variables to be parsed out, you can do so like this:
<?php
$example = Mage::getModel('identifier/name')->load(1);
$filter = Mage::getModel('cms/template_filter');
echo $filter->filter($example->getData('field'));
?>
Replacing identifier/name with the a appropriate values for the model you are loading, and field with the name of the attribute you want to output, which may contain {{ ... }} occurrences that need to be parsed out.
From any Block class that extends \Magento\Framework\View\Element\AbstractBlock
$this->_scopeConfig->getValue('sectionName/groupName/fieldName');
Any other PHP class:
If the class (and none of it's parent's) does not inject \Magento\Framework\App\Config\ScopeConfigInterface
via the constructor, you'll have to add it to your class.
// ... Remaining class definition above...
/**
* @var \Magento\Framework\App\Config\ScopeConfigInterface
*/
protected $_scopeConfig;
/**
* Constructor
*/
public function __construct(
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
// ...any other injected classes the class depends on...
) {
$this->_scopeConfig = $scopeConfig;
// Remaining constructor logic...
}
// ...remaining class definition below...
Once you have injected it into your class, you can now fetch store configuration values with the same syntax example given above for block classes.
Note that after modifying any class's __construct() parameter list, you may have to clear your generated classes as well as dependency injection directory: var/generation
& var/di
To differentiate between scroll up/down in jQuery, you could use:
var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
$('#yourDiv').bind(mousewheelevt, function(e){
var evt = window.event || e //equalize event object
evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible
var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF
if(delta > 0) {
//scroll up
}
else{
//scroll down
}
});
This method also works in divs that have overflow:hidden
.
I successfully tested it in FireFox, IE and Chrome.
i have tried upgrading node-gyp:
sudo npm install -g node-gyp
It worked for me.
I find the solution here, I hope it can help.
Post is the most secured along with SSL installed because its transmitted in the message body.
But all of these methods are insecure because the 7 bit protocol it uses underneath it is hack-able with escapement. Even through a level 4 web application firewall.
Sockets are no guarantee either... Even though its more secure in certain ways.
the lines
account.withdraw(balance, 2500);
account.deposit(balance, 3000);
you might want to make withdraw and deposit non-static and let it modify the balance
public void withdraw(double withdrawAmount) {
balance = balance - withdrawAmount;
}
public void deposit(double depositAmount) {
balance = balance + depositAmount;
}
and remove the balance parameter from the call
My project of spring-boot has run normally according to your assistance. The yaml datasource configuration is:
spring:
# (DataSourceAutoConfiguration & DataSourceProperties)
datasource:
name: ds-h2
url: jdbc:h2:D:/work/workspace/fdata;DATABASE_TO_UPPER=false
username: h2
password: h2
driver-class: org.h2.Driver
Custom DataSource
@Configuration
@Component
public class DataSourceBean {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
@Primary
public DataSource getDataSource() {
return DataSourceBuilder
.create()
// .url("jdbc:h2:D:/work/workspace/fork/gs-serving-web-content/initial/data/fdata;DATABASE_TO_UPPER=false")
// .username("h2")
// .password("h2")
// .driverClassName("org.h2.Driver")
.build();
}
}
I think it is fine because I've seen many people doing this way.
If you are just defining the event handler within the directive, you do not have to define it on the scope, though. Following would be fine.
myApp.directive('clickme', function() {
return function(scope, element, attrs) {
var clickingCallback = function() {
alert('clicked!')
};
element.bind('click', clickingCallback);
}
});
You can add a custom function to the $http
service using a "decorator" that would add the abort()
function to your promises.
Here's some working code:
app.config(function($provide) {
$provide.decorator('$http', function $logDecorator($delegate, $q) {
$delegate.with_abort = function(options) {
let abort_defer = $q.defer();
let new_options = angular.copy(options);
new_options.timeout = abort_defer.promise;
let do_throw_error = false;
let http_promise = $delegate(new_options).then(
response => response,
error => {
if(do_throw_error) return $q.reject(error);
return $q(() => null); // prevent promise chain propagation
});
let real_then = http_promise.then;
let then_function = function () {
return mod_promise(real_then.apply(this, arguments));
};
function mod_promise(promise) {
promise.then = then_function;
promise.abort = (do_throw_error_param = false) => {
do_throw_error = do_throw_error_param;
abort_defer.resolve();
};
return promise;
}
return mod_promise(http_promise);
}
return $delegate;
});
});
This code uses angularjs's decorator functionality to add a with_abort()
function to the $http
service.
with_abort()
uses $http
timeout option that allows you to abort an http request.
The returned promise is modified to include an abort()
function. It also has code to make sure that the abort()
works even if you chain promises.
Here is an example of how you would use it:
// your original code
$http({ method: 'GET', url: '/names' }).then(names => {
do_something(names));
});
// new code with ability to abort
var promise = $http.with_abort({ method: 'GET', url: '/names' }).then(
function(names) {
do_something(names));
});
promise.abort(); // if you want to abort
By default when you call abort()
the request gets canceled and none of the promise handlers run.
If you want your error handlers to be called pass true to abort(true)
.
In your error handler you can check if the "error" was due to an "abort" by checking the xhrStatus
property. Here's an example:
var promise = $http.with_abort({ method: 'GET', url: '/names' }).then(
function(names) {
do_something(names));
},
function(error) {
if (er.xhrStatus === "abort") return;
});
adb kill-server will kill all emulators and restart the server clean.
You might try using my mailer module.
from mailer import Mailer
from mailer import Message
message = Message(From="[email protected]",
To="[email protected]")
message.Subject = "An HTML Email"
message.Html = """<p>Hi!<br>
How are you?<br>
Here is the <a href="http://www.python.org">link</a> you wanted.</p>"""
sender = Mailer('smtp.example.com')
sender.send(message)
The benefit of a generator expression is that it uses less memory since it doesn't build the whole list at once. Generator expressions are best used when the list is an intermediary, such as summing the results, or creating a dict out of the results.
For example:
sum(x*2 for x in xrange(256))
dict( (k, some_func(k)) for k in some_list_of_keys )
The advantage there is that the list isn't completely generated, and thus little memory is used (and should also be faster)
You should, though, use list comprehensions when the desired final product is a list. You are not going to save any memeory using generator expressions, since you want the generated list. You also get the benefit of being able to use any of the list functions like sorted or reversed.
For example:
reversed( [x*2 for x in xrange(256)] )
You just declared a jagged array. Such kind of arrays can have different sizes for all dimensions. For example:
string[][] jaggedStrings = {
new string[] {"x","y","z"},
new string[] {"x","y"},
new string[] {"x"}
};
In your case you need regular array. See answers above. More about jagged arrays
var checked = []
$("input[name='options[]']:checked").each(function ()
{
checked.push(parseInt($(this).val()));
});
simply add + "<br />" +
is enough for a line break
I had this problem in windows. Most of the answers are not as recommended by anaconda, you should not add the path to the environment variables as it can break other things. Instead you should use anaconda prompt as mentioned in the top answer.
However, this may also break. In this case right click on the shortcut, go to shortcut tab, and the target value should read something like:
%windir%\System32\cmd.exe "/K" C:\Users\myUser\Anaconda3\Scripts\activate.bat C:\Users\myUser\Anaconda3
Got the error (in the function init) with the following code ;
"use strict" ;
var hdr ;
function init(){ // called on load
hdr = document.getElementById("hdr");
}
... while using the stock browser on a Samsung galaxy Fame ( crap phone which makes it a good tester ) - userAgent ; Mozilla/5.0 (Linux; U; Android 4.1.2; en-gb; GT-S6810P Build/JZO54K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30
The same code works everywhere else I tried including the stock browser on an older HTC phone - userAgent ; Mozilla/5.0 (Linux; U; Android 2.3.5; en-gb; HTC_WildfireS_A510e Build/GRJ90) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1
The fix for this was to change
var hdr ;
to
var hdr = null ;
The easiest solution I found for this:
git commit -m "fixing merge conflicts"
git push
An additional option is to go to your build folder and use the command ccmake .
This is like the GUI but terminal based. This obviously won't help with an installation script but at least it can be run without a UI.
The one warning I have is it won't let you generate sometimes when you have warnings. if that is the case, exit the interface and call cmake .
As per the comments in the question... On Windows 10 Signtool.exe and other SDK tools have been moved into "%programfiles(x86)%\Windows Kits\".
Typical path to signtool on Windows 10.
Tools for SDK 8.0 and 8.1 also reside in the "Windows Kits" folder.
I use this:
function round(value, precision) {_x000D_
_x000D_
if(precision == 0)_x000D_
return Math.round(value); _x000D_
_x000D_
exp = 1;_x000D_
for(i=0;i<precision;i++)_x000D_
exp *= 10;_x000D_
_x000D_
return Math.round(value*exp)/exp;_x000D_
}
_x000D_
First off, EC2 and Elastic Compute Cloud are the same thing.
Next, AWS encompasses the range of Web Services that includes EC2 and Elastic Beanstalk. It also includes many others such as S3, RDS, DynamoDB, and all the others.
EC2 is Amazon's service that allows you to create a server (AWS calls these instances) in the AWS cloud. You pay by the hour and only what you use. You can do whatever you want with this instance as well as launch n
number of instances.
Elastic Beanstalk is one layer of abstraction away from the EC2 layer. Elastic Beanstalk will setup an "environment" for you that can contain a number of EC2 instances, an optional database, as well as a few other AWS components such as a Elastic Load Balancer, Auto-Scaling Group, Security Group. Then Elastic Beanstalk will manage these items for you whenever you want to update your software running in AWS. Elastic Beanstalk doesn't add any cost on top of these resources that it creates for you. If you have 10 hours of EC2 usage, then all you pay is 10 compute hours.
For running Wordpress, it is whatever you are most comfortable with. You could run it straight on a single EC2 instance, you could use a solution from the AWS Marketplace, or you could use Elastic Beanstalk.
In the case that you want to reduce system operations and just focus on the website, then Elastic Beanstalk would be the best choice for that. Elastic Beanstalk supports a PHP stack (as well as others). You can keep your site in version control and easily deploy to your environment whenever you make changes. It will also setup an Autoscaling group which can spawn up more EC2 instances if traffic is growing.
Here's the first result off of Google when searching for "elastic beanstalk wordpress": https://www.otreva.com/blog/deploying-wordpress-amazon-web-services-aws-ec2-rds-via-elasticbeanstalk/
If your constraint is on a user type, then don't forget to see if there is a Default Constraint
, usually something like DF__TableName__ColumnName__6BAEFA67
, if so then you will need to drop the Default Constraint
, like this:
ALTER TABLE TableName DROP CONSTRAINT [DF__TableName__ColumnName__6BAEFA67]
For more info see the comments by the brilliant Aaron Bertrand on this answer.
You actually can't manually "free" memory in C, in the sense that the memory is released from the process back to the OS ... when you call malloc()
, the underlying libc-runtime will request from the OS a memory region. On Linux, this may be done though a relatively "heavy" call like mmap()
. Once this memory region is mapped to your program, there is a linked-list setup called the "free store" that manages this allocated memory region. When you call malloc()
, it quickly looks though the free-store for a free block of memory at the size requested. It then adjusts the linked list to reflect that there has been a chunk of memory taken out of the originally allocated memory pool. When you call free()
the memory block is placed back in the free-store as a linked-list node that indicates its an available chunk of memory.
If you request more memory than what is located in the free-store, the libc-runtime will again request more memory from the OS up to the limit of the OS's ability to allocate memory for running processes. When you free memory though, it's not returned back to the OS ... it's typically recycled back into the free-store where it can be used again by another call to malloc()
. Thus, if you make a lot of calls to malloc()
and free()
with varying memory size requests, it could, in theory, cause a condition called "memory fragmentation", where there is enough space in the free-store to allocate your requested memory block, but not enough contiguous space for the size of the block you've requested. Thus the call to malloc()
fails, and you're effectively "out-of-memory" even though there may be plenty of memory available as a total amount of bytes in the free-store.
Use String.substring(beginIndex, endIndex)
str.substring(0, str.length() - 2);
The substring begins at the specified beginIndex and extends to the character at index (endIndex - 1)
If all you need is a subject line (as in an alert message) simply do:
mailx -s "This is all she wrote" < /dev/null "myself@myaddress"
Can you assign a unique CSS class to each distinct timer? That way you could use the selector for the CSS class, which would work fine with multiple div
elements.
For those using NHibernate, this is a port of [ram]'s code
public static string GenerateSQL(ICriteria criteria)
{
NHibernate.Impl.CriteriaImpl criteriaImpl = (NHibernate.Impl.CriteriaImpl)criteria;
NHibernate.Engine.ISessionImplementor session = criteriaImpl.Session;
NHibernate.Engine.ISessionFactoryImplementor factory = session.Factory;
NHibernate.Loader.Criteria.CriteriaQueryTranslator translator =
new NHibernate.Loader.Criteria.CriteriaQueryTranslator(
factory,
criteriaImpl,
criteriaImpl.EntityOrClassName,
NHibernate.Loader.Criteria.CriteriaQueryTranslator.RootSqlAlias);
String[] implementors = factory.GetImplementors(criteriaImpl.EntityOrClassName);
NHibernate.Loader.Criteria.CriteriaJoinWalker walker = new NHibernate.Loader.Criteria.CriteriaJoinWalker(
(NHibernate.Persister.Entity.IOuterJoinLoadable)factory.GetEntityPersister(implementors[0]),
translator,
factory,
criteriaImpl,
criteriaImpl.EntityOrClassName,
session.EnabledFilters);
return walker.SqlString.ToString();
}
For Windows User, alternative solution to remove such folder listed here: http://ask.osify.com/qa/567
Among them, a free tool: Long Path Fixer is good to try: http://corz.org/windows/software/accessories/Long-Path-Fixer-for-Windows.php
The process can differ depending on where and how the video is being hosted. Knowing that can help to answer the question in more detail.
As an example; this is how you can download videos with blob links on Vimeo.
You cannot iterate backwards with the jQuery each function, but you can still leverage jQuery syntax.
Try the following:
//get an array of the matching DOM elements
var liItems = $("ul#myUL li").get();
//iterate through this array in reverse order
for(var i = liItems.length - 1; i >= 0; --i)
{
//do Something
}
If choice
is available, use this:
choice /C X /T 10 /D X > nul
where /T 10
is the number of seconds to delay.
Note the syntax can vary depending on your Windows version, so use CHOICE /?
to be sure.
I'm afraid Roman Luštrik's answer is wrong. It works on this input by chance. Consider for example its output on a very similar input (with an additional line similar to the original line 3 with "c" in the I2 column):
rum <- read.table(textConnection("P1 P2 P3 T1 T2 T3 I1 I2
2 3 5 52 43 61 6 b
6 4 3 72 NA 59 1 a
1 5 6 55 48 60 6 f
2 4 4 65 64 58 2 b
1 5 6 55 48 60 6 c"), header = TRUE)
rum$I2 <- as.character(rum$I2)
rum[order(rum$I1, rev(rum$I2), decreasing = TRUE), ]
P1 P2 P3 T1 T2 T3 I1 I2
3 1 5 6 55 48 60 6 f
1 2 3 5 52 43 61 6 b
5 1 5 6 55 48 60 6 c
4 2 4 4 65 64 58 2 b
2 6 4 3 72 NA 59 1 a
This is not the desired result: the first three values of I2 are f b c
instead of b c f
, which would be expected since the secondary sort is I2 in ascending order.
To get the reverse order of I2, you want the large values to be small and vice versa. For numeric values multiplying by -1 will do it, but for characters its a bit more tricky. A general solution for characters/strings would be to go through factors, reverse the levels (to make large values small and small values large) and change the factor back to characters:
rum <- read.table(textConnection("P1 P2 P3 T1 T2 T3 I1 I2
2 3 5 52 43 61 6 b
6 4 3 72 NA 59 1 a
1 5 6 55 48 60 6 f
2 4 4 65 64 58 2 b
1 5 6 55 48 60 6 c"), header = TRUE)
f=factor(rum$I2)
levels(f) = rev(levels(f))
rum[order(rum$I1, as.character(f), decreasing = TRUE), ]
P1 P2 P3 T1 T2 T3 I1 I2
1 2 3 5 52 43 61 6 b
5 1 5 6 55 48 60 6 c
3 1 5 6 55 48 60 6 f
4 2 4 4 65 64 58 2 b
2 6 4 3 72 NA 59 1 a
PHP sends headers automatically if set up to use internal encoding:
ini_set('default_charset', 'utf-8');
Another option is to change the text color (to light gray for example) for the disabled state.
In the storyboard editor, choose Disabled
from the State Config
popup button. Use the Text Color
popup button to change the text color.
In code, use the -setTitleColor:forState:
message.
In SQL server, use:
select top 10 ...
e.g.
select top 100 * from myTable
select top 100 colA, colB from myTable
In MySQL, use:
select ... order by num desc limit 10
You can use this simple code for rate your app in your activity.
try {
Uri uri = Uri.parse("market://details?id=" + getPackageName());
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
startActivity(goToMarket);
} catch (ActivityNotFoundException e) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=" + getPackageName())));
}
$(".excel").click(function () {
var t = $(this).closest(".tblGrid").attr("id");
window.frames["Iframe" + t].document.location.href = pagename + "?tbl=" + t;
});
this is what i use, no jquery needed for this. in this particular scenario for each table i have with an excel export icon this forces the iframe attached to that table to load the same page with a variable in the Query String that the page looks for, and if found response writes out a stream with an excel mimetype and includes the data for that table.
I was getting the same error while connecting my "hr" user of ORCLPDB which is a pluggable database.
First, get hostname and port number by typing a command lsnrctl status
on windows command prompt. In my case, it was 127.0.0.1 with port number as 1521
Second, enter the below command with your hostname and port number:
sqlplus username/password@HostName:Port Number/PluggableDatabaseName.
For example:
sqlplus hr/[email protected]:1521/ORCLPDB.
I installed pysocks and monkey patched create_connection in urllib3, like this:
import socks
import socket
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS4, "127.0.0.1", 1080)
def create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
source_address=None, socket_options=None):
"""Connect to *address* and return the socket object.
Convenience function. Connect to *address* (a 2-tuple ``(host,
port)``) and return the socket object. Passing the optional
*timeout* parameter will set the timeout on the socket instance
before attempting to connect. If no *timeout* is supplied, the
global default timeout setting returned by :func:`getdefaulttimeout`
is used. If *source_address* is set it must be a tuple of (host, port)
for the socket to bind as a source address before making the connection.
An host of '' or port 0 tells the OS to use the default.
"""
host, port = address
if host.startswith('['):
host = host.strip('[]')
err = None
for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res
sock = None
try:
sock = socks.socksocket(af, socktype, proto)
# If provided, set socket level options before connecting.
# This is the only addition urllib3 makes to this function.
urllib3.util.connection._set_socket_options(sock, socket_options)
if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:
sock.settimeout(timeout)
if source_address:
sock.bind(source_address)
sock.connect(sa)
return sock
except socket.error as e:
err = e
if sock is not None:
sock.close()
sock = None
if err is not None:
raise err
raise socket.error("getaddrinfo returns an empty list")
# monkeypatch
urllib3.util.connection.create_connection = create_connection
Try Project Euler:
Project Euler is a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve. Although mathematics will help you arrive at elegant and efficient methods, the use of a computer and programming skills will be required to solve most problems.
The problem is:
Add all the natural numbers below 1000 that are multiples of 3 or 5.
This question will probably introduce you to Python for-loops and the range() builtin function in the least. It might lead you to discover list comprehensions, or generator expressions and the sum() builtin function.
<?php foreach ($sidemenus->mname as $sidemenu): ?>
<?php echo $sidemenu ."<br />";?>
or
$sidemenus = mysql_fetch_array($results);
then
<?php echo $sidemenu['mname']."<br />";?>
Let's concentrate on methods, which are responsible for the UIViewController's lifecycle:
Creation:
- (void)init
- (void)initWithNibName:
View creation:
- (BOOL)isViewLoaded
- (void)loadView
- (void)viewDidLoad
- (UIView *)initWithFrame:(CGRect)frame
- (UIView *)initWithCoder:(NSCoder *)coder
Handling of view state changing:
- (void)viewDidLoad
- (void)viewWillAppear:(BOOL)animated
- (void)viewDidAppear:(BOOL)animated
- (void)viewWillDisappear:(BOOL)animated
- (void)viewDidDisappear:(BOOL)animated
- (void)viewDidUnload
Memory warning handling:
- (void)didReceiveMemoryWarning
Deallocation
- (void)viewDidUnload
- (void)dealloc
For more information please take a look on UIViewController Class Reference.
There are a couple of ways that you can accomplish this. You can do the following:
<li>
@Html.ActionLink("Clients", "Index", "User", new { @class = "elements" }, null)
</li>
or this:
<li>
<a href="@Url.Action("Index", "Users")" class="elements">
<span>Clients</span>
</a>
</li>
Lately I do the following:
<a href="@Url.Action("Index", null, new { area = string.Empty, controller = "User" }, Request.Url.Scheme)">
<span>Clients</span>
</a>
The result would have http://localhost/10000
(or with whatever port you are using) to be appended to the URL structure like:
http://localhost:10000/Users
I hope this helps.
Backticks will run the command on the local shell and put the results on the command line. What you're saying is 'execute ./test/foo.sh and then pass the output as if I'd typed it on the commandline here'.
Try the following command, and make sure that thats the path from your home directory on the remote computer to your script.
ssh kev@server1 './test/foo.sh'
Also, the script has to be on the remote computer. What this does is essentially log you into the remote computer with the listed command as your shell. You can't run a local script on a remote computer like this (unless theres some fun trick I don't know).
$duplicate = false;
if(count(array) != count(array_unique(array))){
$duplicate = true;
}
git config
allows to specify a config file.
And .gitmodules
is a config file.
So, with the help of "use space as a delimiter with cut command":
git config --file=.gitmodules --get-regexp ^^submodule.*\.path$ | cut -d " " -f 2
That will list only the paths, one per declared submodule.
As Tino points out in the comments:
- This fails for submodules with spaces in it.
submodule paths may contain newlines, as in
git submodule add https://github.com/hilbix/bashy.git "sub module" git mv 'sub module' $'sub\nmodule'
As a more robust alternative, Tino proposes:
git config -z --file .gitmodules --get-regexp '\.path$' | \ sed -nz 's/^[^\n]*\n//p' | \ tr '\0' '\n'
For paths with newlines in them (they can be created with
git mv
), leave away the| tr '\0' '\n'
and use something like... | while IFS='' read -d '' path; do ...
for further processing with bash.
This needs a modern bash which understandsread -d ''
(do not forget the space between-d and ''
).
This is how I did it:
$str = file_get_contents("my-code-file.php");
echo "<textarea disabled='true' style='border: none;background-color:white;'>";
echo $str;
echo "</textarea>";
Many times, we need to hide some parts of codes while writing a long code.
Example: - Just on clicking "Code show/hide", we can hide 3 lines of codes.
So here is the function that you need to define for partially hiding few part of codes and then call it whenever you want to hide some code:
from IPython.display import HTML
def hide_toggle(for_next=False):
this_cell = """$('div.cell.code_cell.rendered.selected')""" ; next_cell = this_cell + '.next()';
toggle_text = 'Code show/hide' # text shown on toggle link
target_cell = this_cell ; js_hide_current = ''
if for_next:
target_cell = next_cell; toggle_text += ' next cell';
js_hide_current = this_cell + '.find("div.input").hide();'
js_f_name = 'code_toggle_{}'.format(str(random.randint(1,2**64)))
html = """<script>
function {f_name}() {{{cell_selector}.find('div.input').toggle(); }}
{js_hide_current}
</script>
<a href="javascript:{f_name}()">{toggle_text}</a>
""".format(f_name=js_f_name,cell_selector=target_cell,js_hide_current=js_hide_current, toggle_text=toggle_text )
return HTML(html)
Once we are ready with function definition, our next task is very easy. Just we need to call the function to hide/show the code.
print("Function for hiding the cell")
hide_toggle()
I did a quick test in both node and chrome and found in both cases +=
is faster:
var profile = func => {
var start = new Date();
for (var i = 0; i < 10000000; i++) func('test');
console.log(new Date() - start);
}
profile(x => "testtesttesttesttest");
profile(x => `${x}${x}${x}${x}${x}`);
profile(x => x + x + x + x + x );
profile(x => { var s = x; s += x; s += x; s += x; s += x; return s; });
profile(x => [x, x, x, x, x].join(""));
profile(x => { var a = [x]; a.push(x); a.push(x); a.push(x); a.push(x); return a.join(""); });
results in node: 7.0.10
results from chrome 86.0.4240.198:
import urllib.request as ur
s = ur.urlopen("http://www.google.com")
sl = s.read()
print(sl)
In Python v3 the "urllib.request" is a module by itself, therefore "urllib" cannot be used here.
Use google guava Multiset<String>
.
Multiset<String> wordsMultiset = HashMultiset.create();
wordsMultiset.addAll(words);
for(Multiset.Entry<E> entry:wordsMultiset.entrySet()){
System.out.println(entry.getElement()+" - "+entry.getCount());
}
If you are OK with converting the input button to a server side control by specifying runat="server"
, and you are using asp.net
, an option could be using the HtmlButton.OnServerClick property.
<input id="foo "runat="server" type="button" onserverclick="foo_OnClick" />
This should work and call foo_OnClick
in your server side code.
Also notice that based on Microsoft documentation linked above, you should also be able to use the HTML 4.0 tag.
I've generalized Piotr Stapp's JavaScript/jQuery method a bit further, encapsulating it into a function and generalizing it a bit.
This function uses the RabbitMQ HTTP API to query available queues in a given vhost
, and then delete them based on an optional queuePrefix
:
function deleteQueues(vhost, queuePrefix) {
if (vhost === '/') vhost = '%2F'; // html encode forward slashes
$.ajax({
url: '/api/queues/'+vhost,
success: function(result) {
$.each(result, function(i, queue) {
if (queuePrefix && !queue.name.startsWith(queuePrefix)) return true;
$.ajax({
url: '/api/queues/'+vhost+'/'+queue.name,
type: 'DELETE',
success: function(result) { console.log('deleted '+ queue.name)}
});
});
}
});
};
Once you paste this function in your browser's JavaScript console while on your RabbitMQ management page, you can use it like this:
Delete all queues in '/' vhost
deleteQueues('/');
Delete all queues in '/' vhost beginning with 'test'
deleteQueues('/', 'test');
Delete all queues in 'dev' vhost beginning with 'foo'
deleteQueues('dev', 'foo');
Please use this at your own risk!
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
int i, parameter = 0;
if (argc >= 2) {
/* there is 1 parameter (or more) in the command line used */
/* argv[0] may point to the program name */
/* argv[1] points to the 1st parameter */
/* argv[argc] is NULL */
parameter = atoi(argv[1]); /* better to use strtol */
if (parameter > 0) {
for (i = 0; i < parameter; i++) printf("%d ", i);
} else {
fprintf(stderr, "Please use a positive integer.\n");
}
}
return 0;
}
In C#, they are interchangeable (although method is the proper term) because you cannot write a method without incorporating it into a class. If it were independent of a class, then it would be a function. Methods are functions that operate through a designated class.
Solution using the destructuring assignment syntax of ES6:
var temp = { 'a' : 'apple', 'b' : 'banana', 'c' : 'carrot' };_x000D_
var { [Object.keys(temp).pop()]: lastItem } = temp;_x000D_
console.info(lastItem); //"carrot"
_x000D_
While there might be a way I would tend to keep that kind of logic out of the Model. I agree that you shouldn't put that in the view (keep it skinny) but unless the model is returning a url as a piece of data to the controller, the routing stuff should be in the controller.
Set the colspan
attribute to 2.
Simply put:
.democlass {
background-color: rgba(246,245,245,0);
}
That should give you a transparent background.
If you wish to use "like" as a parameter your link needs to be:
<a href="/topic.php?like=like">Like</a>
More likely though is that you want:
<a href="/topic.php?id=14&like=like">Like</a>
string input = Console.ReadLine();
double d;
if (!Double.TryParse(input, out d))
Console.WriteLine("Wrong input");
double r = d * Math.Pi;
Console.WriteLine(r);
The main reason of different input/output you're facing is that Console.Read()
returns char code, not a number you typed! Learn how to use MSDN.
using user 113716 solution, which by the way is great to avoid all those if-else I have implemented it this way to calculate my subtotal textbox from textbox unit and textbox quantity.
In the process writing of non numbers in unit and quantity textboxes, their values are bing replace by zero so final posting of user data has no non-numbers .
<script src="/common/tools/jquery-1.10.2.js"></script>
<script src="/common/tools/jquery-ui.js"></script>
<!----------------- link above 2 lines to your jquery files ------>
<script type="text/javascript" >
function calculate_subtotal(){
$('#quantity').val((+$('#quantity').val() || 0));
$('#unit').val((+$('#unit').val() || 0));
var calculated = $('#quantity').val() * $('#unit').val() ;
$('#subtotal').val(calculated);
}
</script>
<input type = "text" onChange ="calculate_subtotal();" id = "quantity"/>
<input type = "text" onChange ="calculate_subtotal();" id = "unit"/>
<input type = "text" id = "subtotal"/>
pip install --ignore-installed --upgrade --user tensorflow==2.0.1
Here 2.0.1 is the version of tensorflow.
After having tried most of what I could read in this thread without success, I stumbled across this one: Remote branch not showing up in "git branch -r"
It turned out that my .git/config file was incorrect. After doing a simple fix all branches showed up.
Going from
[remote "origin"]
url = http://stash.server.com/scm/EX/project.git
fetch = +refs/heads/master:refs/remotes/origin/master
to
[remote "origin"]
url = http://stash.server.com/scm/EX/project.git
fetch = +refs/heads/*:refs/remotes/origin/*
Did the trick
$this->db1->where('tennant_id', $tennant_id);
$this->db1->order_by('id', 'DESC');
return $this->db1->get('courses')->result();
<xsl:variable name="count" select="count(/Property/long = $parPropId)"/>
Un-tested but I think that should work. I'm assuming the Property nodes are direct children of the root node and therefor taking out your descendant selector for peformance
These lines in your makefile,
INC_DIR = ../StdCUtil
CFLAGS=-c -Wall -I$(INC_DIR)
DEPS = split.h
and this line in your .cpp file,
#include "StdCUtil/split.h"
are in conflict.
With your makefile in your source directory and with that -I
option you should be using #include "split.h"
in your source file, and your dependency should be ../StdCUtil/split.h
.
Another option:
INC_DIR = ../StdCUtil
CFLAGS=-c -Wall -I$(INC_DIR)/.. # Ugly!
DEPS = $(INC_DIR)/split.h
With this your #include
directive would remain as #include "StdCUtil/split.h"
.
Yet another option is to place your makefile in the parent directory:
root
|____Makefile
|
|___Core
| |____DBC.cpp
| |____Lock.cpp
| |____Trace.cpp
|
|___StdCUtil
|___split.h
With this layout it is common to put the object files (and possibly the executable) in a subdirectory that is parallel to your Core
and StdCUtil
directories. Object
, for example. With this, your makefile becomes:
INC_DIR = StdCUtil
SRC_DIR = Core
OBJ_DIR = Object
CFLAGS = -c -Wall -I.
SRCS = $(SRC_DIR)/Lock.cpp $(SRC_DIR)/DBC.cpp $(SRC_DIR)/Trace.cpp
OBJS = $(OBJ_DIR)/Lock.o $(OBJ_DIR)/DBC.o $(OBJ_DIR)/Trace.o
# Note: The above will soon get unwieldy.
# The wildcard and patsubt commands will come to your rescue.
DEPS = $(INC_DIR)/split.h
# Note: The above will soon get unwieldy.
# You will soon want to use an automatic dependency generator.
all: $(OBJS)
$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp
$(CC) $(CFLAGS) -c $< -o $@
$(OBJ_DIR)/Trace.o: $(DEPS)
use getBoundingClientRect
if $el
is the actual DOM object:
var top = $el.getBoundingClientRect().top;
Fiddle will show that this will get the same value that jquery's offset top will give you
Edit: as mentioned in comments this does not account for scrolled content, below is the code that jQuery uses
https://github.com/jquery/jquery/blob/master/src/offset.js (5/13/2015)
offset: function( options ) {
//...
var docElem, win, rect, doc,
elem = this[ 0 ];
if ( !elem ) {
return;
}
rect = elem.getBoundingClientRect();
// Make sure element is not hidden (display: none) or disconnected
if ( rect.width || rect.height || elem.getClientRects().length ) {
doc = elem.ownerDocument;
win = getWindow( doc );
docElem = doc.documentElement;
return {
top: rect.top + win.pageYOffset - docElem.clientTop,
left: rect.left + win.pageXOffset - docElem.clientLeft
};
}
}
Open Command Prompt inside your Application's source. Run the Command
npm run eject
Open your scripts/build.js file and add this at the beginning of the file after 'use strict' line
'use strict';
....
process.env.PUBLIC_URL = './'
// Provide the current path
.....
Open your config/paths.js and modify the buildApp property in the exports object to your destination folder. (Here, I provide 'react-app-scss' as the destination folder)
module.exports = {
.....
appBuild: resolveApp('build/react-app-scss'),
.....
}
Run
npm run build
Note: Running Platform dependent scripts are not advisable
My favorite is to look at the boot messages. If it's been recently booted try running /etc/dmesg. Otherwise find the boot messages, logged in /var/adm or some place in /var.
This gets the size by forcing the array into a scalar context, in which it is evaluated as its size:
print scalar @arr;
This is another way of forcing the array into a scalar context, since it's being assigned to a scalar variable:
my $arrSize = @arr;
This gets the index of the last element in the array, so it's actually the size minus 1 (assuming indexes start at 0, which is adjustable in Perl although doing so is usually a bad idea):
print $#arr;
This last one isn't really good to use for getting the array size. It would be useful if you just want to get the last element of the array:
my $lastElement = $arr[$#arr];
Also, as you can see here on Stack Overflow, this construct isn't handled correctly by most syntax highlighters...
If like me, you are using some micro VM lacking of memory, creating a swap file does the trick:
#Check free memory before
free -m
mkdir -p /var/_swap_
cd /var/_swap_
#Here, 1M * 2000 ~= 2GB of swap memory. Feel free to add MORE
dd if=/dev/zero of=swapfile bs=1M count=2000
chmod 600 swapfile
mkswap swapfile
swapon swapfile
#Automatically mount this swap partition at startup
echo "/var/_swap_/swapfile none swap sw 0 0" >> /etc/fstab
#Check free memory after
free -m
As several comments pointed out, don't forget to add sudo if you don't work as root.
btw, feel free to select another location/filename/size for the file.
/var
is probably not the best place, but I don't know which place would be, and rarely care since tiny servers are mostly used for testing purposes.
Use String.Replace()
if you just want to replace the dots from string. Alternative would be to use Pattern-Matcher
with StringBuilder
, this gives you more flexibility as you can find groups that are between dots. If using the latter, i would recommend that you ignore empty entries with "\\.+"
.
public static int count(String str, String regex) {
int i = 0;
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
while (m.find()) {
m.group();
i++;
}
return i;
}
public static void main(String[] args) {
int i = 0, j = 0, k = 0;
String str = "-.-..-...-.-.--..-k....k...k..k.k-.-";
// this will just remove dots
System.out.println(str.replaceAll("\\.", ""));
// this will just remove sequences of ".." dots
System.out.println(str.replaceAll("\\.{2}", ""));
// this will just remove sequences of dots, and gets
// multiple of dots as 1
System.out.println(str.replaceAll("\\.+", ""));
/* for this to be more obvious, consider following */
System.out.println(count(str, "\\."));
System.out.println(count(str, "\\.{2}"));
System.out.println(count(str, "\\.+"));
}
The output will be:
--------kkkkk--
-.--.-.-.---kk.kk.k-.-
--------kkkkk--
21
7
11
you can achieve this easily without writing Js. Just add an attribute called data-page-length={put your number here}. see example below, I used 100 for example
<table id="datatable-keytable" data-page-length='100' class="p-table table table-bordered" width="100%">
For Notepad++ 64-bit:
There is an unreleased 64-bit version of this plugin. You can download the DLL from here, drop it under Notepad++/plugins/NppTextFX directory and restart Notepad++. You will need to create the NppTextFX directory first though.
As per this GitHub issue, there might be some bugs lurking around. If you run into any, feel free to raise a GitHub ticket for each, as the author (HQJaTu) is recommending. As per the author, the code behind this binary is found on this branch.
Tested on Notepad++ v7.5.8 (64-bit, Build time: Jul 23 2018)